code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
using System.Linq.Expressions; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Query.Expressions; using Microsoft.EntityFrameworkCore.Utilities; using EFCore.SqlCe.Infrastructure.Internal; using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors; using Microsoft.EntityFrameworkCore.Query; namespace EFCore.SqlCe.Query.ExpressionVisitors { /// <summary> /// A factory for creating instances of <see cref="SqlCeTranslatingExpressionVisitor" />. /// </summary> public class SqlCeTranslatingExpressionVisitorFactory : ISqlTranslatingExpressionVisitorFactory { private readonly SqlTranslatingExpressionVisitorDependencies _dependencies; private readonly ISqlCeOptions _sqlCeOptions; /// <summary> /// Creates a new instance of <see cref="SqlTranslatingExpressionVisitorFactory" />. /// </summary> /// <param name="dependencies"> The relational annotation provider. </param> /// <param name="sqlCeOptions">SqlCe options</param> public SqlCeTranslatingExpressionVisitorFactory( [NotNull] SqlTranslatingExpressionVisitorDependencies dependencies, [NotNull] ISqlCeOptions sqlCeOptions) { Check.NotNull(dependencies, nameof(dependencies)); Check.NotNull(sqlCeOptions, nameof(sqlCeOptions)); _dependencies = dependencies; _sqlCeOptions = sqlCeOptions; } /// <summary> /// Creates a new SqlTranslatingExpressionVisitor. /// </summary> /// <param name="queryModelVisitor"> The query model visitor. </param> /// <param name="targetSelectExpression"> The target select expression. </param> /// <param name="topLevelPredicate"> The top level predicate. </param> /// <param name="inProjection"> true if we are translating a projection. </param> /// <returns> /// A SqlTranslatingExpressionVisitor. /// </returns> public virtual SqlTranslatingExpressionVisitor Create( RelationalQueryModelVisitor queryModelVisitor, SelectExpression targetSelectExpression = null, Expression topLevelPredicate = null, bool inProjection = false) => new SqlCeTranslatingExpressionVisitor( _dependencies, _sqlCeOptions, Check.NotNull(queryModelVisitor, nameof(queryModelVisitor)), targetSelectExpression, topLevelPredicate, inProjection); } }
ErikEJ/EntityFramework.SqlServerCompact
src/Provider40/Query/ExpressionVisitors/SqlCeTranslatingExpressionVisitorFactory.cs
C#
apache-2.0
2,569
[//]: # (title: Using builders with builder type inference) Kotlin supports _builder type inference_ (or builder inference), which can come in useful when you are working with generic builders. It helps the compiler infer the type arguments of a builder call based on the type information about other calls inside its lambda argument. Consider this example of [`buildMap()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/build-map.html) usage: ```kotlin fun addEntryToMap(baseMap: Map<String, Number>, additionalEntry: Pair<String, Int>?) { val myMap = buildMap { putAll(baseMap) if (additionalEntry != null) { put(additionalEntry.first, additionalEntry.second) } } } ``` There is not enough type information here to infer type arguments in a regular way, but builder inference can analyze the calls inside the lambda argument. Based on the type information about `putAll()` and `put()` calls, the compiler can automatically infer type arguments of the `buildMap()` call into `String` and `Number`. Builder inference allows to omit type arguments while using generic builders. ## Writing your own builders ### Requirements for enabling builder inference > Before Kotlin 1.6.0, enabling builder inference for a builder function required the [`@BuilderInference`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-builder-inference/) > annotation to be present on a builder lambda parameter. In 1.6.0, you can omit the annotation if both you and your > builder's clients are using the compiler option `-Xenable-builder-inference`. > {type="note"} To let builder inference work for your own builder, make sure its declaration has a builder lambda parameter of a function type with a receiver. There are also two requirements for the receiver type: 1. It should use the type arguments that builder inference is supposed to infer. For example: ```kotlin fun <V> buildList(builder: MutableList<V>.() -> Unit) { ... } ``` > Note that passing the type parameter's type directly like `fun <T> myBuilder(builder: T.() -> Unit)` is not yet supported. > {type="note"} 2. It should provide public members or extensions that contain the corresponding type parameters in their signature. For example: ```kotlin class ItemHolder<T> { private val items = mutableListOf<T>() fun addItem(x: T) { items.add(x) } fun getLastItem(): T? = items.lastOrNull() } fun <T> ItemHolder<T>.addAllItems(xs: List<T>) { xs.forEach { addItem(it) } } fun <T> itemHolderBuilder(builder: ItemHolder<T>.() -> Unit): ItemHolder<T> = ItemHolder<T>().apply(builder) fun test(s: String) { val itemHolder1 = itemHolderBuilder { // Type of itemHolder1 is ItemHolder<String> addItem(s) } val itemHolder2 = itemHolderBuilder { // Type of itemHolder2 is ItemHolder<String> addAllItems(listOf(s)) } val itemHolder3 = itemHolderBuilder { // Type of itemHolder3 is ItemHolder<String?> val lastItem: String? = getLastItem() // ... } } ``` ### Supported features Builder inference supports: * Inferring several type arguments ```kotlin fun <K, V> myBuilder(builder: MutableMap<K, V>.() -> Unit): Map<K, V> { ... } ``` * Inferring type arguments of several builder lambdas within one call including interdependent ones ```kotlin fun <K, V> myBuilder( listBuilder: MutableList<V>.() -> Unit, mapBuilder: MutableMap<K, V>.() -> Unit ): Pair<List<V>, Map<K, V>> = mutableListOf<V>().apply(listBuilder) to mutableMapOf<K, V>().apply(mapBuilder) fun main() { val result = myBuilder( { add(1) }, { put("key", 2) } ) // result has Pair<List<Int>, Map<String, Int>> type } ``` * Inferring type arguments whose type parameters are lambda's parameter or return types ```kotlin fun <K, V> myBuilder1( mapBuilder: MutableMap<K, V>.() -> K ): Map<K, V> = mutableMapOf<K, V>().apply { mapBuilder() } fun <K, V> myBuilder2( mapBuilder: MutableMap<K, V>.(K) -> Unit ): Map<K, V> = mutableMapOf<K, V>().apply { mapBuilder(2 as K) } fun main() { // result1 has the Map<Long, String> type inferred val result1 = myBuilder1 { put(1L, "value") 2 } val result2 = myBuilder2 { put(1, "value 1") // You can use `it` as "postponed type variable" type // See the details in the section below put(it, "value 2") } } ``` ## How builder inference works ### Postponed type variables Builder inference works in terms of _postponed type variables_, which appear inside the builder lambda during builder inference analysis. A postponed type variable is a type argument's type, which is in the process of inferring. The compiler uses it to collect type information about the type argument. Consider the example with [`buildList()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/build-list.html): ```kotlin val result = buildList { val x = get(0) } ``` Here `x` has a type of postponed type variable: the `get()` call returns a value of type `E`, but `E` itself is not yet fixed. At this moment, a concrete type for `E` is unknown. When a value of a postponed type variable gets associated with a concrete type, builder inference collects this information to infer the resulting type of the corresponding type argument at the end of the builder inference analysis. For example: ```kotlin val result = buildList { val x = get(0) val y: String = x } // result has the List<String> type inferred ``` After the postponed type variable gets assigned to a variable of the `String` type, builder inference gets the information that `x` is a subtype of `String`. This assignment is the last statement in the builder lambda, so the builder inference analysis ends with the result of inferring the type argument `E` into `String`. Note that you can always call `equals()`, `hashCode()`, and `toString()` functions with a postponed type variable as a receiver. ### Contributing to builder inference results Builder inference can collect different varieties of type information that contribute to the analysis result. It considers: * Calling methods on a lambda's receiver that use the type parameter's type ```kotlin val result = buildList { // Type argument is inferred into String based on the passed "value" argument add("value") } // result has the List<String> type inferred ``` * Specifying the expected type for calls that return the type parameter's type ```kotlin val result = buildList { // Type argument is inferred into Float based on the expected type val x: Float = get(0) } // result has the List<Float> type ``` ```kotlin class Foo<T> { val items = mutableListOf<T>() } fun <K> myBuilder(builder: Foo<K>.() -> Unit): Foo<K> = Foo<K>().apply(builder) fun main() { val result = myBuilder { val x: List<CharSequence> = items // ... } // result has the Foo<CharSequence> type } ``` * Passing postponed type variables' types into methods that expect concrete types ```kotlin fun takeMyLong(x: Long) { ... } fun String.isMoreThat3() = length > 3 fun takeListOfStrings(x: List<String>) { ... } fun main() { val result1 = buildList { val x = get(0) takeMyLong(x) } // result1 has the List<Long> type val result2 = buildList { val x = get(0) val isLong = x.isMoreThat3() // ... } // result2 has the List<String> type val result3 = buildList { takeListOfStrings(this) } // result3 has the List<String> type } ``` * Taking a callable reference to the lambda receiver's member ```kotlin fun main() { val result = buildList { val x: KFunction1<Int, Float> = ::get } // result has the List<Float> type } ``` ```kotlin fun takeFunction(x: KFunction1<Int, Float>) { ... } fun main() { val result = buildList { takeFunction(::get) } // result has the List<Float> type } ``` At the end of the analysis, builder inference considers all collected type information and tries to merge it into the resulting type. See the example. ```kotlin val result = buildList { // Inferring postponed type variable E // Considering E is Number or a subtype of Number val n: Number? = getOrNull(0) // Considering E is Int or a supertype of Int add(1) // E gets inferred into Int } // result has the List<Int> type ``` The resulting type is the most specific type that corresponds to the type information collected during the analysis. If the given type information is contradictory and cannot be merged, the compiler reports an error. Note that the Kotlin compiler uses builder inference only if regular type inference cannot infer a type argument. This means you can contribute type information outside a builder lambda, and then builder inference analysis is not required. Consider the example: ```kotlin fun someMap() = mutableMapOf<CharSequence, String>() fun <E> MutableMap<E, String>.f(x: MutableMap<E, String>) { ... } fun main() { val x: Map<in String, String> = buildMap { put("", "") f(someMap()) // Type mismatch (required String, found CharSequence) } } ``` Here a type mismatch appears because the expected type of the map is specified outside the builder lambda. The compiler analyzes all the statements inside with the fixed receiver type `Map<in String, String>`.
hltj/kotlin-web-site-cn
docs/topics/using-builders-with-builder-inference.md
Markdown
apache-2.0
9,704
<html lang='und'> <!-- ** ** Copyright 2006, 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. */ --> <p>ᐃ ᐄ ᐅ ᐆ ᐊ ᐋ ᐱ ᐲ ᐳ ᐴ ᐸ ᐹ ᑉ ᑎ ᑏ ᑐ ᑑ ᑕ ᑖ ᑦ ᑭ ᑮ ᑯ ᑰ ᑲ ᑳ ᒃ ᒋ ᒌ ᒍ ᒎ ᒐ ᒑ ᒡ ᒥ ᒦ ᒧ ᒨ ᒪ ᒫ ᒻ ᓂ ᓃ ᓄ ᓅ ᓇ ᓈ ᓐ ᓕ ᓖ ᓗ ᓘ ᓚ ᓛ ᓪ ᓯ ᓰ ᓱ ᓲ ᓴ</p> </html>
googlei18n/noto-source
test/CanadianAboriginal/fontdiff-und-Cans_chars.html
HTML
apache-2.0
900
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.gcp.pubsub; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.beam.sdk.coders.ByteArrayCoder; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.CustomCoder; /** A coder for PubsubMessage treating the raw bytes being decoded as the message's payload. */ public class PubsubMessagePayloadOnlyCoder extends CustomCoder<PubsubMessage> { private static final Coder<byte[]> PAYLOAD_CODER = ByteArrayCoder.of(); public static PubsubMessagePayloadOnlyCoder of() { return new PubsubMessagePayloadOnlyCoder(); } @Override public void encode(PubsubMessage value, OutputStream outStream) throws IOException { encode(value, outStream, Context.NESTED); } @Override public void encode(PubsubMessage value, OutputStream outStream, Context context) throws IOException { PAYLOAD_CODER.encode(value.getPayload(), outStream, context); } @Override public PubsubMessage decode(InputStream inStream) throws IOException { return decode(inStream, Context.NESTED); } @Override public PubsubMessage decode(InputStream inStream, Context context) throws IOException { return new PubsubMessage(PAYLOAD_CODER.decode(inStream, context), ImmutableMap.of()); } }
tgroh/incubator-beam
sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/pubsub/PubsubMessagePayloadOnlyCoder.java
Java
apache-2.0
2,160
$packageName = 'drivergenius' $installerType = 'exe' $silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' $url = 'http://www.driver-soft.com/products/DG_Setup.exe' $checksum = '115aea224d55e3235f2a783df2aafc269b5c2a44ba5e77bd752cb122594d3bc2' $checksumType = 'sha256' $validExitCodes = @(0) Install-ChocolateyPackage -PackageName "$packageName" ` -FileType "$installerType" ` -SilentArgs "$silentArgs" ` -Url "$url" ` -ValidExitCodes $validExitCodes ` -Checksum "$checksum" ` -ChecksumType "$checksumType"
dtgm/chocolatey-packages
automatic/_output/drivergenius/17.0.0.139/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
674
--- layout: docwithnav assignees: - ashvayka title: Tenants description: ThingsBoard Tenants management --- {% include docs/user-guide/ui/tenants.md %}
volodymyr-babak/thingsboard.github.io
docs/user-guide/ui/tenants.md
Markdown
apache-2.0
153
# # Author:: AJ Christensen (<aj@hjksolutions.com>) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # 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. # require 'chef/mixin/shell_out' require 'chef/provider/service' require 'chef/provider/service/simple' require 'chef/mixin/command' class Chef class Provider class Service class Init < Chef::Provider::Service::Simple include Chef::Mixin::ShellOut def initialize(new_resource, run_context) super @init_command = "/etc/init.d/#{@new_resource.service_name}" end def define_resource_requirements # do not call super here, inherit only shared_requirements shared_resource_requirements requirements.assert(:start, :stop, :restart, :reload) do |a| a.assertion do custom_command_for_action?(action) || ::File.exist?(default_init_command) end a.failure_message(Chef::Exceptions::Service, "#{default_init_command} does not exist!") a.whyrun("Init script '#{default_init_command}' doesn't exist, assuming a prior action would have created it.") do # blindly assume that the service exists but is stopped in why run mode: @status_load_success = false end end end def start_service if @new_resource.start_command super else shell_out!("#{default_init_command} start") end end def stop_service if @new_resource.stop_command super else shell_out!("#{default_init_command} stop") end end def restart_service if @new_resource.restart_command super elsif @new_resource.supports[:restart] shell_out!("#{default_init_command} restart") else stop_service sleep 1 start_service end end def reload_service if @new_resource.reload_command super elsif @new_resource.supports[:reload] shell_out!("#{default_init_command} reload") end end end end end end
ccope/chef
lib/chef/provider/service/init.rb
Ruby
apache-2.0
2,775
package com.ctrip.xpipe.redis.console.migration.status.migration.statemachine; /** * @author wenchao.meng * <p> * Aug 31, 2017 */ public interface StateActionState { void tryAction(); void tryRollback(); void actionDone(); void rollbackDone(); boolean allowTimeout(); void timeout(); }
Yiiinsh/x-pipe
redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/migration/status/migration/statemachine/StateActionState.java
Java
apache-2.0
337
/* * Copyright 2001-2016 Artima, 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 org.scalatest.prop import org.scalactic.anyvals.{PosInt,PosZInt} /** * The results of a call to [[CommonGenerators.classify]]. * * The `classify` function takes a [[PartialFunction]] and a [[Generator]], and organizes the values created * by the Generator based on the PartialFunction. It returns this data structure, which describes * how many of the values went into each bucket. * * If the PartialFunction did not cover all the possible generated values, then the [[totals]] field will * not include the others, and the numbers in totals will add up to less than [[totalGenerated]]. * * @param totalGenerated How many values were actually created by the Generator overall. * @param totals For each of the buckets defined in the PartialFunction, how many values belonged in each one. */ case class Classification(val totalGenerated: PosInt, val totals: Map[String, PosZInt]) { /** * For each bucket, what fraction of the generated values fell into it? * * @return Exactly what proportion of the values fell into each bucket. */ def portions: Map[String, Double] = totals.mapValues(count => count.toDouble / totalGenerated.toDouble).toMap /** * For each bucket, what percentage of the generated values fell into it? * * This is essentially a lower-precision but easier-to-understand variant of [[portions]]. * * @return Approximately what proportion of the values fell into each bucket. */ def percentages: Map[String, PosZInt] = (totals mapValues { count => PosZInt.ensuringValid((count * 100.0 / totalGenerated).round.toInt) }).toMap override def toString = { val lines = percentages map { case (classification, percentage) => s"${percentage.value}% $classification" } lines.mkString("\n") } }
scalatest/scalatest
jvm/common-test/src/main/scala/org/scalatest/prop/Classification.scala
Scala
apache-2.0
2,414
/* * * 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.flex.compiler.tree; /** * Constants used to identify AST nodes to the BURM. */ public enum ASTNodeID { UnknownID(null), AccessorID(null), AnonymousFunctionID(null), ArgumentID(null), ArgumentRestID("..."), ArrayIndexExpressionID(null), ArrayLiteralID(null), AssignmentExpressionID("="), BaseDefinitionID(null), BaseLiteralContainerID(null), BaseProjectRootID(null), BaseStatementExpressionID(null), BaseStatementID(null), BaseTypedDefinitionID(null), BaseVariableID("var"), BasicMetaID("metadata"), BindableVariableID("var"), BlockID("{"), BreakID("break"), CatchID("catch"), ClassID("class"), ClassReferenceID("class"), ComponentBlockID("{"), ConditionalID("?"), ConfigBlockID("CONFIG"), ContainerID(null), ContinueID("continue"), DefaultID("default"), DefaultXMLStatementID(null), DoWhileLoopID("do"), DynamicID("dynamic"), E4XFilterID(".("), ElseID("else"), EmbedID("embed"), EventTagID("event"), ExpressionID(null), ExternalProjectRootID(null), EventTriggerTagID(null), FXGFileID(null), FileID(null), FinalID("final"), FinallyID("finally"), FoldedExpressionID(null), ForLoopID("for"), ForEachLoopID("for"), FullNameID(null), FunctionCallID(null), FunctionID("function"), FunctionObjectID(null), GetterID("get"), GotoID("goto"), IdentifierID(null), IfStatementID("if"), ImportID("import"), IncludeContainerID("include"), InspectableTagID(null), InstructionListID(null), InterfaceID("interface"), KeywordDefaultXMLNamespaceID("default xml namespace"), KeywordConstID("const"), KeywordExtendsID("extends"), KeywordFunctionID("function"), KeywordImplementsID("implements"), KeywordGetID("get"), KeywordNewID("new"), KeywordSetID("set"), KeywordVarID("var"), KeywordClassID("class"), KeywordInterfaceID("interface"), LabledStatementID(null), LeafID(null), LiteralID(null), LiteralArrayID(null), LiteralBooleanID(null), LiteralIntegerID(null), LiteralIntegerZeroID(null), LiteralDoubleID(null), LiteralNullID("null"), LiteralNumberID(null), LiteralObjectID(null), LiteralRegexID(null), LiteralStringID(null), LiteralVoidID("void"), LiteralUintID(null), LiteralXMLID(null), LoopID(null), MemberAccessExpressionID(null), MemberedID(null), MetaTagID(null), MetaTagsID(null), ModifierID(null), ModifiersSetID(null), NativeID("native"), NamespaceAccessExpressionID(null), NamespaceIdentifierID(null), NamespaceID(null), NilID(null), NodeBaseID(null), NonResolvingIdentifierID(null), ObjectLiteralExpressionID(null), ObjectLiteralValuePairID(null), OperatorExpressionID(null), Op_EqualID("=="), Op_LessThanID("<"), Op_MultiplyID("*"), Op_ModuloID("%"), Op_DivideID("/"), Op_AddID("+"), Op_SubtractID("-"), Op_PreDecrID("--"), Op_PreIncrID("++"), Op_PostIncrID("++"), Op_PostDecrID("--"), Op_ColonID(":"), Op_ConditionalID("?"), Op_CommaID(","), Op_LeftShiftID("<<"), Op_LeftShiftAssignID("<<="), Op_RightShiftID(">>"), Op_RightShiftAssignID(">>="), Op_UnsignedRightShift(">>>"), Op_UnsignedRightShiftAssignID(">>>="), Op_DeleteID("delete"), Op_DescendantsID(".."), Op_TypeOfID("typeof"), Op_MultiplyAssignID("*="), Op_MemberAccessID(null), Op_AsID("as"), Op_IsID("is"), Op_InID("in"), Op_InstanceOfID("instanceof"), Op_AssignId("="), Op_NamespaceAccessID(null), Op_DivideAssignID("/="), Op_ModuloAssignID("%="), Op_BitwiseAndID("&"), Op_BitwiseAndAssignID("&="), Op_BitwiseXorID("^"), Op_BitwiseXorAssignID("^="), Op_BitwiseOrID("|"), Op_BitwiseOrAssignID("|="), Op_AddAssignID("+="), Op_SubtractAssignID("-="), Op_LogicalNotID("!"), Op_BitwiseNotID("~"), Op_GreaterThanID(">"), Op_GreaterThanEqualsID(">="), Op_LessThanEqualsID("<="), Op_StrictEqualID("==="), Op_NotEqualID("!="), Op_StrictNotEqualID("!=="), Op_LogicalAndID("&&"), Op_LogicalAndAssignID("&&="), Op_LogicalOrID("||"), Op_LogicalOrAssignID("||="), Op_AtID("at"), Op_FilterID(".("), Op_VoidID("void"), OverrideID("override"), PackageID("package"), PropertiesFileID(null), PropertiesEntryID(null), ProjectRootID(null), ProjectUnitID(null), LRUCacheID(null), QualifiedNameExpressionID(null), QualifiedNamespaceExpressionID(null), ReturnStatementID("return"), ResourceBundleTagID(null), SWCFileID(null), SWCNamespaceIdentifierID(null), SetterID("set"), SharedMetaTagsID(null), StaticID("static"), StopID("stop"), SuperID("super"), SwitchID("switch"), TerminalID(null), TernaryExpressionID("?"), ThisID("this"), ThrowsStatementID("throw"), TransparentContainerID(null), TreeID(null), TryID("try"), TypeID(null), TypedExpressionID(null), UseID("use"), VariableExpressionID(null), VariableID("var"), VectorInformationID(null), FunctionInfoID(null), ArgumentInfoID(null), VectorLiteralID(null), VectorID(null), WhileLoopID("while"), WithID("with"), XMLContentID(null), XMLListContentID(null), RuntimeNameExpressionID(null), VoidID("void"), /// MXML-specific nodes MXMLApplicationID(null, true), MXMLArrayID(null, true), MXMLBindingID(null, true), MXMLBindingAttributeID(null, true), MXMLBooleanID(null, true), MXMLClassID(null, true), MXMLClassDefinitionID(null, true), MXMLClearID(null, true), MXMLComponentID(null, true), MXMLConcatenatedDataBindingID(null, true), MXMLDataBindingID(null, true), MXMLDateID(null, true), MXMLDeclarationsID(null, true), MXMLDeferredInstanceID(null, true), MXMLDefinitionID(null, true), MXMLDesignLayerID(null, true), MXMLDocumentID(null, true), MXMLEmbedID(null, true), MXMLEffectSpecifierID(null, true), MXMLEventSpecifierID(null, true), MXMLFactoryID(null, true), MXMLFileID(null, true), MXMLFunctionID(null, true), MXMLHTTPServiceID(null, true), MXMLHTTPServiceRequestID(null, true), MXMLImplementsID(null, true), MXMLInstanceID(null, true), MXMLIntID(null, true), MXMLLibraryID(null, true), MXMLLiteralID(null, true), MXMLMetadataID(null, true), MXMLModelID(null, true), MXMLModelPropertyID(null, true), MXMLModelRootID(null, true), MXMLNumberID(null, true), MXMLObjectID(null, true), MXMLPrivateID(null, true), MXMLPropertySpecifierID(null, true), MXMLRegExpID(null, true), MXMLRemoteObjectID(null, true), MXMLRemoteObjectMethodID(null, true), MXMLReparentID(null, true), MXMLRepeaterID(null, true), MXMLResourceID(null, true), MXMLScriptID(null, true), MXMLStateID(null, true), MXMLStringID(null, true), MXMLStyleID(null, true), MXMLStyleSpecifierID(null, true), MXMLUintID(null, true), MXMLVectorID(null, true), MXMLWebServiceID(null, true), MXMLWebServiceOperationID(null, true), MXMLXMLID(null, true), MXMLXMLListID(null, true), InvalidNodeID(null); private boolean isMXMLNode = false; /** * Construct an ASTNodeID with a paraphrase. * * @param paraphrase - the paraphrase expression for this ID. */ ASTNodeID(String paraphrase) { this.paraphrase = paraphrase; } ASTNodeID(String paraphrase, boolean isMXMLNode) { this.paraphrase = paraphrase; this.isMXMLNode = isMXMLNode; } /** * The explicit paraphrase, if one was provided. */ private String paraphrase; /** * Get a paraphrase expression for this node ID. If the enum constructor * supplied an explicit paraphrase, use that; otherwise return a cleaned up * version of the enum itself. */ public String getParaphrase() { String result; if (this.paraphrase != null) { result = this.paraphrase; } else { result = this.toString(); // Make the text a little more readable // by trimming jargon suffixes and prefixes. if (result.endsWith("ID")) result = result.substring(0, result.lastIndexOf("ID")); if (result.endsWith("Id")) result = result.substring(0, result.lastIndexOf("Id")); if (result.startsWith("Keyword")) result = result.substring(7); else if (result.startsWith("Op_")) result = result.substring(3); } return result; } public boolean isMXMLNode() { return isMXMLNode; } }
adufilie/flex-falcon
compiler/src/org/apache/flex/compiler/tree/ASTNodeID.java
Java
apache-2.0
9,795
/* * JBoss, Home of Professional Open Source * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.tests.observers.pseudoscope; import javax.enterprise.event.Observes; import javax.enterprise.event.Reception; /** * @author Kirill Gaevskii */ @CustomSingletonScope public class CustomScopedBean { boolean observerCalled = false; public void onAnyDocumentEvent(@Observes(notifyObserver=Reception.IF_EXISTS) NotifyObserverTest event) { observerCalled = true; } public boolean isObserverCalled() { return observerCalled; } }
antoinesd/weld-core
tests-arquillian/src/test/java/org/jboss/weld/tests/observers/pseudoscope/CustomScopedBean.java
Java
apache-2.0
1,286
package provision import ( "bufio" "fmt" "net/http" "strings" "github.com/docker/machine/commands/mcndirs" "github.com/docker/machine/libmachine/auth" "github.com/docker/machine/libmachine/drivers" "github.com/docker/machine/libmachine/engine" "github.com/docker/machine/libmachine/log" "github.com/docker/machine/libmachine/mcnutils" "github.com/docker/machine/libmachine/provision/pkgaction" "github.com/docker/machine/libmachine/provision/serviceaction" "github.com/docker/machine/libmachine/state" "github.com/docker/machine/libmachine/swarm" ) const ( versionsUrl = "http://releases.rancher.com/os/versions.yml" isoUrl = "https://github.com/rancherio/os/releases/download/%s/machine-rancheros.iso" hostnameTmpl = `sudo mkdir -p /var/lib/rancher/conf/cloud-config.d/ sudo tee /var/lib/rancher/conf/cloud-config.d/machine-hostname.yml << EOF #cloud-config hostname: %s EOF ` ) func init() { Register("RancherOS", &RegisteredProvisioner{ New: NewRancherProvisioner, }) } func NewRancherProvisioner(d drivers.Driver) Provisioner { return &RancherProvisioner{ GenericProvisioner{ DockerOptionsDir: "/var/lib/rancher/conf", DaemonOptionsFile: "/var/lib/rancher/conf/docker", OsReleaseId: "rancheros", Driver: d, }, } } type RancherProvisioner struct { GenericProvisioner } func (provisioner *RancherProvisioner) Service(name string, action serviceaction.ServiceAction) error { command := fmt.Sprintf("sudo system-docker %s %s", action.String(), name) if _, err := provisioner.SSHCommand(command); err != nil { return err } return nil } func (provisioner *RancherProvisioner) Package(name string, action pkgaction.PackageAction) error { var packageAction string if name == "docker" && action == pkgaction.Upgrade { return provisioner.upgrade() } switch action { case pkgaction.Install: packageAction = "enabled" case pkgaction.Remove: packageAction = "disable" case pkgaction.Upgrade: // TODO: support upgrade packageAction = "upgrade" } command := fmt.Sprintf("sudo rancherctl service %s %s", packageAction, name) if _, err := provisioner.SSHCommand(command); err != nil { return err } return nil } func (provisioner *RancherProvisioner) Provision(swarmOptions swarm.SwarmOptions, authOptions auth.AuthOptions, engineOptions engine.EngineOptions) error { provisioner.SwarmOptions = swarmOptions provisioner.AuthOptions = authOptions provisioner.EngineOptions = engineOptions if provisioner.EngineOptions.StorageDriver == "" { provisioner.EngineOptions.StorageDriver = "overlay" } else if provisioner.EngineOptions.StorageDriver != "overlay" { return fmt.Errorf("Unsupported storage driver: %s", provisioner.EngineOptions.StorageDriver) } log.Debugf("Setting hostname %s", provisioner.Driver.GetMachineName()) if err := provisioner.SetHostname(provisioner.Driver.GetMachineName()); err != nil { return err } for _, pkg := range provisioner.Packages { log.Debugf("Installing package %s", pkg) if err := provisioner.Package(pkg, pkgaction.Install); err != nil { return err } } log.Debugf("Preparing certificates") provisioner.AuthOptions = setRemoteAuthOptions(provisioner) log.Debugf("Setting up certificates") if err := ConfigureAuth(provisioner); err != nil { return err } log.Debugf("Configuring swarm") if err := configureSwarm(provisioner, swarmOptions, provisioner.AuthOptions); err != nil { return err } return nil } func (provisioner *RancherProvisioner) SetHostname(hostname string) error { // /etc/hosts is bind mounted from Docker, this is hack to that the generic provisioner doesn't try to mv /etc/hosts if _, err := provisioner.SSHCommand("sed /127.0.1.1/d /etc/hosts > /tmp/hosts && cat /tmp/hosts | sudo tee /etc/hosts"); err != nil { return err } if err := provisioner.GenericProvisioner.SetHostname(hostname); err != nil { return err } if _, err := provisioner.SSHCommand(fmt.Sprintf(hostnameTmpl, hostname)); err != nil { return err } return nil } func (provisioner *RancherProvisioner) upgrade() error { switch provisioner.Driver.DriverName() { case "virtualbox": return provisioner.upgradeIso() default: log.Infof("Running upgrade") if _, err := provisioner.SSHCommand("sudo rancherctl os upgrade -f --no-reboot"); err != nil { return err } log.Infof("Upgrade succeeded, rebooting") // ignore errors here because the SSH connection will close provisioner.SSHCommand("sudo reboot") return nil } } func (provisioner *RancherProvisioner) upgradeIso() error { // Largely copied from Boot2Docker provisioner, we should find a way to share this code log.Info("Stopping machine to do the upgrade...") if err := provisioner.Driver.Stop(); err != nil { return err } if err := mcnutils.WaitFor(drivers.MachineInState(provisioner.Driver, state.Stopped)); err != nil { return err } machineName := provisioner.GetDriver().GetMachineName() log.Infof("Upgrading machine %s...", machineName) // TODO: Ideally, we should not read from mcndirs directory at all. // The driver should be able to communicate how and where to place the // relevant files. b2dutils := mcnutils.NewB2dUtils(mcndirs.GetBaseDir()) url, err := provisioner.getLatestISOURL() if err != nil { return err } if err := b2dutils.DownloadISOFromURL(url); err != nil { return err } // Copy the latest version of boot2docker ISO to the machine's directory if err := b2dutils.CopyIsoToMachineDir("", machineName); err != nil { return err } log.Infof("Starting machine back up...") if err := provisioner.Driver.Start(); err != nil { return err } return mcnutils.WaitFor(drivers.MachineInState(provisioner.Driver, state.Running)) } func (provisioner *RancherProvisioner) getLatestISOURL() (string, error) { log.Debugf("Reading %s", versionsUrl) resp, err := http.Get(versionsUrl) if err != nil { return "", err } defer resp.Body.Close() // Don't want to pull in yaml parser, we'll do this manually scanner := bufio.NewScanner(resp.Body) for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, "current: ") { log.Debugf("Found %s", line) return fmt.Sprintf(isoUrl, strings.Split(line, ":")[2]), err } } return "", fmt.Errorf("Failed to find current version") }
pdxjohnny/machine
libmachine/provision/rancheros.go
GO
apache-2.0
6,316
Bridge.merge(new System.Globalization.CultureInfo("quc", true), { englishName: "K'iche'", nativeName: "K'iche'", numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), { nanSymbol: "NeuN", negativeSign: "-", positiveSign: "+", negativeInfinitySymbol: "-Infinito", positiveInfinitySymbol: "Infinito", percentSymbol: "%", percentGroupSizes: [3], percentDecimalDigits: 2, percentDecimalSeparator: ".", percentGroupSeparator: ",", percentPositivePattern: 0, percentNegativePattern: 0, currencySymbol: "Q", currencyGroupSizes: [3], currencyDecimalDigits: 2, currencyDecimalSeparator: ".", currencyGroupSeparator: ",", currencyNegativePattern: 1, currencyPositivePattern: 0, numberGroupSizes: [3], numberDecimalDigits: 2, numberDecimalSeparator: ".", numberGroupSeparator: ",", numberNegativePattern: 1 }), dateTimeFormat: Bridge.merge(new System.Globalization.DateTimeFormatInfo(), { abbreviatedDayNames: ["juq'","kaq'","oxq'","kajq'","joq'","waqq'","wuqq'"], abbreviatedMonthGenitiveNames: ["nab'e","ukab'","urox","ukaj","uro","uwaq","uwuq","uwajxaq","ub'elej","ulaj","ujulaj","ukab'laj",""], abbreviatedMonthNames: ["nab'e","ukab'","urox","ukaj","uro","uwaq","uwuq","uwajxaq","ub'elej","ulaj","ujulaj","ukab'laj",""], amDesignator: "a.m.", dateSeparator: "/", dayNames: ["juq'ij","kaq'ij","oxq'ij","kajq'ij","joq'ij","waqq'ij","wuqq'ij"], firstDayOfWeek: 1, fullDateTimePattern: "dddd, dd' rech 'MMMM' rech 'yyyy h:mm:ss tt", longDatePattern: "dddd, dd' rech 'MMMM' rech 'yyyy", longTimePattern: "h:mm:ss tt", monthDayPattern: "d' rech 'MMMM", monthGenitiveNames: ["nab'e ik'","ukab' ik'","urox ik'","ukaj ik'","uro ik'","uwaq ik'","uwuq ik'","uwajxaq ik'","ub'elej ik'","ulaj ik'","ujulaj ik'","ukab'laj ik'",""], monthNames: ["nab'e ik'","ukab' ik'","urox ik'","ukaj ik'","uro ik'","uwaq ik'","uwuq ik'","uwajxaq ik'","ub'elej ik'","ulaj ik'","ujulaj ik'","ukab'laj ik'",""], pmDesignator: "p.m.", rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", shortDatePattern: "dd/MM/yyyy", shortestDayNames: ["ju","ka","ox","kj","jo","wa","wu"], shortTimePattern: "h:mm tt", sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", sortableDateTimePattern1: "yyyy'-'MM'-'dd", timeSeparator: ":", universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", yearMonthPattern: "MMMM' rech 'yyyy", roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz" }), TextInfo: Bridge.merge(new System.Globalization.TextInfo(), { ANSICodePage: 1252, CultureName: "quc-Latn-GT", EBCDICCodePage: 20284, IsRightToLeft: false, LCID: 1158, listSeparator: ",", MacCodePage: 10000, OEMCodePage: 850, IsReadOnly: true }) });
AndreyZM/Bridge
Bridge/Resources/Locales/quc.js
JavaScript
apache-2.0
3,111
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """## Functions for working with arbitrarily nested sequences of elements. NOTE(mrry): This fork of the `tensorflow.python.util.nest` module makes two changes: 1. It removes support for lists as a level of nesting in nested structures. 2. It adds support for `SparseTensorValue` as an atomic element. The motivation for this change is twofold: 1. It seems more natural for lists to be treated (e.g. in Dataset constructors) as tensors, rather than lists of (lists of...) tensors. 2. This is needed because `SparseTensorValue` is implemented as a `namedtuple` that would normally be flattened and we want to be able to create sparse tensor from `SparseTensorValue's similarly to creating tensors from numpy arrays. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import six as _six from tensorflow.python.framework import sparse_tensor as _sparse_tensor from tensorflow.python.util import _pywrap_utils from tensorflow.python.util import nest from tensorflow.python.util.compat import collections_abc as _collections_abc def _sorted(dict_): """Returns a sorted list of the dict keys, with error if keys not sortable.""" try: return sorted(list(dict_)) except TypeError: raise TypeError("nest only supports dicts with sortable keys.") def _yield_value(iterable): if isinstance(iterable, _collections_abc.Mapping): # Iterate through dictionaries in a deterministic order by sorting the # keys. Notice this means that we ignore the original order of `OrderedDict` # instances. This is intentional, to avoid potential bugs caused by mixing # ordered and plain dicts (e.g., flattening a dict but using a # corresponding `OrderedDict` to pack it back). for key in _sorted(iterable): yield iterable[key] elif isinstance(iterable, _sparse_tensor.SparseTensorValue): yield iterable else: for value in iterable: yield value # See the swig file (../../util/util.i) for documentation. is_sequence = _pywrap_utils.IsSequenceForData # See the swig file (../../util/util.i) for documentation. flatten = _pywrap_utils.FlattenForData def assert_same_structure(nest1, nest2, check_types=True): """Asserts that two structures are nested in the same way. Args: nest1: an arbitrarily nested structure. nest2: an arbitrarily nested structure. check_types: if `True` (default) types of sequences should be same as well. For dictionary, "type" of dictionary is considered to include its keys. In other words, two dictionaries with different keys are considered to have a different "type". If set to `False`, two iterables are considered same as long as they yield the elements that have same structures. Raises: ValueError: If the two structures do not have the same number of elements or if the two structures are not nested in the same way. TypeError: If the two structures differ in the type of sequence in any of their substructures. Only possible if `check_types` is `True`. """ _pywrap_utils.AssertSameStructureForData(nest1, nest2, check_types) def _packed_nest_with_indices(structure, flat, index): """Helper function for pack_nest_as. Args: structure: Substructure (tuple of elements and/or tuples) to mimic flat: Flattened values to output substructure for. index: Index at which to start reading from flat. Returns: The tuple (new_index, child), where: * new_index - the updated index into `flat` having processed `structure`. * packed - the subset of `flat` corresponding to `structure`, having started at `index`, and packed into the same nested format. Raises: ValueError: if `structure` contains more elements than `flat` (assuming indexing starts from `index`). """ packed = [] for s in _yield_value(structure): if is_sequence(s): new_index, child = _packed_nest_with_indices(s, flat, index) packed.append(nest._sequence_like(s, child)) # pylint: disable=protected-access index = new_index else: packed.append(flat[index]) index += 1 return index, packed def pack_sequence_as(structure, flat_sequence): """Returns a given flattened sequence packed into a nest. If `structure` is a scalar, `flat_sequence` must be a single-element list; in this case the return value is `flat_sequence[0]`. Args: structure: tuple or list constructed of scalars and/or other tuples/lists, or a scalar. Note: numpy arrays are considered scalars. flat_sequence: flat sequence to pack. Returns: packed: `flat_sequence` converted to have the same recursive structure as `structure`. Raises: ValueError: If nest and structure have different element counts. """ if not (is_sequence(flat_sequence) or isinstance(flat_sequence, list)): raise TypeError("flat_sequence must be a sequence") if not is_sequence(structure): if len(flat_sequence) != 1: raise ValueError("Structure is a scalar but len(flat_sequence) == %d > 1" % len(flat_sequence)) return flat_sequence[0] flat_structure = flatten(structure) if len(flat_structure) != len(flat_sequence): raise ValueError( "Could not pack sequence. Structure had %d elements, but flat_sequence " "had %d elements. Structure: %s, flat_sequence: %s." % (len(flat_structure), len(flat_sequence), structure, flat_sequence)) _, packed = _packed_nest_with_indices(structure, flat_sequence, 0) return nest._sequence_like(structure, packed) # pylint: disable=protected-access def map_structure(func, *structure, **check_types_dict): """Applies `func` to each entry in `structure` and returns a new structure. Applies `func(x[0], x[1], ...)` where x[i] is an entry in `structure[i]`. All structures in `structure` must have the same arity, and the return value will contain the results in the same structure. Args: func: A callable that accepts as many arguments are there are structures. *structure: scalar, or tuple or list of constructed scalars and/or other tuples/lists, or scalars. Note: numpy arrays are considered scalars. **check_types_dict: only valid keyword argument is `check_types`. If set to `True` (default) the types of iterables within the structures have to be same (e.g. `map_structure(func, [1], (1,))` raises a `TypeError` exception). To allow this set this argument to `False`. Returns: A new structure with the same arity as `structure`, whose values correspond to `func(x[0], x[1], ...)` where `x[i]` is a value in the corresponding location in `structure[i]`. If there are different sequence types and `check_types` is `False` the sequence types of the first structure will be used. Raises: TypeError: If `func` is not callable or if the structures do not match each other by depth tree. ValueError: If no structure is provided or if the structures do not match each other by type. ValueError: If wrong keyword arguments are provided. """ if not callable(func): raise TypeError("func must be callable, got: %s" % func) if not structure: raise ValueError("Must provide at least one structure") if check_types_dict: if "check_types" not in check_types_dict or len(check_types_dict) > 1: raise ValueError("Only valid keyword argument is check_types") check_types = check_types_dict["check_types"] else: check_types = True for other in structure[1:]: assert_same_structure(structure[0], other, check_types=check_types) flat_structure = (flatten(s) for s in structure) entries = zip(*flat_structure) return pack_sequence_as( structure[0], [func(*x) for x in entries]) def _yield_flat_up_to(shallow_tree, input_tree): """Yields elements `input_tree` partially flattened up to `shallow_tree`.""" if is_sequence(shallow_tree): for shallow_branch, input_branch in zip(_yield_value(shallow_tree), _yield_value(input_tree)): for input_leaf in _yield_flat_up_to(shallow_branch, input_branch): yield input_leaf else: yield input_tree def assert_shallow_structure(shallow_tree, input_tree, check_types=True): """Asserts that `shallow_tree` is a shallow structure of `input_tree`. That is, this function tests if the `input_tree` structure can be created from the `shallow_tree` structure by replacing its leaf nodes with deeper tree structures. Examples: The following code will raise an exception: ```python shallow_tree = ["a", "b"] input_tree = ["c", ["d", "e"], "f"] assert_shallow_structure(shallow_tree, input_tree) ``` The following code will not raise an exception: ```python shallow_tree = ["a", "b"] input_tree = ["c", ["d", "e"]] assert_shallow_structure(shallow_tree, input_tree) ``` Args: shallow_tree: an arbitrarily nested structure. input_tree: an arbitrarily nested structure. check_types: if `True` (default) the sequence types of `shallow_tree` and `input_tree` have to be the same. Raises: TypeError: If `shallow_tree` is a sequence but `input_tree` is not. TypeError: If the sequence types of `shallow_tree` are different from `input_tree`. Only raised if `check_types` is `True`. ValueError: If the sequence lengths of `shallow_tree` are different from `input_tree`. """ if is_sequence(shallow_tree): if not is_sequence(input_tree): raise TypeError( "If shallow structure is a sequence, input must also be a sequence. " "Input has type: %s." % type(input_tree)) if check_types and not isinstance(input_tree, type(shallow_tree)): raise TypeError( "The two structures don't have the same sequence type. Input " "structure has type %s, while shallow structure has type %s." % (type(input_tree), type(shallow_tree))) if len(input_tree) != len(shallow_tree): raise ValueError( "The two structures don't have the same sequence length. Input " "structure has length %s, while shallow structure has length %s." % (len(input_tree), len(shallow_tree))) if check_types and isinstance(shallow_tree, _collections_abc.Mapping): if set(input_tree) != set(shallow_tree): raise ValueError( "The two structures don't have the same keys. Input " "structure has keys %s, while shallow structure has keys %s." % (list(input_tree), list(shallow_tree))) input_tree = sorted(_six.iteritems(input_tree)) shallow_tree = sorted(_six.iteritems(shallow_tree)) for shallow_branch, input_branch in zip(shallow_tree, input_tree): assert_shallow_structure(shallow_branch, input_branch, check_types=check_types) def flatten_up_to(shallow_tree, input_tree): """Flattens `input_tree` up to `shallow_tree`. Any further depth in structure in `input_tree` is retained as elements in the partially flatten output. If `shallow_tree` and `input_tree` are not sequences, this returns a single-element list: `[input_tree]`. Use Case: Sometimes we may wish to partially flatten a nested sequence, retaining some of the nested structure. We achieve this by specifying a shallow structure, `shallow_tree`, we wish to flatten up to. The input, `input_tree`, can be thought of as having the same structure as `shallow_tree`, but with leaf nodes that are themselves tree structures. Examples: ```python input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] shallow_tree = [[True, True], [False, True]] flattened_input_tree = flatten_up_to(shallow_tree, input_tree) flattened_shallow_tree = flatten_up_to(shallow_tree, shallow_tree) # Output is: # [[2, 2], [3, 3], [4, 9], [5, 5]] # [True, True, False, True] ``` ```python input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]] shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]] input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree) input_tree_flattened = flatten(input_tree) # Output is: # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # ['a', 1, 'b', 2, 'c', 3, 'd', 4] ``` Non-Sequence Edge Cases: ```python flatten_up_to(0, 0) # Output: [0] flatten_up_to(0, [0, 1, 2]) # Output: [[0, 1, 2]] flatten_up_to([0, 1, 2], 0) # Output: TypeError flatten_up_to([0, 1, 2], [0, 1, 2]) # Output: [0, 1, 2] ``` Args: shallow_tree: a possibly pruned structure of input_tree. input_tree: an arbitrarily nested structure or a scalar object. Note, numpy arrays are considered scalars. Returns: A Python list, the partially flattened version of `input_tree` according to the structure of `shallow_tree`. Raises: TypeError: If `shallow_tree` is a sequence but `input_tree` is not. TypeError: If the sequence types of `shallow_tree` are different from `input_tree`. ValueError: If the sequence lengths of `shallow_tree` are different from `input_tree`. """ assert_shallow_structure(shallow_tree, input_tree) return list(_yield_flat_up_to(shallow_tree, input_tree)) def map_structure_up_to(shallow_tree, func, *inputs): """Applies a function or op to a number of partially flattened inputs. The `inputs` are flattened up to `shallow_tree` before being mapped. Use Case: Sometimes we wish to apply a function to a partially flattened sequence (for example when the function itself takes sequence inputs). We achieve this by specifying a shallow structure, `shallow_tree` we wish to flatten up to. The `inputs`, can be thought of as having the same structure as `shallow_tree`, but with leaf nodes that are themselves tree structures. This function, therefore, will return something with the same base structure as `shallow_tree`. Examples: ```python ab_tuple = collections.namedtuple("ab_tuple", "a, b") op_tuple = collections.namedtuple("op_tuple", "add, mul") inp_val = ab_tuple(a=2, b=3) inp_ops = ab_tuple(a=op_tuple(add=1, mul=2), b=op_tuple(add=2, mul=3)) out = map_structure_up_to(inp_val, lambda val, ops: (val + ops.add) * ops.mul, inp_val, inp_ops) # Output is: ab_tuple(a=6, b=15) ``` ```python data_list = [[2, 4, 6, 8], [[1, 3, 5, 7, 9], [3, 5, 7]]] name_list = ['evens', ['odds', 'primes']] out = map_structure_up_to( name_list, lambda name, sec: "first_{}_{}".format(len(sec), name), name_list, data_list) # Output is: ['first_4_evens', ['first_5_odds', 'first_3_primes']] ``` Args: shallow_tree: a shallow tree, common to all the inputs. func: callable which will be applied to each input individually. *inputs: arbitrarily nested combination of objects that are compatible with shallow_tree. The function `func` is applied to corresponding partially flattened elements of each input, so the function must support arity of `len(inputs)`. Raises: TypeError: If `shallow_tree` is a sequence but `input_tree` is not. TypeError: If the sequence types of `shallow_tree` are different from `input_tree`. ValueError: If the sequence lengths of `shallow_tree` are different from `input_tree`. Returns: result of repeatedly applying `func`, with same structure as `shallow_tree`. """ if not inputs: raise ValueError("Cannot map over no sequences") for input_tree in inputs: assert_shallow_structure(shallow_tree, input_tree) # Flatten each input separately, apply the function to corresponding elements, # then repack based on the structure of the first input. all_flattened_up_to = ( flatten_up_to(shallow_tree, input_tree) for input_tree in inputs) results = [func(*tensors) for tensors in zip(*all_flattened_up_to)] return pack_sequence_as(structure=shallow_tree, flat_sequence=results)
annarev/tensorflow
tensorflow/python/data/util/nest.py
Python
apache-2.0
16,774
/* * 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. */ var Thrift = { Type : { "STOP" : 0, "VOID" : 1, "BOOL" : 2, "BYTE" : 3, "I08" : 3, "DOUBLE" : 4, "I16" : 6, "I32" : 8, "I64" : 10, "STRING" : 11, "UTF7" : 11, "STRUCT" : 12, "MAP" : 13, "SET" : 14, "LIST" : 15, "UTF8" : 16, "UTF16" : 17 }, MessageType : { "CALL" : 1, "REPLY" : 2, "EXCEPTION" : 3 } } Thrift.TException = {} Thrift.TException.prototype = { initialize: function( message, code ) { this.message = message; this.code = (code == null) ? 0 : code; } } Thrift.TApplicationExceptionType = { "UNKNOWN" : 0, "UNKNOWN_METHOD" : 1, "INVALID_MESSAGE_TYPE" : 2, "WRONG_METHOD_NAME" : 3, "BAD_SEQUENCE_ID" : 4, "MISSING_RESULT" : 5 } Thrift.TApplicationException = function(message, code){ this.message = message this.code = (code == null) ? 0 : code } Thrift.TApplicationException.prototype = { read : function(input){ var ftype var fid var ret = input.readStructBegin(fname) this.fname = ret.fname while(1){ ret = input.readFieldBegin() if(ret.ftype == TType.STOP) break var fid = ret.fid switch(fid){ case 1: if( ret.ftype == Type.STRING ){ ret = input.readString() this.message = ret.value } else { ret = input.skip(ret.ftype) } break case 2: if( ret.ftype == Type.I32 ){ ret = input.readI32() this.code = ret.value } else { ret = input.skip(ret.ftype) } break default: ret = input.skip(ret.ftype) break } input.readFieldEnd() } input.readStructEnd() }, write: function(output){ var xfer = 0; output.writeStructBegin('TApplicationException'); if (this.message) { output.writeFieldBegin('message', Type.STRING, 1) output.writeString(this.getMessage()) output.writeFieldEnd() } if (this.code) { output.writeFieldBegin('type', Type.I32, 2) output.writeI32(this.code) output.writeFieldEnd() } output.writeFieldStop() output.writeStructEnd() }, getCode : function() { return this.code }, getMessage : function() { return this.message } } /** *If you do not specify a url then you must handle ajax on your own. *This is how to use js bindings in a async fashion. */ Thrift.Transport = function(url){ this.url = url this.wpos = 0 this.rpos = 0 this.send_buf = '' this.recv_buf = '' } Thrift.Transport.prototype = { //Gets the browser specific XmlHttpRequest Object getXmlHttpRequestObject : function() { try { return new XMLHttpRequest() } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) {} throw "Your browser doesn't support the XmlHttpRequest object. Try upgrading to Firefox." }, flush : function(){ //async mode if(this.url == undefined || this.url == '') return this.send_buf; var xreq = this.getXmlHttpRequestObject() if (xreq.overrideMimeType) xreq.overrideMimeType("application/json") xreq.open("POST", this.url, false) xreq.send(this.send_buf) if (xreq.readyState != 4) throw "encountered an unknown ajax ready state: "+xreq.readyState if (xreq.status != 200) throw "encountered a unknown request status: "+xreq.status this.recv_buf = xreq.responseText this.recv_buf_sz = this.recv_buf.length this.wpos = this.recv_buf.length this.rpos = 0 }, setRecvBuffer : function(buf){ this.recv_buf = buf this.recv_buf_sz = this.recv_buf.length this.wpos = this.recv_buf.length this.rpos = 0 }, isOpen : function() { return true }, open : function() {}, close: function() {}, read : function(len) { var avail = this.wpos - this.rpos if(avail == 0) return '' var give = len if(avail < len) give = avail var ret = this.read_buf.substr(this.rpos,give) this.rpos += give //clear buf when complete? return ret }, readAll : function() { return this.recv_buf }, write : function(buf){ this.send_buf = buf }, getSendBuffer : function(){ return this.send_buf } } Thrift.Protocol = function(transport){ this.transport = transport } Thrift.Protocol.Type = {} Thrift.Protocol.Type[ Thrift.Type.BOOL ] = '"tf"' Thrift.Protocol.Type[ Thrift.Type.BYTE ] = '"i8"' Thrift.Protocol.Type[ Thrift.Type.I16 ] = '"i16"' Thrift.Protocol.Type[ Thrift.Type.I32 ] = '"i32"' Thrift.Protocol.Type[ Thrift.Type.I64 ] = '"i64"' Thrift.Protocol.Type[ Thrift.Type.DOUBLE ] = '"dbl"' Thrift.Protocol.Type[ Thrift.Type.STRUCT ] = '"rec"' Thrift.Protocol.Type[ Thrift.Type.STRING ] = '"str"' Thrift.Protocol.Type[ Thrift.Type.MAP ] = '"map"' Thrift.Protocol.Type[ Thrift.Type.LIST ] = '"lst"' Thrift.Protocol.Type[ Thrift.Type.SET ] = '"set"' Thrift.Protocol.RType = {} Thrift.Protocol.RType[ "tf" ] = Thrift.Type.BOOL Thrift.Protocol.RType[ "i8" ] = Thrift.Type.BYTE Thrift.Protocol.RType[ "i16"] = Thrift.Type.I16 Thrift.Protocol.RType[ "i32"] = Thrift.Type.I32 Thrift.Protocol.RType[ "i64"] = Thrift.Type.I64 Thrift.Protocol.RType[ "dbl"] = Thrift.Type.DOUBLE Thrift.Protocol.RType[ "rec"] = Thrift.Type.STRUCT Thrift.Protocol.RType[ "str"] = Thrift.Type.STRING Thrift.Protocol.RType[ "map"] = Thrift.Type.MAP Thrift.Protocol.RType[ "lst"] = Thrift.Type.LIST Thrift.Protocol.RType[ "set"] = Thrift.Type.SET Thrift.Protocol.Version = 1 Thrift.Protocol.prototype = { getTransport : function(){ return this.transport }, //Write functions writeMessageBegin : function(name,messageType,seqid){ this.tstack = new Array() this.tpos = new Array(); this.tstack.push([Thrift.Protocol.Version,'"'+name+'"',messageType,seqid]); }, writeMessageEnd : function(){ var obj = this.tstack.pop() this.wobj = this.tstack.pop() this.wobj.push(obj) this.wbuf = "["+this.wobj.join(",")+"]"; this.transport.write(this.wbuf); }, writeStructBegin : function(name){ this.tpos.push(this.tstack.length) this.tstack.push({}) }, writeStructEnd : function(){ var p = this.tpos.pop() var struct = this.tstack[p] var str = "{" var first = true for( var key in struct ){ if(first) first = false; else str += ","; str += key+":"+struct[key] } str += "}" this.tstack[p] = str; }, writeFieldBegin : function(name,fieldType,fieldId){ this.tpos.push(this.tstack.length) this.tstack.push({"fieldId" : '"'+fieldId+'"', "fieldType" : Thrift.Protocol.Type[fieldType]}); }, writeFieldEnd : function(){ var value = this.tstack.pop() var fieldInfo = this.tstack.pop() this.tstack[this.tstack.length-1][fieldInfo.fieldId] = "{"+fieldInfo.fieldType+":"+value+"}" this.tpos.pop() }, writeFieldStop : function(){ //na }, writeMapBegin : function(keyType,valType,size){ //size is invalid, we'll set it on end. this.tpos.push(this.tstack.length) this.tstack.push([Thrift.Protocol.Type[keyType],Thrift.Protocol.Type[valType],0]) }, writeMapEnd : function(){ var p = this.tpos.pop() if(p == this.tstack.length) return; if((this.tstack.length - p - 1) % 2 != 0) this.tstack.push(""); var size = (this.tstack.length - p - 1)/2 this.tstack[p][this.tstack[p].length-1] = size; var map = "{" var first = true while( this.tstack.length > p+1 ){ var v = this.tstack.pop() var k = this.tstack.pop() if(first){ first = false }else{ map += "," } map += '"'+k+'":'+v } map += "}" this.tstack[p].push(map) this.tstack[p] = "["+this.tstack[p].join(",")+"]" }, writeListBegin : function(elemType,size){ this.tpos.push(this.tstack.length) this.tstack.push([Thrift.Protocol.Type[elemType],size]); }, writeListEnd : function(){ var p = this.tpos.pop() while( this.tstack.length > p+1 ){ var tmpVal = this.tstack[p+1] this.tstack.splice(p+1, 1) this.tstack[p].push(tmpVal) } this.tstack[p] = '['+this.tstack[p].join(",")+']'; }, writeSetBegin : function(elemType,size){ this.tpos.push(this.tstack.length) this.tstack.push([Thrift.Protocol.Type[elemType],size]); }, writeSetEnd : function(){ var p = this.tpos.pop() while( this.tstack.length > p+1 ){ var tmpVal = this.tstack[p+1] this.tstack.splice(p+1, 1) this.tstack[p].push(tmpVal) } this.tstack[p] = '['+this.tstack[p].join(",")+']'; }, writeBool : function(value){ this.tstack.push( value ? 1 : 0 ); }, writeByte : function(i8){ this.tstack.push(i8); }, writeI16 : function(i16){ this.tstack.push(i16); }, writeI32 : function(i32){ this.tstack.push(i32); }, writeI64 : function(i64){ this.tstack.push(i64); }, writeDouble : function(dbl){ this.tstack.push(dbl); }, writeString : function(str){ // We do not encode uri components for wire transfer: if(str === null) { this.tstack.push(null); } else { // concat may be slower than building a byte buffer var escapedString = ""; for(var i = 0; i < str.length; i++) { var ch = str.charAt(i); // a single double quote: " if(ch === '\"') { escapedString += '\\\"'; // write out as: \" } else if(ch === '\\') { // a single backslash: \ escapedString += '\\\\'; // write out as: \\ /* Currently escaped forward slashes break TJSONProtocol. * As it stands, we can simply pass forward slashes into our strings * across the wire without being escaped. * I think this is the protocol's bug, not thrift.js * } else if(ch === '/') { // a single forward slash: / * escapedString += '\\/'; // write out as \/ * } */ } else if(ch === '\b') { // a single backspace: invisible escapedString += '\\b'; // write out as: \b" } else if(ch === '\f') { // a single formfeed: invisible escapedString += '\\f'; // write out as: \f" } else if(ch === '\n') { // a single newline: invisible escapedString += '\\n'; // write out as: \n" } else if(ch === '\r') { // a single return: invisible escapedString += '\\r'; // write out as: \r" } else if(ch === '\t') { // a single tab: invisible escapedString += '\\t'; // write out as: \t" } else { escapedString += ch; // Else it need not be escaped } } this.tstack.push('"' + escapedString + '"'); } }, writeBinary : function(str){ this.writeString(str); }, // Reading functions readMessageBegin : function(name, messageType, seqid){ this.rstack = new Array() this.rpos = new Array() this.robj = eval(this.transport.readAll()) var r = {} var version = this.robj.shift() if(version != Thrift.Protocol.Version){ throw "Wrong thrift protocol version: "+version } r["fname"] = this.robj.shift() r["mtype"] = this.robj.shift() r["rseqid"] = this.robj.shift() //get to the main obj this.rstack.push(this.robj.shift()) return r }, readMessageEnd : function(){ }, readStructBegin : function(name){ var r = {} r["fname"] = '' //incase this is an array of structs if(this.rstack[this.rstack.length-1] instanceof Array) this.rstack.push(this.rstack[this.rstack.length-1].shift()) return r }, readStructEnd : function(){ if(this.rstack[this.rstack.length-2] instanceof Array) this.rstack.pop() }, readFieldBegin : function(){ var r = {}; var fid = -1 var ftype = Thrift.Type.STOP //get a fieldId for(var f in (this.rstack[this.rstack.length-1])){ if(f == null) continue fid = parseInt(f) this.rpos.push(this.rstack.length) var field = this.rstack[this.rstack.length-1][fid] //remove so we don't see it again delete this.rstack[this.rstack.length-1][fid] this.rstack.push(field) break } if(fid != -1){ //should only be 1 of these but this is the only //way to match a key for(var f in (this.rstack[this.rstack.length-1])){ if(Thrift.Protocol.RType[f] == null ) continue ftype = Thrift.Protocol.RType[f] this.rstack[this.rstack.length-1] = this.rstack[this.rstack.length-1][f] } } r["fname"] = '' r["ftype"] = ftype r["fid"] = fid return r }, readFieldEnd : function(){ var pos = this.rpos.pop() //get back to the right place in the stack while(this.rstack.length > pos) this.rstack.pop(); }, readMapBegin : function(keyType,valType,size){ var map = this.rstack.pop() var r = {}; r["ktype"] = Thrift.Protocol.RType[map.shift()] r["vtype"] = Thrift.Protocol.RType[map.shift()] r["size"] = map.shift() this.rpos.push(this.rstack.length) this.rstack.push(map.shift()) return r; }, readMapEnd : function(){ this.readFieldEnd() }, readListBegin : function(elemType,size){ var list = this.rstack[this.rstack.length-1] var r = {}; r["etype"] = Thrift.Protocol.RType[list.shift()]; r["size" ] = list.shift(); this.rpos.push(this.rstack.length); this.rstack.push(list) return r; }, readListEnd : function(){ this.readFieldEnd() }, readSetBegin : function(elemType,size){ return this.readListBegin(elemType,size) }, readSetEnd : function(){ return this.readListEnd() }, readBool : function(){ var r = this.readI32() if( r != null && r["value"] == "1" ){ r["value"] = true }else{ r["value"] = false } return r }, readByte : function(){ return this.readI32() }, readI16 : function(){ return this.readI32() }, readI32 : function(f){ if(f == undefined) f = this.rstack[this.rstack.length-1] var r = {} if(f instanceof Array){ if(f.length == 0) r["value"] = undefined else r["value"] = f.shift() }else if(f instanceof Object){ for(var i in f){ if(i == null) continue this.rstack.push(f[i]) delete f[i] r["value"] = i break } } else { r["value"] = f } return r }, readI64 : function(){ return this.readI32() }, readDouble : function(){ return this.readI32() }, readString : function(){ var r = this.readI32() return r }, readBinary : function(){ return this.readString() }, //Method to arbitrarily skip over data. skip : function(type){ throw "skip not supported yet" } }
milliondreams/brisk
demos/portfolio_manager/resources/thrift.js
JavaScript
apache-2.0
18,902
use v5.18; $_ = <<'HERE'; Out "Top 'Middle "Bottom" Middle' Out" HERE my @matches; say "Matched!" if m/ (?(DEFINE) (?<QUOTE_MARK> ['"]) (?<NOT_QUOTE_MARK> [^'"]) (?<QUOTE> ( (?<quote>(?&QUOTE_MARK)) (?: (?&NOT_QUOTE_MARK)++ (?&QUOTE) )* \g{quote} ) (?{ push @matches, $^N }) ) ) (?&QUOTE) /x;
mishin/presentation
regex_recursion/amelia_9.pl
Perl
apache-2.0
589
package docs.home.persistence; //#imports import akka.NotUsed; import com.lightbend.lagom.javadsl.api.ServiceCall; import com.lightbend.lagom.javadsl.persistence.jdbc.JdbcSession; import org.pcollections.PSequence; import org.pcollections.TreePVector; import javax.inject.Inject; import java.sql.PreparedStatement; import java.sql.ResultSet; //#imports public interface JdbcReadSideQuery { interface BlogService { public ServiceCall<NotUsed, PSequence<PostSummary>> getPostSummaries(); } //#service-impl public class BlogServiceImpl implements BlogService { private final JdbcSession jdbcSession; @Inject public BlogServiceImpl(JdbcSession jdbcSession) { this.jdbcSession = jdbcSession; } @Override public ServiceCall<NotUsed, PSequence<PostSummary>> getPostSummaries() { return request -> { return jdbcSession.withConnection(connection -> { try (PreparedStatement ps = connection.prepareStatement("SELECT id, title FROM blogsummary")) { try (ResultSet rs = ps.executeQuery()) { PSequence<PostSummary> summaries = TreePVector.empty(); while (rs.next()) { summaries = summaries.plus( new PostSummary(rs.getString("id"), rs.getString("title")) ); } return summaries; } } }); }; } } //#service-impl }
edouardKaiser/lagom
docs/manual/java/guide/cluster/code/docs/home/persistence/JdbcReadSideQuery.java
Java
apache-2.0
1,645
// Source :- https://gist.github.com/czue/464479 // Param "o": JavaScript object // Param "tab": tab or indent string for pretty output formatting omit or use empty string "" to supress. // Returns: XML string function json2xml(o, tab) { var toXml = function(v, name, ind) { var xml = ""; if (v instanceof Array) { for (var i=0, n=v.length; i<n; i++) xml += ind + toXml(v[i], name, ind+"\t") + "\n"; } else if (typeof(v) == "object") { var hasChild = false; xml += ind + "<" + name; for (var m in v) { if (m.charAt(0) == "@") xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\""; else hasChild = true; } xml += hasChild ? ">" : "/>"; if (hasChild) { for (var m in v) { if (m == "#text") xml += v[m]; else if (m == "#cdata") xml += "<![CDATA[" + v[m] + "]]>"; else if (m.charAt(0) != "@") xml += toXml(v[m], m, ind+"\t"); } xml += (xml.charAt(xml.length-1)=="\n"?ind:"") + "</" + name + ">"; } } else { xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">"; } return xml; }, xml=""; for (var m in o) xml += toXml(o[m], m, ""); return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, ""); } //Source :- https://goessner.net/download/prj/jsonxml/xml2json.js //Param "o": JavaScript object //Param "tab": tab or indent string for pretty output formatting omit or use empty string "" to supress. //Returns: JSON string function xml2json(xml, tab) { var X = { toObj: function(xml) { var o = {}; if (xml.nodeType==1) { // element node .. if (xml.attributes.length) // element with attributes .. for (var i=0; i<xml.attributes.length; i++) o["@"+xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue||"").toString(); if (xml.firstChild) { // element has child nodes .. var textChild=0, cdataChild=0, hasElementChild=false; for (var n=xml.firstChild; n; n=n.nextSibling) { if (n.nodeType==1) hasElementChild = true; else if (n.nodeType==3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text else if (n.nodeType==4) cdataChild++; // cdata section node } if (hasElementChild) { if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node .. X.removeWhite(xml); for (var n=xml.firstChild; n; n=n.nextSibling) { if (n.nodeType == 3) // text node o["#text"] = X.escape(n.nodeValue); else if (n.nodeType == 4) // cdata node o["#cdata"] = X.escape(n.nodeValue); else if (o[n.nodeName]) { // multiple occurence of element .. if (o[n.nodeName] instanceof Array) o[n.nodeName][o[n.nodeName].length] = X.toObj(n); else o[n.nodeName] = [o[n.nodeName], X.toObj(n)]; } else // first occurence of element.. o[n.nodeName] = X.toObj(n); } } else { // mixed content if (!xml.attributes.length) o = X.escape(X.innerXml(xml)); else o["#text"] = X.escape(X.innerXml(xml)); } } else if (textChild) { // pure text if (!xml.attributes.length) o = X.escape(X.innerXml(xml)); else o["#text"] = X.escape(X.innerXml(xml)); } else if (cdataChild) { // cdata if (cdataChild > 1) o = X.escape(X.innerXml(xml)); else for (var n=xml.firstChild; n; n=n.nextSibling) o["#cdata"] = X.escape(n.nodeValue); } } if (!xml.attributes.length && !xml.firstChild) o = null; } else if (xml.nodeType==9) { // document.node o = X.toObj(xml.documentElement); } else alert("unhandled node type: " + xml.nodeType); return o; }, toJson: function(o, name, ind) { var json = name ? ("\""+name+"\"") : ""; if (o instanceof Array) { for (var i=0,n=o.length; i<n; i++) o[i] = X.toJson(o[i], "", ind+"\t"); json += (name?":[":"[") + (o.length > 1 ? ("\n"+ind+"\t"+o.join(",\n"+ind+"\t")+"\n"+ind) : o.join("")) + "]"; } else if (o == null) json += (name&&":") + "null"; else if (typeof(o) == "object") { var arr = []; for (var m in o) arr[arr.length] = X.toJson(o[m], m, ind+"\t"); json += (name?":{":"{") + (arr.length > 1 ? ("\n"+ind+"\t"+arr.join(",\n"+ind+"\t")+"\n"+ind) : arr.join("")) + "}"; } else if (typeof(o) == "string") json += (name&&":") + "\"" + o.toString() + "\""; else json += (name&&":") + o.toString(); return json; }, innerXml: function(node) { var s = "" if ("innerHTML" in node) s = node.innerHTML; else { var asXml = function(n) { var s = ""; if (n.nodeType == 1) { s += "<" + n.nodeName; for (var i=0; i<n.attributes.length;i++) s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue||"").toString() + "\""; if (n.firstChild) { s += ">"; for (var c=n.firstChild; c; c=c.nextSibling) s += asXml(c); s += "</"+n.nodeName+">"; } else s += "/>"; } else if (n.nodeType == 3) s += n.nodeValue; else if (n.nodeType == 4) s += "<![CDATA[" + n.nodeValue + "]]>"; return s; }; for (var c=node.firstChild; c; c=c.nextSibling) s += asXml(c); } return s; }, escape: function(txt) { return txt.replace(/[\\]/g, "\\\\") .replace(/[\"]/g, '\\"') .replace(/[\n]/g, '\\n') .replace(/[\r]/g, '\\r'); }, removeWhite: function(e) { e.normalize(); for (var n = e.firstChild; n; ) { if (n.nodeType == 3) { // text node if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node var nxt = n.nextSibling; e.removeChild(n); n = nxt; } else n = n.nextSibling; } else if (n.nodeType == 1) { // element node X.removeWhite(n); n = n.nextSibling; } else // any other node n = n.nextSibling; } return e; } }; if (xml.nodeType == 9) // document node xml = xml.documentElement; var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t"); return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}"; }
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.visualdatamapper.diagram/HTMLPages/js/DataTypeConverter.js
JavaScript
apache-2.0
7,930
package cn.itcast_02; import java.util.HashMap; import java.util.Set; /* * HashMap<String,Student> * 键:String 学号 * 值:Student 学生对象 */ public class HashMapDemo3 { public static void main(String[] args) { // 创建集合对象 HashMap<String, Student> hm = new HashMap<String, Student>(); // 创建学生对象 Student s1 = new Student("周星驰", 58); Student s2 = new Student("刘德华", 55); Student s3 = new Student("梁朝伟", 54); Student s4 = new Student("刘嘉玲", 50); // 添加元素 hm.put("9527", s1); hm.put("9522", s2); hm.put("9524", s3); hm.put("9529", s4); // 遍历 Set<String> set = hm.keySet(); for (String key : set) { // 注意了:这次值不是字符串了 // String value = hm.get(key); Student value = hm.get(key); System.out.println(key + "---" + value.getName() + "---" + value.getAge()); } } }
aircjm/JavaSE
day18/code/day18_Map_Son/src/cn/itcast_02/HashMapDemo3.java
Java
apache-2.0
907
/* * Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase, * Shigeo Mitsunari * * The software is licensed under either the MIT License (below) or the Perl * license. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <assert.h> #include <stddef.h> #include <string.h> #ifdef __SSE4_2__ #ifdef _MSC_VER #include <nmmintrin.h> #else #include <x86intrin.h> #endif #endif #include "picohttpparser.h" /* $Id: a707070d11d499609f99d09f97535642cec910a8 $ */ #if __GNUC__ >= 3 #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else #define likely(x) (x) #define unlikely(x) (x) #endif #ifdef _MSC_VER #define ALIGNED(n) _declspec(align(n)) #else #define ALIGNED(n) __attribute__((aligned(n))) #endif #define IS_PRINTABLE_ASCII(c) ((unsigned char)(c)-040u < 0137u) #define CHECK_EOF() \ if (buf == buf_end) { \ *ret = -2; \ return NULL; \ } #define EXPECT_CHAR_NO_CHECK(ch) \ if (*buf++ != ch) { \ *ret = -1; \ return NULL; \ } #define EXPECT_CHAR(ch) \ CHECK_EOF(); \ EXPECT_CHAR_NO_CHECK(ch); #define ADVANCE_TOKEN(tok, toklen) \ do { \ const char *tok_start = buf; \ static const char ALIGNED(16) ranges2[] = "\000\040\177\177"; \ int found2; \ buf = findchar_fast(buf, buf_end, ranges2, sizeof(ranges2) - 1, &found2); \ if (!found2) { \ CHECK_EOF(); \ } \ while (1) { \ if (*buf == ' ') { \ break; \ } else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \ if ((unsigned char)*buf < '\040' || *buf == '\177') { \ *ret = -1; \ return NULL; \ } \ } \ ++buf; \ CHECK_EOF(); \ } \ tok = tok_start; \ toklen = buf - tok_start; \ } while (0) static const char *token_char_map = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\1\0\1\1\1\1\1\0\0\1\1\0\1\1\0\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0" "\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\1\1" "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\1\0\1\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges, size_t ranges_size, int *found) { *found = 0; #if __SSE4_2__ if (likely(buf_end - buf >= 16)) { __m128i ranges16 = _mm_loadu_si128((const __m128i *)ranges); size_t left = (buf_end - buf) & ~15; do { __m128i b16 = _mm_loadu_si128((const __m128i *)buf); int r = _mm_cmpestri(ranges16, ranges_size, b16, 16, _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS); if (unlikely(r != 16)) { buf += r; *found = 1; break; } buf += 16; left -= 16; } while (likely(left != 0)); } #else /* suppress unused parameter warning */ (void)buf_end; (void)ranges; (void)ranges_size; #endif return buf; } static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token, size_t *token_len, int *ret) { const char *token_start = buf; #ifdef __SSE4_2__ static const char ranges1[] = "\0\010" /* allow HT */ "\012\037" /* allow SP and up to but not including DEL */ "\177\177" /* allow chars w. MSB set */ ; int found; buf = findchar_fast(buf, buf_end, ranges1, sizeof(ranges1) - 1, &found); if (found) goto FOUND_CTL; #else /* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined */ while (likely(buf_end - buf >= 8)) { #define DOIT() \ do { \ if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \ goto NonPrintable; \ ++buf; \ } while (0) DOIT(); DOIT(); DOIT(); DOIT(); DOIT(); DOIT(); DOIT(); DOIT(); #undef DOIT continue; NonPrintable: if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { goto FOUND_CTL; } ++buf; } #endif for (;; ++buf) { CHECK_EOF(); if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { goto FOUND_CTL; } } } FOUND_CTL: if (likely(*buf == '\015')) { ++buf; EXPECT_CHAR('\012'); *token_len = buf - 2 - token_start; } else if (*buf == '\012') { *token_len = buf - token_start; ++buf; } else { *ret = -1; return NULL; } *token = token_start; return buf; } static const char *is_complete(const char *buf, const char *buf_end, size_t last_len, int *ret) { int ret_cnt = 0; buf = last_len < 3 ? buf : buf + last_len - 3; while (1) { CHECK_EOF(); if (*buf == '\015') { ++buf; CHECK_EOF(); EXPECT_CHAR('\012'); ++ret_cnt; } else if (*buf == '\012') { ++buf; ++ret_cnt; } else { ++buf; ret_cnt = 0; } if (ret_cnt == 2) { return buf; } } *ret = -2; return NULL; } #define PARSE_INT(valp_, mul_) \ if (*buf < '0' || '9' < *buf) { \ buf++; \ *ret = -1; \ return NULL; \ } \ *(valp_) = (mul_) * (*buf++ - '0'); #define PARSE_INT_3(valp_) \ do { \ int res_ = 0; \ PARSE_INT(&res_, 100) \ *valp_ = res_; \ PARSE_INT(&res_, 10) \ *valp_ += res_; \ PARSE_INT(&res_, 1) \ *valp_ += res_; \ } while (0) /* returned pointer is always within [buf, buf_end), or null */ static const char *parse_http_version(const char *buf, const char *buf_end, int *minor_version, int *ret) { /* we want at least [HTTP/1.<two chars>] to try to parse */ if (buf_end - buf < 9) { *ret = -2; return NULL; } EXPECT_CHAR_NO_CHECK('H'); EXPECT_CHAR_NO_CHECK('T'); EXPECT_CHAR_NO_CHECK('T'); EXPECT_CHAR_NO_CHECK('P'); EXPECT_CHAR_NO_CHECK('/'); EXPECT_CHAR_NO_CHECK('1'); EXPECT_CHAR_NO_CHECK('.'); PARSE_INT(minor_version, 1); return buf; } static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) { for (;; ++*num_headers) { CHECK_EOF(); if (*buf == '\015') { ++buf; EXPECT_CHAR('\012'); break; } else if (*buf == '\012') { ++buf; break; } if (*num_headers == max_headers) { *ret = -1; return NULL; } if (!(*num_headers != 0 && (*buf == ' ' || *buf == '\t'))) { /* parsing name, but do not discard SP before colon, see * http://www.mozilla.org/security/announce/2006/mfsa2006-33.html */ headers[*num_headers].name = buf; static const char ALIGNED(16) ranges1[] = "\x00 " /* control chars and up to SP */ "\"\"" /* 0x22 */ "()" /* 0x28,0x29 */ ",," /* 0x2c */ "//" /* 0x2f */ ":@" /* 0x3a-0x40 */ "[]" /* 0x5b-0x5d */ "{\377"; /* 0x7b-0xff */ int found; buf = findchar_fast(buf, buf_end, ranges1, sizeof(ranges1) - 1, &found); if (!found) { CHECK_EOF(); } while (1) { if (*buf == ':') { break; } else if (!token_char_map[(unsigned char)*buf]) { *ret = -1; return NULL; } ++buf; CHECK_EOF(); } if ((headers[*num_headers].name_len = buf - headers[*num_headers].name) == 0) { *ret = -1; return NULL; } ++buf; for (;; ++buf) { CHECK_EOF(); if (!(*buf == ' ' || *buf == '\t')) { break; } } } else { headers[*num_headers].name = NULL; headers[*num_headers].name_len = 0; } if ((buf = get_token_to_eol(buf, buf_end, &headers[*num_headers].value, &headers[*num_headers].value_len, ret)) == NULL) { return NULL; } } return buf; } static const char *parse_request(const char *buf, const char *buf_end, const char **method, size_t *method_len, const char **path, size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) { /* skip first empty line (some clients add CRLF after POST content) */ CHECK_EOF(); if (*buf == '\015') { ++buf; EXPECT_CHAR('\012'); } else if (*buf == '\012') { ++buf; } /* parse request line */ ADVANCE_TOKEN(*method, *method_len); ++buf; ADVANCE_TOKEN(*path, *path_len); ++buf; if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) { return NULL; } if (*buf == '\015') { ++buf; EXPECT_CHAR('\012'); } else if (*buf == '\012') { ++buf; } else { *ret = -1; return NULL; } return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); } int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len) { const char *buf = buf_start, *buf_end = buf_start + len; size_t max_headers = *num_headers; int r; *method = NULL; *method_len = 0; *path = NULL; *path_len = 0; *minor_version = -1; *num_headers = 0; /* if last_len != 0, check if the request is complete (a fast countermeasure againt slowloris */ if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { return r; } if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, minor_version, headers, num_headers, max_headers, &r)) == NULL) { return r; } return (int)(buf - buf_start); } static const char *parse_response(const char *buf, const char *buf_end, int *minor_version, int *status, const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) { /* parse "HTTP/1.x" */ if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) { return NULL; } /* skip space */ if (*buf++ != ' ') { *ret = -1; return NULL; } /* parse status code, we want at least [:digit:][:digit:][:digit:]<other char> to try to parse */ if (buf_end - buf < 4) { *ret = -2; return NULL; } PARSE_INT_3(status); /* skip space */ if (*buf++ != ' ') { *ret = -1; return NULL; } /* get message */ if ((buf = get_token_to_eol(buf, buf_end, msg, msg_len, ret)) == NULL) { return NULL; } return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); } int phr_parse_response(const char *buf_start, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t last_len) { const char *buf = buf_start, *buf_end = buf + len; size_t max_headers = *num_headers; int r; *minor_version = -1; *status = 0; *msg = NULL; *msg_len = 0; *num_headers = 0; /* if last_len != 0, check if the response is complete (a fast countermeasure against slowloris */ if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { return r; } if ((buf = parse_response(buf, buf_end, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == NULL) { return r; } return (int)(buf - buf_start); } int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len) { const char *buf = buf_start, *buf_end = buf + len; size_t max_headers = *num_headers; int r; *num_headers = 0; /* if last_len != 0, check if the response is complete (a fast countermeasure against slowloris */ if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { return r; } if ((buf = parse_headers(buf, buf_end, headers, num_headers, max_headers, &r)) == NULL) { return r; } return (int)(buf - buf_start); } enum { CHUNKED_IN_CHUNK_SIZE, CHUNKED_IN_CHUNK_EXT, CHUNKED_IN_CHUNK_DATA, CHUNKED_IN_CHUNK_CRLF, CHUNKED_IN_TRAILERS_LINE_HEAD, CHUNKED_IN_TRAILERS_LINE_MIDDLE }; static int decode_hex(int ch) { if ('0' <= ch && ch <= '9') { return ch - '0'; } else if ('A' <= ch && ch <= 'F') { return ch - 'A' + 0xa; } else if ('a' <= ch && ch <= 'f') { return ch - 'a' + 0xa; } else { return -1; } } ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *_bufsz) { size_t dst = 0, src = 0, bufsz = *_bufsz; ssize_t ret = -2; /* incomplete */ while (1) { switch (decoder->_state) { case CHUNKED_IN_CHUNK_SIZE: for (;; ++src) { int v; if (src == bufsz) goto Exit; if ((v = decode_hex(buf[src])) == -1) { if (decoder->_hex_count == 0) { ret = -1; goto Exit; } break; } if (decoder->_hex_count == sizeof(size_t) * 2) { ret = -1; goto Exit; } decoder->bytes_left_in_chunk = decoder->bytes_left_in_chunk * 16 + v; ++decoder->_hex_count; } decoder->_hex_count = 0; decoder->_state = CHUNKED_IN_CHUNK_EXT; /* fallthru */ case CHUNKED_IN_CHUNK_EXT: /* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */ for (;; ++src) { if (src == bufsz) goto Exit; if (buf[src] == '\012') break; } ++src; if (decoder->bytes_left_in_chunk == 0) { if (decoder->consume_trailer) { decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; break; } else { goto Complete; } } decoder->_state = CHUNKED_IN_CHUNK_DATA; /* fallthru */ case CHUNKED_IN_CHUNK_DATA: { size_t avail = bufsz - src; if (avail < decoder->bytes_left_in_chunk) { if (dst != src) memmove(buf + dst, buf + src, avail); src += avail; dst += avail; decoder->bytes_left_in_chunk -= avail; goto Exit; } if (dst != src) memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk); src += decoder->bytes_left_in_chunk; dst += decoder->bytes_left_in_chunk; decoder->bytes_left_in_chunk = 0; decoder->_state = CHUNKED_IN_CHUNK_CRLF; } /* fallthru */ case CHUNKED_IN_CHUNK_CRLF: for (;; ++src) { if (src == bufsz) goto Exit; if (buf[src] != '\015') break; } if (buf[src] != '\012') { ret = -1; goto Exit; } ++src; decoder->_state = CHUNKED_IN_CHUNK_SIZE; break; case CHUNKED_IN_TRAILERS_LINE_HEAD: for (;; ++src) { if (src == bufsz) goto Exit; if (buf[src] != '\015') break; } if (buf[src++] == '\012') goto Complete; decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE; /* fallthru */ case CHUNKED_IN_TRAILERS_LINE_MIDDLE: for (;; ++src) { if (src == bufsz) goto Exit; if (buf[src] == '\012') break; } ++src; decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; break; default: assert(!"decoder is corrupt"); } } Complete: ret = bufsz - src; Exit: if (dst != src) memmove(buf + dst, buf + src, bufsz - src); *_bufsz = dst; return ret; } int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder) { return decoder->_state == CHUNKED_IN_CHUNK_DATA; } #undef CHECK_EOF #undef EXPECT_CHAR #undef ADVANCE_TOKEN
billlin0904/librapid
thirdparty/picohttpparser/picohttpparser.c
C
apache-2.0
25,002
/********************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ #ifndef HSCONST_H #define HSCONST_H /* -*-C++-*- ***************************************************************************** * * File: hs_const.h * Description: Global constants. * Created: 03/25/96 * Language: C++ * * * * ***************************************************************************** */ #include <float.h> #include "BaseTypes.h" #include "ComSmallDefs.h" #include "EncodedValue.h" /*==============================*/ /* HISTOGRAM CONSTANTS */ /*==============================*/ const Lng32 HS_MAX_INTERVAL_COUNT = 10000; const Lng32 HS_MAX_BOUNDARY_LEN = 500; const Lng32 HS_MAX_UCS_BOUNDARY_CHAR = HS_MAX_BOUNDARY_LEN / 2; const Lng32 HS_SAMP_PCNT_UPSCALE = 10000; const Lng32 SAMPLE_THRESHOLD = 100000000; const Lng32 MIN_SAMPLE_SIZE = 40000; const Lng32 MAX_MC_COLUMNS = 1000; //if you modify the MAX_ROWSET value, you must manually modify the ROWSET //declarations in SQLHIST.MDF. If you forget, you will receive //ERROR[30008] Rowset index is out of range. const Lng32 MAX_ROWSET = HS_MAX_INTERVAL_COUNT + 1; const Lng32 MIN_BLOCK_SIZE = 512 ; const Lng32 MB_IN_BYTES = 1048576; const Lng32 VARCHAR_LEN_FIELD_IN_BYTES = 2; const Lng32 TIMESTAMP_CHAR_LEN = 19; const Lng32 MAX_IUS_WHERE_LEN = 512; // keep this in synch with declared len of // persistent_samples.ius_search_condition /*==============================*/ /* OBJECT RELATED */ /*==============================*/ enum hs_table_type { UNKNOWN_TYPE = 0, GUARDIAN_TABLE, ANSI_TABLE }; #define HS_EXTENT_SIZE_MX " EXTENT(8192, 16384) MAXEXTENTS 768 " #define HS_EXTENT_SIZE_MP_FMT2 " EXTENT(8192, 16384) MAXEXTENTS 959 " #define HS_EXTENT_SIZE_MP_FMT1 " EXTENT(8192, 1024) MAXEXTENTS 959 " /*==============================*/ /* SYNTAX / PARSING */ /*==============================*/ /*=== BASIC OPTIONS ===*/ #define CLEAR_OPT 0x00000001 /* CLEAR */ #define VIEWONLY_OPT 0x00000002 /* VIEWONLY (unpublished) */ #define INTERVAL_OPT 0x00000004 /* GENERATE x INTERVALS */ #define EVERYCOL_OPT 0x00000008 /* ON EVERY COLUMN */ #define ROWCOUNT_OPT 0x00000010 /* SET ROWCOUNT c */ #define EVERYKEY_OPT 0x00000020 /* ON EVERY KEY */ #define LOG_OPT 0x00000040 /* LOG (unpublished) */ #define EXISTING_OPT 0x00000080 /* ON EXISTING COLUMNS */ #define NECESSARY_OPT 0x00000100 /* ON NECESSARY COLUMNS */ #define REG_GROUP_OPT 0x00000200 /* ON col,... */ #define CREATE_SAMPLE_OPT 0x00000400 /* CREATE SAMPLE */ #define REMOVE_SAMPLE_OPT 0x00000800 /* REMOVE SAMPLE */ /*=== SAMPLING OPTIONS ===*/ #define SAMPLE_BASIC_0 0x00001000 /* SAMPLE */ #define SAMPLE_BASIC_1 0x00002000 /* SAMPLE+ROWS */ #define SAMPLE_RAND_1 0x00004000 /* SAMPLE RANDOM */ #define SAMPLE_RAND_2 0x00008000 /* SAMPLE RANDOM+CLUSTERS */ #define SAMPLE_PERIODIC 0x00010000 /* SAMPLE PERIODIC */ #define SAMPLE_REQUESTED 0x0001F000 /* 'OR' sampling options */ #define SAMPLE_ALL 0x00020000 /* For REMOVE SAMPLE */ #define NO_SAMPLE 0x00200000 /* NO SAMPLE (explicit) */ /*=== IUS OPTIONS ===*/ #define IUS_OPT 0x00040000 /* INCREMENTAL UPDATE STATS*/ #define IUS_PERSIST 0x00080000 /* CREATE PERSISTENT SAMPLE*/ /*=== SHOWSTATS OPTIONS ===*/ #define SHOWSTATS_OPT 0x00100000 /* SHOWSTATS COMMAND */ // note 0x00200000 taken above #define DETAIL_OPT 0x00000001 /* DETAILS */ /*==============================*/ /* ERROR CODES */ /*==============================*/ const Lng32 HS_EOF = 100; const Lng32 HS_WARNING = 4; const Lng32 HS_PKEY_FLOAT_ERROR = 1120; #define HS_QUERY_ERROR "Process_Query" #define HS_DDL_ERROR "Process_DDL" const Lng32 HS_MAX_MSGTOK_LEN = 1024; enum USTAT_ERROR_CODES {UERR_SYNTAX_ERROR = 15001, UERR_ERROR_LINE_NUMBER = 1001, UERR_OBJECT_INACCESSIBLE = 4082, UERR_FIRST_ERROR = 9200, UERR_INTERNAL_ERROR = 9200, UERR_UNABLE_TO_DROP_OBJECT = 9201, UERR_DOWN_LEVEL_HISTOGRAMS = 9202, UERR_COLUMNLIST_NOT_UNIQUE = 9203, UERR_INVALID_OPTION = 9204, UERR_INVALID_OBJECT = 9205, UERR_SECURITY_VIOLATION = 9206, UERR_SAMPLE_SET_IS_ZERO = 9207, UERR_UNABLE_TO_DESCRIBE_COLUMN_NAMES = 9208, UERR_COLUMN_NAME_DOES_NOT_EXIST = 9209, UERR_UNSUPPORTED_DATATYPE = 9210, UERR_WRONG_ON_CLAUSE_FOR_IUS = 9211, UERR_WARNING_SET_ROWCOUNT = 9212, UERR_WARNING_FILE_STATISTICS = 9213, UERR_UNABLE_TO_CREATE_OBJECT = 9214, UERR_GENERIC_ERROR = 9215, UERR_EVERY_COLUMN_NOT_ALLOWED_FOR_LOG = 9216, UERR_WARNING_NO_EXISTING_HISTOGRAMS = 9217, UERR_WARNING_NO_OBSOLETE_HISTOGRAMS = 9218, UERR_IUS_BAD_WHERE_CLAUSE = 9219, UERR_WARNING_NO_SAMPLE_TABLE_CREATED = 9220, UERR_IUS_NO_PERSISTENT_SAMPLE = 9221, UERR_WARNING_IUS_TOO_MUCH_RC_CHANGE_INTERVAL = 9222, UERR_WARNING_IUS_TOO_MUCH_RC_CHANGE_TOTAL = 9223, UERR_WARNING_IUS_TOO_MUCH_UEC_CHANGE_INTERVAL= 9224, UERR_WARNING_IUS_TOO_MUCH_UEC_CHANGE_TOTAL = 9225, UERR_WARNING_IUS_ZERO_UEC_INTERVAL = 9226, UERR_WARNING_IUS_EMPTY_INTERVAL = 9227, UERR_WARNING_NO_SAMPLE_TABLE = 9228, UERR_MULTI_COLUMN_LIMIT_EXCEEDED = 9229, UERR_WARNING_IUS_INSUFFICIENT_MEMORY = 9230, UERR_IUS_WRONG_RANDOM = 9231, UERR_IUS_IN_PROGRESS = 9232, UERR_ALL_LOB_COLUMNS = 9233, UERR_IUS_INSERT_NONMFV_OVERFLOW = 9234, UERR_WARNING_NONEXISTENT_COLUMN = 9235, UERR_IUS_NO_EXISTING_STATS = 9236, UERR_IUS_WHERE_CLAUSE = 9237, UERR_WARNING_FILESTATS_FAILED = 9238, UERR_NO_VIEWONLY = 9239, UERR_NO_ONEVERYKEY = 9240, UERR_NO_PRIVILEGE = 9241, UERR_CANT_CREATE_HIVE_STATS_SCHEMA = 9242, UERR_YOU_WILL_LIKELY_BE_SORRY = 9243, UERR_USER_TRANSACTION = 9244, UERR_UNEXPECTED_BACKWARDS_DATA = 9245, UERR_LOB_STATS_NOT_SUPPORTED = 9246, UERR_VOLATILE_TABLES_NOT_SUPPORTED = 9247, UERR_FASTSTATS_MEM_ALLOCATION_ERROR = 9248, UERR_IUS_IS_DISABLED = 9249, UERR_WARNING_IUS_NO_LONGER_ALL_NULL = 9250, UERR_DROP_PERSISTANT_SAMPLE_FIRST = 9251, UERR_BAD_EST_ROWCOUNT = 9252, UERR_NO_ERROR = 9259, UERR_LAST_ERROR = 9259 }; // reason of a histogram entry. it is a char value. enum HS_REASON { HS_REASON_EMPTY = ' ', // it was added because it was needed // but had not been generated HS_REASON_MANUAL = 'M', // it was manually generated // by running update statistics HS_REASON_AUTO_INIT = 'I', // it is an initial entry generated // by histogram automation HS_REASON_AUTO_REGEN = 'N', // it is a re-generated entry by histogram automation // because it was recently needed by optimizer HS_REASON_SMALL_SAMPLE = 'S', // it is a histogram generated during compile time HS_REASON_UNKNOWN = 'X' }; const Int32 HS_TIMESTAMP_SIZE = 30; const Int32 USTAT_CQDS_ALLOWED_FOR_SPAWNED_COMPILERS_MAX_SIZE = 15000; #endif /* HSCONST_H */
apache/incubator-trafodion
core/sql/ustat/hs_const.h
C
apache-2.0
11,346
if AUTOTAUNT_ENABLED then local function runAutoTaunter() local players = team.GetPlayers(TEAM_PROPS) local pRange = TAUNT_MAX_PITCH - TAUNT_MIN_PITCH --Render the Auto-taunt HUD for _,ply in pairs(players) do local taunt = table.Random( PROP_TAUNTS ) if ply:Alive() && ply:Team() == TEAM_PROPS then if ply.lastTaunt != nil then local lastAutoTaunt = math.Round(CurTime() - ply.lastTaunt) --Check if the lastAutoTaunt exceeds the autoTauntInterval if (lastAutoTaunt > ply.autoTauntInterval) then --Send the Taunt to the player local pRange = TAUNT_MAX_PITCH - TAUNT_MIN_PITCH local pitch = math.random()*pRange + TAUNT_MIN_PITCH SendTaunt(ply, taunt, pitch ) end end end end end function CreateAutoTauntTimer() timer.Create("AutoTauntTimer", 0.1, 0, runAutoTaunter) end hook.Add( "Initialize", "Set Map Time", function () mapStartTime = os.time() CreateAutoTauntTimer() end) hook.Add("OBJHUNT_RoundStart", "Restart the Timer", function () local players = team.GetPlayers(TEAM_PROPS) for _,ply in pairs(players) do ply.autoTauntInterval = OBJHUNT_AUTOTAUNT_INTERVAL + OBJHUNT_HIDE_TIME ply.lastTaunt = CurTime() net.Start( "AutoTaunt Update" ) net.WriteUInt( ply:EntIndex(), 8 ) net.WriteFloat( ply.lastTaunt ) net.WriteFloat( ply.autoTauntInterval ) net.Broadcast() end if timer.Exists("AutoTauntTimer") then timer.Start("AutoTauntTimer") else CreateAutoTauntTimer() end end) end
Newbrict/ObjHunt
gamemode/server/autotaunt.lua
Lua
apache-2.0
1,520
/* Copyright 2015 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package e2e import ( "fmt" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/util" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) // Returns a number of currently scheduled and not scheduled Pods. func getPodsScheduled(pods *api.PodList) (scheduledPods, notScheduledPods []api.Pod) { for _, pod := range pods.Items { if pod.Spec.NodeName != "" { scheduledPods = append(scheduledPods, pod) } else { notScheduledPods = append(notScheduledPods, pod) } } return } // Simplified version of RunRC, that does not create RC, but creates plain Pods and // requires passing whole Pod definition, which is needed to test various Scheduler predicates. func startPods(c *client.Client, replicas int, ns string, podNamePrefix string, pod api.Pod) { allPods, err := c.Pods(api.NamespaceAll).List(api.ListOptions{}) expectNoError(err) podsScheduledBefore, _ := getPodsScheduled(allPods) for i := 0; i < replicas; i++ { podName := fmt.Sprintf("%v-%v", podNamePrefix, i) pod.ObjectMeta.Name = podName pod.ObjectMeta.Labels["name"] = podName pod.Spec.Containers[0].Name = podName _, err = c.Pods(ns).Create(&pod) expectNoError(err) } // Wait for pods to start running. Note: this is a functional // test, not a performance test, so the timeout needs to be // sufficiently long that it's only triggered if things are // completely broken vs. running slowly. timeout := 10 * time.Minute startTime := time.Now() currentlyScheduledPods := 0 for len(podsScheduledBefore)+replicas != currentlyScheduledPods { allPods, err := c.Pods(api.NamespaceAll).List(api.ListOptions{}) expectNoError(err) scheduledPods := 0 for _, pod := range allPods.Items { if pod.Spec.NodeName != "" { scheduledPods += 1 } } currentlyScheduledPods = scheduledPods Logf("%v pods running", currentlyScheduledPods) if startTime.Add(timeout).Before(time.Now()) { Logf("Timed out after %v waiting for pods to start running.", timeout) break } time.Sleep(5 * time.Second) } Expect(currentlyScheduledPods).To(Equal(len(podsScheduledBefore) + replicas)) } func getRequestedCPU(pod api.Pod) int64 { var result int64 for _, container := range pod.Spec.Containers { result += container.Resources.Requests.Cpu().MilliValue() } return result } func verifyResult(c *client.Client, podName string, ns string) { allPods, err := c.Pods(api.NamespaceAll).List(api.ListOptions{}) expectNoError(err) scheduledPods, notScheduledPods := getPodsScheduled(allPods) selector := fields.Set{ "involvedObject.kind": "Pod", "involvedObject.name": podName, "involvedObject.namespace": ns, "source": "scheduler", "reason": "FailedScheduling", }.AsSelector() options := api.ListOptions{FieldSelector: selector} schedEvents, err := c.Events(ns).List(options) expectNoError(err) // If we failed to find event with a capitalized first letter of reason // try looking for one starting with a small one for backward compatibility. // If we don't do it we end up in #15806. // TODO: remove this block when we don't care about supporting v1.0 too much. if len(schedEvents.Items) == 0 { selector := fields.Set{ "involvedObject.kind": "Pod", "involvedObject.name": podName, "involvedObject.namespace": ns, "source": "scheduler", "reason": "failedScheduling", }.AsSelector() options := api.ListOptions{FieldSelector: selector} schedEvents, err = c.Events(ns).List(options) expectNoError(err) } printed := false printOnce := func(msg string) string { if !printed { printed = true return msg } else { return "" } } Expect(len(notScheduledPods)).To(Equal(1), printOnce(fmt.Sprintf("Not scheduled Pods: %#v", notScheduledPods))) Expect(schedEvents.Items).ToNot(BeEmpty(), printOnce(fmt.Sprintf("Scheduled Pods: %#v", scheduledPods))) } func cleanupPods(c *client.Client, ns string) { By("Removing all pods in namespace " + ns) pods, err := c.Pods(ns).List(api.ListOptions{}) expectNoError(err) opt := api.NewDeleteOptions(0) for _, p := range pods.Items { expectNoError(c.Pods(ns).Delete(p.ObjectMeta.Name, opt)) } } // Waits until all existing pods are scheduled and returns their amount. func waitForStableCluster(c *client.Client) int { timeout := 10 * time.Minute startTime := time.Now() allPods, err := c.Pods(api.NamespaceAll).List(api.ListOptions{}) expectNoError(err) scheduledPods, currentlyNotScheduledPods := getPodsScheduled(allPods) for len(currentlyNotScheduledPods) != 0 { time.Sleep(2 * time.Second) allPods, err := c.Pods(api.NamespaceAll).List(api.ListOptions{}) expectNoError(err) scheduledPods, currentlyNotScheduledPods = getPodsScheduled(allPods) if startTime.Add(timeout).Before(time.Now()) { Failf("Timed out after %v waiting for stable cluster.", timeout) break } } return len(scheduledPods) } var _ = Describe("SchedulerPredicates [Serial]", func() { var c *client.Client var nodeList *api.NodeList var totalPodCapacity int64 var RCName string var ns string AfterEach(func() { rc, err := c.ReplicationControllers(ns).Get(RCName) if err == nil && rc.Spec.Replicas != 0 { By("Cleaning up the replication controller") err := DeleteRC(c, ns, RCName) expectNoError(err) } }) framework := NewFramework("sched-pred") BeforeEach(func() { c = framework.Client ns = framework.Namespace.Name nodeList = ListSchedulableNodesOrDie(c) }) // This test verifies that max-pods flag works as advertised. It assumes that cluster add-on pods stay stable // and cannot be run in parallel with any other test that touches Nodes or Pods. It is so because to check // if max-pods is working we need to fully saturate the cluster and keep it in this state for few seconds. It("validates MaxPods limit number of pods that are allowed to run", func() { totalPodCapacity = 0 for _, node := range nodeList.Items { podCapacity, found := node.Status.Capacity["pods"] Expect(found).To(Equal(true)) totalPodCapacity += podCapacity.Value() Logf("Node: %v", node) } currentlyScheduledPods := waitForStableCluster(c) podsNeededForSaturation := int(totalPodCapacity) - currentlyScheduledPods By(fmt.Sprintf("Starting additional %v Pods to fully saturate the cluster max pods and trying to start another one", podsNeededForSaturation)) startPods(c, podsNeededForSaturation, ns, "maxp", api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, ObjectMeta: api.ObjectMeta{ Name: "", Labels: map[string]string{"name": ""}, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: "", Image: "gcr.io/google_containers/pause:2.0", }, }, }, }) podName := "additional-pod" _, err := c.Pods(ns).Create(&api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, ObjectMeta: api.ObjectMeta{ Name: podName, Labels: map[string]string{"name": "additional"}, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: podName, Image: "gcr.io/google_containers/pause:2.0", }, }, }, }) expectNoError(err) // Wait a bit to allow scheduler to do its thing // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds. Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.") time.Sleep(10 * time.Second) verifyResult(c, podName, ns) cleanupPods(c, ns) }) // This test verifies we don't allow scheduling of pods in a way that sum of limits of pods is greater than machines capacity. // It assumes that cluster add-on pods stay stable and cannot be run in parallel with any other test that touches Nodes or Pods. // It is so because we need to have precise control on what's running in the cluster. It("validates resource limits of pods that are allowed to run [Conformance]", func() { nodeToCapacityMap := make(map[string]int64) for _, node := range nodeList.Items { capacity, found := node.Status.Capacity["cpu"] Expect(found).To(Equal(true)) nodeToCapacityMap[node.Name] = capacity.MilliValue() } waitForStableCluster(c) pods, err := c.Pods(api.NamespaceAll).List(api.ListOptions{}) expectNoError(err) for _, pod := range pods.Items { _, found := nodeToCapacityMap[pod.Spec.NodeName] Expect(found).To(Equal(true)) if pod.Status.Phase == api.PodRunning { Logf("Pod %v requesting capacity %v on Node %v", pod.Name, getRequestedCPU(pod), pod.Spec.NodeName) nodeToCapacityMap[pod.Spec.NodeName] -= getRequestedCPU(pod) } } var podsNeededForSaturation int milliCpuPerPod := int64(500) for name, leftCapacity := range nodeToCapacityMap { Logf("Node: %v has capacity: %v", name, leftCapacity) podsNeededForSaturation += (int)(leftCapacity / milliCpuPerPod) } By(fmt.Sprintf("Starting additional %v Pods to fully saturate the cluster CPU and trying to start another one", podsNeededForSaturation)) startPods(c, podsNeededForSaturation, ns, "overcommit", api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, ObjectMeta: api.ObjectMeta{ Name: "", Labels: map[string]string{"name": ""}, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: "", Image: "gcr.io/google_containers/pause:2.0", Resources: api.ResourceRequirements{ Limits: api.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"), }, Requests: api.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"), }, }, }, }, }, }) podName := "additional-pod" _, err = c.Pods(ns).Create(&api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, ObjectMeta: api.ObjectMeta{ Name: podName, Labels: map[string]string{"name": "additional"}, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: podName, Image: "gcr.io/google_containers/pause:2.0", Resources: api.ResourceRequirements{ Limits: api.ResourceList{ "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"), }, }, }, }, }, }) expectNoError(err) // Wait a bit to allow scheduler to do its thing // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds. Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.") time.Sleep(10 * time.Second) verifyResult(c, podName, ns) cleanupPods(c, ns) }) // Test Nodes does not have any label, hence it should be impossible to schedule Pod with // nonempty Selector set. It("validates that NodeSelector is respected if not matching [Conformance]", func() { By("Trying to schedule Pod with nonempty NodeSelector.") podName := "restricted-pod" waitForStableCluster(c) _, err := c.Pods(ns).Create(&api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, ObjectMeta: api.ObjectMeta{ Name: podName, Labels: map[string]string{"name": "restricted"}, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: podName, Image: "gcr.io/google_containers/pause:2.0", }, }, NodeSelector: map[string]string{ "label": "nonempty", }, }, }) expectNoError(err) // Wait a bit to allow scheduler to do its thing // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds. Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.") time.Sleep(10 * time.Second) verifyResult(c, podName, ns) cleanupPods(c, ns) }) It("validates that NodeSelector is respected if matching [Conformance]", func() { // launch a pod to find a node which can launch a pod. We intentionally do // not just take the node list and choose the first of them. Depending on the // cluster and the scheduler it might be that a "normal" pod cannot be // scheduled onto it. By("Trying to launch a pod without a label to get a node which can launch it.") podName := "without-label" _, err := c.Pods(ns).Create(&api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, ObjectMeta: api.ObjectMeta{ Name: podName, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: podName, Image: "gcr.io/google_containers/pause:2.0", }, }, }, }) expectNoError(err) expectNoError(waitForPodRunningInNamespace(c, podName, ns)) pod, err := c.Pods(ns).Get(podName) expectNoError(err) nodeName := pod.Spec.NodeName err = c.Pods(ns).Delete(podName, api.NewDeleteOptions(0)) expectNoError(err) By("Trying to apply a random label on the found node.") k := fmt.Sprintf("kubernetes.io/e2e-%s", string(util.NewUUID())) v := "42" patch := fmt.Sprintf(`{"metadata":{"labels":{"%s":"%s"}}}`, k, v) err = c.Patch(api.MergePatchType).Resource("nodes").Name(nodeName).Body([]byte(patch)).Do().Error() expectNoError(err) node, err := c.Nodes().Get(nodeName) expectNoError(err) Expect(node.Labels[k]).To(Equal(v)) By("Trying to relaunch the pod, now with labels.") labelPodName := "with-labels" _, err = c.Pods(ns).Create(&api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: "Pod", }, ObjectMeta: api.ObjectMeta{ Name: labelPodName, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: labelPodName, Image: "gcr.io/google_containers/pause:2.0", }, }, NodeSelector: map[string]string{ "kubernetes.io/hostname": nodeName, k: v, }, }, }) expectNoError(err) defer c.Pods(ns).Delete(labelPodName, api.NewDeleteOptions(0)) // check that pod got scheduled. We intentionally DO NOT check that the // pod is running because this will create a race condition with the // kubelet and the scheduler: the scheduler might have scheduled a pod // already when the kubelet does not know about its new label yet. The // kubelet will then refuse to launch the pod. expectNoError(waitForPodNotPending(c, ns, labelPodName)) labelPod, err := c.Pods(ns).Get(labelPodName) expectNoError(err) Expect(labelPod.Spec.NodeName).To(Equal(nodeName)) }) })
diditaxi/kubernetes
test/e2e/scheduler_predicates.go
GO
apache-2.0
15,042
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <db/db.h> #include <cmn/agent_cmn.h> #include <oper/interface_common.h> #include <oper/interface.h> #include <oper/mirror_table.h> #include "vr_genetlink.h" #include "vr_interface.h" #include "vr_types.h" #include "nl_util.h" #include <uve/stats_collector.h> #include <vrouter/stats_collector/agent_stats_collector.h> #include <uve/vn_uve_table.h> #include <uve/vm_uve_table.h> #include <uve/interface_uve_stats_table.h> #include <init/agent_param.h> #include <vrouter/stats_collector/interface_stats_io_context.h> #include <vrouter/stats_collector/vrf_stats_io_context.h> #include <vrouter/stats_collector/drop_stats_io_context.h> #include <uve/agent_uve.h> #include <vrouter/stats_collector/agent_stats_interval_types.h> AgentStatsCollector::AgentStatsCollector (boost::asio::io_service &io, Agent* agent) : StatsCollector(TaskScheduler::GetInstance()-> GetTaskId("Agent::StatsCollector"), StatsCollector::AgentStatsCollector, io, agent->params()->agent_stats_interval(), "Agent Stats collector"), agent_(agent) { intf_stats_sandesh_ctx_.reset(new AgentStatsSandeshContext(agent, true)); vrf_stats_sandesh_ctx_.reset( new AgentStatsSandeshContext(agent, false)); drop_stats_sandesh_ctx_.reset(new AgentStatsSandeshContext(agent, false)); InitDone(); } AgentStatsCollector::~AgentStatsCollector() { } void AgentStatsCollector::SendInterfaceBulkGet() { vr_interface_req encoder; encoder.set_h_op(sandesh_op::DUMP); encoder.set_vifr_context(0); encoder.set_vifr_marker(intf_stats_sandesh_ctx_.get()->marker_id()); /* Always fetch per-interface Drop-stats along with other stats */ encoder.set_vifr_flags(VIF_FLAG_GET_DROP_STATS); SendRequest(encoder, InterfaceStatsType); } void AgentStatsCollector::SendVrfStatsBulkGet() { vr_vrf_stats_req encoder; encoder.set_h_op(sandesh_op::DUMP); encoder.set_vsr_rid(0); encoder.set_vsr_family(AF_INET); encoder.set_vsr_marker(vrf_stats_sandesh_ctx_.get()->marker_id()); SendRequest(encoder, VrfStatsType); } void AgentStatsCollector::SendDropStatsBulkGet() { vr_drop_stats_req encoder; encoder.set_h_op(sandesh_op::GET); encoder.set_vds_rid(0); encoder.set_vds_core(0); SendRequest(encoder, DropStatsType); } bool AgentStatsCollector::SendRequest(Sandesh &encoder, StatsType type) { int encode_len; int error; uint8_t *buf = (uint8_t *)malloc(KSYNC_DEFAULT_MSG_SIZE); encode_len = encoder.WriteBinary(buf, KSYNC_DEFAULT_MSG_SIZE, &error); SendAsync((char*)buf, encode_len, type); return true; } IoContext *AgentStatsCollector::AllocateIoContext(char* buf, uint32_t buf_len, StatsType type, uint32_t seq) { switch (type) { case InterfaceStatsType: return (new InterfaceStatsIoContext(buf_len, buf, seq, intf_stats_sandesh_ctx_.get(), IoContext::IOC_UVE)); break; case VrfStatsType: return (new VrfStatsIoContext(buf_len, buf, seq, vrf_stats_sandesh_ctx_.get(), IoContext::IOC_UVE)); break; case DropStatsType: return (new DropStatsIoContext(buf_len, buf, seq, drop_stats_sandesh_ctx_.get(), IoContext::IOC_UVE)); break; default: return NULL; } } void AgentStatsCollector::SendAsync(char* buf, uint32_t buf_len, StatsType type) { KSyncSock *sock = KSyncSock::Get(0); uint32_t seq = sock->AllocSeqNo(IoContext::IOC_UVE, 0); IoContext *ioc = AllocateIoContext(buf, buf_len, type, seq); if (ioc) { sock->GenericSend(ioc); } } bool AgentStatsCollector::Run() { SendInterfaceBulkGet(); SendVrfStatsBulkGet(); SendDropStatsBulkGet(); return true; } void AgentStatsCollector::Shutdown(void) { StatsCollector::Shutdown(); } void SetAgentStatsInterval_InSeconds::HandleRequest() const { SandeshResponse *resp; AgentStatsCollector *col = Agent::GetInstance()->stats_collector(); if (!col) { resp = new AgentStatsCfgResp(); } else if (get_interval() > 0) { col->set_expiry_time(get_interval() * 1000); resp = new AgentStatsCfgResp(); } else { resp = new AgentStatsCfgErrResp(); } resp->set_context(context()); resp->Response(); return; } void GetAgentStatsInterval::HandleRequest() const { AgentStatsIntervalResp_InSeconds *resp = new AgentStatsIntervalResp_InSeconds(); AgentStatsCollector *col = Agent::GetInstance()->stats_collector(); if (col) { resp->set_agent_stats_interval((col->expiry_time())/1000); } resp->set_context(context()); resp->Response(); return; }
rombie/contrail-controller
src/vnsw/agent/vrouter/stats_collector/agent_stats_collector.cc
C++
apache-2.0
5,121
/* * Copyright (C) 2005-2017 Qihoo 360 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.qihoo360.loader2; import android.text.TextUtils; import android.util.Log; import com.qihoo360.replugin.helper.LogRelease; import com.qihoo360.replugin.utils.CloseableUtils; import com.qihoo360.mobilesafe.core.BuildConfig; import com.qihoo360.replugin.helper.LogDebug; import com.qihoo360.replugin.utils.FileUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * 与插件Native(SO)库有关的方法,都放在此处 <p> * 该类主要用于:安装插件的SO库,获取SO库路径等 <p> * 【仅框架内部使用】 * * @author RePlugin Team */ public class PluginNativeLibsHelper { private static final String TAG = "PluginNativeLibsHelper"; /** * 安装Native SO库 <p> * 模拟系统安装流程,最终只释放一个最合身的SO库进入Libs目录中 * * @param apkPath APK文件路径 * @param nativeDir 要释放的Libs目录,通常从getLibDir中获取 * @return 安装是否成功 */ public static boolean install(String apkPath, File nativeDir) { if (BuildConfig.DEBUG) { Log.d(TAG, "install(): Start. apkp=" + apkPath + "; nd=" + nativeDir.getAbsolutePath()); } // TODO 线程同步 // 为防止加载旧SO,先清空目录 clear(nativeDir); ZipFile zipFile = null; try { zipFile = new ZipFile(apkPath); Map<String, ZipEntry> libZipEntries = new HashMap<>(); Map<String, Set<String>> soList = new HashMap<>(); // 找到所有的SO库,包括各种版本的,方便findSoPathForAbis中过滤 injectEntriesAndLibsMap(zipFile, libZipEntries, soList); for (String soName : soList.keySet()) { Set<String> soPaths = soList.get(soName); String soPath = findSoPathForAbis(soPaths, soName); if (BuildConfig.DEBUG) { Log.d(TAG, "install(): Ready to extract. so=" + soName + "; sop=" + soPath); } if (soPath == null) { continue; } File file = new File(nativeDir, soName); extractFile(zipFile, libZipEntries.get(soPath), file); } return true; } catch (Throwable e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } // 清除所有释放的文件,防止释放了一半 clear(nativeDir); return false; } finally { CloseableUtils.closeQuietly(zipFile); } } /** * 删除插件的SO库,通常在插件SO释放失败后,或者已有新插件,需要清除老插件时才会生效 */ public static void clear(File nativeDir) { if (!nativeDir.exists()) { return; } try { FileUtils.forceDelete(nativeDir); } catch (IOException e) { // IOException:有可能是IO,如权限出现问题等,打出日志 e.printStackTrace(); } catch (IllegalArgumentException e2) { if (LogRelease.LOGR) { e2.printStackTrace(); } } } private static void injectEntriesAndLibsMap(ZipFile zipFile, Map<String, ZipEntry> libZipEntries, Map<String, Set<String>> soList) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (name.contains("../")) { // 过滤,防止被攻击 continue; } if (name.startsWith("lib/") && !entry.isDirectory()) { libZipEntries.put(name, entry); String soName = new File(name).getName(); Set<String> fs = soList.get(soName); if (fs == null) { fs = new TreeSet<>(); soList.put(soName, fs); } fs.add(name); } } } private static void extractFile(ZipFile zipFile, ZipEntry ze, File outFile) throws IOException { InputStream in = null; try { in = zipFile.getInputStream(ze); FileUtils.copyInputStreamToFile(in, outFile); if (BuildConfig.DEBUG) { Log.i(TAG, "extractFile(): Success! fn=" + outFile.getName()); } } finally { CloseableUtils.closeQuietly(in); } } // 根据Abi来获取需要释放的SO在压缩包中的位置 private static String findSoPathForAbis(Set<String> soPaths, String soName) { if (soPaths == null || soPaths.size() <= 0) { return null; } // 若主程序用的是64位进程,则所属的SO必须只拷贝64位的,否则会出异常。32位也是如此 // 问:如果用户用的是64位处理器,宿主没有放任何SO,那么插件会如何? // 答:宿主在被安装时,系统会标记此为64位App,则之后的SO加载则只认64位的 // 问:如何让插件支持32位? // 答:宿主需被标记为32位才可以。可在宿主App中放入任意32位的SO(如放到libs/armeabi目录下)即可。 // 获取指令集列表 boolean is64 = VMRuntimeCompat.is64Bit(); String[] abis; if (is64) { abis = BuildCompat.SUPPORTED_64_BIT_ABIS; } else { abis = BuildCompat.SUPPORTED_32_BIT_ABIS; } // 开始寻找合适指定指令集的SO路径 String soPath = findSoPathWithAbiList(soPaths, soName, abis); if (LogDebug.LOG) { LogDebug.d(TAG, "findSoPathForAbis: Find so path. name=" + soName + "; list=" + soPath + "; Host-is-64bit?=" + is64 + "; abis=" + Arrays.toString(abis)); } return soPath; } private static String findSoPathWithAbiList(Set<String> soPaths, String soName, String[] supportAbis) { Arrays.sort(supportAbis); for (String soPath : soPaths) { String abi = soPath.replaceFirst("lib/", ""); abi = abi.replace("/" + soName, ""); if (!TextUtils.isEmpty(abi) && Arrays.binarySearch(supportAbis, abi) >= 0) { return soPath; } } return null; } }
dstmath/RePlugin
replugin-host-library/replugin-host-lib/src/main/java/com/qihoo360/loader2/PluginNativeLibsHelper.java
Java
apache-2.0
7,301
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.RouterMediator; import org.wso2.developerstudio.eclipse.gmf.esb.RouterMediatorOutputConnector; /** * @generated */ public class RouterMediatorOutputConnectorCreateCommand extends EditElementCommand { /** * @generated */ public RouterMediatorOutputConnectorCreateCommand(CreateElementRequest req) { super(req.getLabel(), null, req); } /** * FIXME: replace with setElementToEdit() * * @generated */ protected EObject getElementToEdit() { EObject container = ((CreateElementRequest) getRequest()).getContainer(); if (container instanceof View) { container = ((View) container).getElement(); } return container; } /** * @generated */ public boolean canExecute() { RouterMediator container = (RouterMediator) getElementToEdit(); if (container.getOutputConnector() != null) { return false; } return true; } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { RouterMediatorOutputConnector newElement = EsbFactory.eINSTANCE.createRouterMediatorOutputConnector(); RouterMediator owner = (RouterMediator) getElementToEdit(); owner.setOutputConnector(newElement); doConfigure(newElement, monitor, info); ((CreateElementRequest) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(RouterMediatorOutputConnector newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((CreateElementRequest) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } }
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/commands/RouterMediatorOutputConnectorCreateCommand.java
Java
apache-2.0
3,162
// ---------------------------------------------------------------------------------- // // Copyright 2011 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.Samples.WindowsAzure.ServiceManagement; namespace Microsoft.WindowsAzure.Management.Model { public class SubscriptionDataExtended : SubscriptionData { public string AccountAdminLiveEmailId { get; set; } public int CurrentCoreCount { get; set; } public int CurrentHostedServices { get; set; } public int CurrentDnsServers { get; set; } public int CurrentLocalNetworkSites { get; set; } public int CurrentVirtualNetworkSites { get; set; } public int CurrentStorageAccounts { get; set; } public int MaxCoreCount { get; set; } public int MaxDnsServers { get; set; } public int MaxHostedServices { get; set; } public int MaxLocalNetworkSites { get; set; } public int MaxVirtualNetworkSites { get; set; } public int MaxStorageAccounts { get; set; } public string ServiceAdminLiveEmailId { get; set; } public string SubscriptionRealName { get; set; } public string SubscriptionStatus { get; set; } public string OperationDescription { get; set; } public string OperationId { get; set; } public string OperationStatus { get; set; } public SubscriptionDataExtended(Subscription subscription, SubscriptionData subscriptionData, string description, Operation operation) { OperationDescription = description; OperationStatus = operation.Status; OperationId = operation.OperationTrackingId; SubscriptionName = subscriptionData.SubscriptionName; SubscriptionId = subscriptionData.SubscriptionId; Certificate = subscriptionData.Certificate; CurrentStorageAccount = subscriptionData.CurrentStorageAccount; ServiceEndpoint = subscriptionData.ServiceEndpoint; SqlAzureServiceEndpoint = subscriptionData.SqlAzureServiceEndpoint; IsDefault = subscriptionData.IsDefault; AccountAdminLiveEmailId = subscription.AccountAdminLiveEmailId; CurrentCoreCount = subscription.CurrentCoreCount; CurrentHostedServices = subscription.CurrentHostedServices; CurrentStorageAccounts = subscription.CurrentStorageAccounts; CurrentDnsServers = subscription.CurrentDnsServers; CurrentLocalNetworkSites = subscription.CurrentLocalNetworkSites; CurrentVirtualNetworkSites = subscription.CurrentVirtualNetworkSites; MaxCoreCount = subscription.MaxCoreCount; MaxHostedServices = subscription.MaxHostedServices; MaxStorageAccounts = subscription.MaxStorageAccounts; MaxDnsServers = subscription.MaxDnsServers; MaxLocalNetworkSites = subscription.MaxLocalNetworkSites; MaxVirtualNetworkSites = subscription.MaxVirtualNetworkSites; ServiceAdminLiveEmailId = subscription.ServiceAdminLiveEmailId; SubscriptionRealName = subscription.SubscriptionName; SubscriptionStatus = subscription.SubscriptionStatus; } } }
aidancasey/azure-sdk-tools
WindowsAzurePowershell/src/Management/Model/SubscriptionDataExtended.cs
C#
apache-2.0
3,858
<?php /* * Copyright 2013 Johannes M. Schmitt <johannes@scrutinizer-ci.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. */ namespace Scrutinizer\PhpAnalyzer\Model\Type; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\ConversionException; use Doctrine\DBAL\Types\TextType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\NoType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\AllType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\ArrayType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\BooleanType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\CallableType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\DoubleType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\FalseType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\IntegerType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\NamedType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\NoObjectType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\NullType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\ObjectType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\PhpType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\ResourceType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\StringType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\ThisType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\TypeRegistry; use Scrutinizer\PhpAnalyzer\PhpParser\Type\UnionType; use Scrutinizer\PhpAnalyzer\PhpParser\Type\UnknownType; class PhpTypeType extends TextType { const NAME = 'PhpType'; /** @var TypeRegistry */ private static $typeRegistry; public static function setTypeRegistry(TypeRegistry $registry) { self::$typeRegistry = $registry; } public static function getTypeRegistry() { if (null === self::$typeRegistry) { self::$typeRegistry = new TypeRegistry(); } return self::$typeRegistry; } /** * Converts a value from its PHP representation to its database representation * of this type. * * @param mixed $value The value to convert. * @param AbstractPlatform $platform The currently used database platform. * @return mixed The database representation of the value. */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { if (null === $value) { return null; } if (null === self::$typeRegistry) { self::$typeRegistry = new TypeRegistry(); } if ( ! $value instanceof PhpType) { throw ConversionException::conversionFailed($value, 'string'); } return $this->convertToString($value); } public function convertToString(PhpType $value) { $typeName = $this->getStringRepr($value); $attrs = $value->getAttributes(); if (empty($attrs)) { return $typeName; } return $typeName.$this->dumpJsonLike($attrs, true); } /** * Converts a value from its database representation to its PHP representation * of this type. * * @param mixed $value The value to convert. * @param AbstractPlatform $platform The currently used database platform. * @return mixed The PHP representation of the value. */ public function convertToPHPValue($value, AbstractPlatform $platform) { $value = (is_resource($value)) ? stream_get_contents($value) : $value; if (empty($value)) { return null; } if (null === self::$typeRegistry) { self::$typeRegistry = new TypeRegistry(); } // We cannot lookup classes in the cache as this would result in another // database query during the currently executed query, and consequentially // in a FATAL error inside Doctrine's hydrators. return self::$typeRegistry->resolveType($value, TypeRegistry::LOOKUP_NO_CACHE); } // TODO: This should probably be moved to the types themselves. private function getStringRepr(PhpType $type) { switch (true) { case $type instanceof AllType: return TypeRegistry::NATIVE_ALL; // This handles the generic array type specially. case $type === self::$typeRegistry->getNativeType('array'): return 'array'; case $type instanceof ArrayType: $itemTypes = $type->getItemTypes(); if (empty($itemTypes)) { return TypeRegistry::NATIVE_ARRAY.'<'.$this->getStringRepr($type->getKeyType()).','.$this->getStringRepr($type->getElementType()).'>'; } return sprintf( 'array<%s,%s,%s>', $this->getStringRepr($type->getKeyType()), $this->getStringRepr($type->getElementType()), $this->dumpJsonLike($itemTypes, true)); case $type instanceof FalseType: return TypeRegistry::NATIVE_BOOLEAN_FALSE; case $type instanceof BooleanType: return TypeRegistry::NATIVE_BOOLEAN; case $type instanceof CallableType: return TypeRegistry::NATIVE_CALLABLE; case $type instanceof ResourceType: return TypeRegistry::NATIVE_RESOURCE; case $type instanceof DoubleType: return TypeRegistry::NATIVE_DOUBLE; case $type instanceof IntegerType: return TypeRegistry::NATIVE_INTEGER; case $type instanceof ThisType: return 'this<'.$type->getReferenceName().'>'; case $type instanceof NamedType: // If this type has been resolved, we can get the representation // of the resolved type instead of using the reference name. if ( ! $type->isNoResolvedType()) { return $this->getStringRepr($type->getReferencedType()); } return 'object<'.$type->getReferenceName().'>'; case $type instanceof NoObjectType: return TypeRegistry::NATIVE_OBJECT; case $type instanceof NoType: return TypeRegistry::NATIVE_NONE; case $type instanceof NullType: return TypeRegistry::NATIVE_NULL; case $type instanceof ObjectType: return 'object<'.$type->getName().'>'; case $type instanceof StringType: return TypeRegistry::NATIVE_STRING; case $type instanceof UnionType: $alt = array(); foreach ($type->getAlternates() as $t) { $alt[] = $this->getStringRepr($t); } return implode('|', $alt); case $type instanceof UnknownType: return $type->isChecked() ? TypeRegistry::NATIVE_UNKNOWN_CHECKED : TypeRegistry::NATIVE_UNKNOWN; } throw new \InvalidArgumentException(sprintf('The SWITCH statement is exhaustive, but got "%s".', get_class($type))); } private function dumpJsonLike(array $data, $isRoot = false) { $isList = $isRoot ? false : (array_keys($data) === range(0, count($data) - 1)); $jsonLike = $isList ? '[' : '{'; $first = true; foreach ($data as $k => $v) { if ( ! $first) { $jsonLike .= ','; } $first = false; if ( ! $isList) { $jsonLike .= json_encode($k).':'; } if ($v instanceof PhpType) { $jsonLike .= 'type('.$this->getStringRepr($v).')'; } else if ($v === null || is_scalar($v)) { $jsonLike .= json_encode($v); } else if (is_array($v)) { $jsonLike .= $this->dumpJsonLike($v); } else { throw new \RuntimeException('Encountered unsupported data of type %s.', gettype($v)); } } $jsonLike .= $isList ? ']' : '}'; return $jsonLike; } public function getName() { return self::NAME; } }
Ocramius/php-analyzer
src/Scrutinizer/PhpAnalyzer/Model/Type/PhpTypeType.php
PHP
apache-2.0
8,557
<?php namespace Laravel\Lumen\Http; use Illuminate\Http\Request as BaseRequest; use Illuminate\Support\Arr; use Illuminate\Support\Str; use RuntimeException; class Request extends BaseRequest { /** * Determine if the route name matches a given pattern. * * @param mixed $patterns * @return bool */ public function routeIs(...$patterns) { if (! Arr::exists($route = $this->route()[1], 'as')) { return false; } foreach ($patterns as $pattern) { if (Str::is($pattern, $route['as'])) { return true; } } return false; } /** * Get the route handling the request. * * @param string|null $param * @param mixed $default * * @return array|string */ public function route($param = null, $default = null) { $route = call_user_func($this->getRouteResolver()); if (is_null($route) || is_null($param)) { return $route; } return Arr::get($route[2], $param, $default); } /** * Get a unique fingerprint for the request / route / IP address. * * @return string * * @throws \RuntimeException */ public function fingerprint() { if (! $route = $this->route()) { throw new RuntimeException('Unable to generate fingerprint. Route unavailable.'); } return sha1(implode('|', [ $this->getMethod(), $this->root(), $this->path(), $this->ip(), ])); } /** * Determine if the given offset exists. * * @param string $offset * @return bool */ public function offsetExists($offset) { return Arr::has( $this->all() + $this->route()[2], $offset ); } }
tsugiproject/tsugi
vendor/laravel/lumen-framework/src/Http/Request.php
PHP
apache-2.0
1,845
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Net.Http.Headers; namespace System.Net.Http { internal static class HttpHeaderExtensions { public static void CopyTo(this HttpContentHeaders fromHeaders, HttpContentHeaders toHeaders) { Contract.Assert(fromHeaders != null, "fromHeaders cannot be null."); Contract.Assert(toHeaders != null, "toHeaders cannot be null."); foreach (KeyValuePair<string, IEnumerable<string>> header in fromHeaders) { toHeaders.TryAddWithoutValidation(header.Key, header.Value); } } } }
Terminator-Aaron/Katana
aspnetwebsrc/System.Net.Http.Formatting/HttpHeaderExtensions.cs
C#
apache-2.0
799
/* * 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.kafka.raft.internals; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import net.jqwik.api.ForAll; import net.jqwik.api.Property; import org.apache.kafka.common.record.CompressionType; import org.apache.kafka.common.record.FileRecords; import org.apache.kafka.common.record.MemoryRecords; import org.apache.kafka.common.record.Records; import org.apache.kafka.common.utils.BufferSupplier; import org.apache.kafka.raft.Batch; import org.apache.kafka.server.common.serialization.RecordSerde; import org.apache.kafka.test.TestUtils; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public final class RecordsIteratorTest { private static final RecordSerde<String> STRING_SERDE = new StringSerde(); private static Stream<Arguments> emptyRecords() throws IOException { return Stream.of( FileRecords.open(TestUtils.tempFile()), MemoryRecords.EMPTY ).map(Arguments::of); } @ParameterizedTest @MethodSource("emptyRecords") void testEmptyRecords(Records records) throws IOException { testIterator(Collections.emptyList(), records); } @Property public void testMemoryRecords( @ForAll CompressionType compressionType, @ForAll long seed ) { List<TestBatch<String>> batches = createBatches(seed); MemoryRecords memRecords = buildRecords(compressionType, batches); testIterator(batches, memRecords); } @Property public void testFileRecords( @ForAll CompressionType compressionType, @ForAll long seed ) throws IOException { List<TestBatch<String>> batches = createBatches(seed); MemoryRecords memRecords = buildRecords(compressionType, batches); FileRecords fileRecords = FileRecords.open(TestUtils.tempFile()); fileRecords.append(memRecords); testIterator(batches, fileRecords); } private void testIterator( List<TestBatch<String>> expectedBatches, Records records ) { Set<ByteBuffer> allocatedBuffers = Collections.newSetFromMap(new IdentityHashMap<>()); RecordsIterator<String> iterator = createIterator( records, mockBufferSupplier(allocatedBuffers) ); for (TestBatch<String> batch : expectedBatches) { assertTrue(iterator.hasNext()); assertEquals(batch, TestBatch.from(iterator.next())); } assertFalse(iterator.hasNext()); assertThrows(NoSuchElementException.class, iterator::next); iterator.close(); assertEquals(Collections.emptySet(), allocatedBuffers); } static RecordsIterator<String> createIterator(Records records, BufferSupplier bufferSupplier) { return new RecordsIterator<>(records, STRING_SERDE, bufferSupplier, Records.HEADER_SIZE_UP_TO_MAGIC); } static BufferSupplier mockBufferSupplier(Set<ByteBuffer> buffers) { BufferSupplier bufferSupplier = Mockito.mock(BufferSupplier.class); Mockito.when(bufferSupplier.get(Mockito.anyInt())).thenAnswer(invocation -> { int size = invocation.getArgument(0); ByteBuffer buffer = ByteBuffer.allocate(size); buffers.add(buffer); return buffer; }); Mockito.doAnswer(invocation -> { ByteBuffer released = invocation.getArgument(0); buffers.remove(released); return null; }).when(bufferSupplier).release(Mockito.any(ByteBuffer.class)); return bufferSupplier; } public static List<TestBatch<String>> createBatches(long seed) { Random random = new Random(seed); long baseOffset = random.nextInt(100); int epoch = random.nextInt(3) + 1; long appendTimestamp = random.nextInt(1000); int numberOfBatches = random.nextInt(100) + 1; List<TestBatch<String>> batches = new ArrayList<>(numberOfBatches); for (int i = 0; i < numberOfBatches; i++) { int numberOfRecords = random.nextInt(100) + 1; List<String> records = random .ints(numberOfRecords, 0, 10) .mapToObj(String::valueOf) .collect(Collectors.toList()); batches.add(new TestBatch<>(baseOffset, epoch, appendTimestamp, records)); baseOffset += records.size(); if (i % 5 == 0) { epoch += random.nextInt(3); } appendTimestamp += random.nextInt(1000); } return batches; } public static MemoryRecords buildRecords( CompressionType compressionType, List<TestBatch<String>> batches ) { ByteBuffer buffer = ByteBuffer.allocate(102400); for (TestBatch<String> batch : batches) { BatchBuilder<String> builder = new BatchBuilder<>( buffer, STRING_SERDE, compressionType, batch.baseOffset, batch.appendTimestamp, false, batch.epoch, 1024 ); for (String record : batch.records) { builder.appendRecord(record, null); } builder.build(); } buffer.flip(); return MemoryRecords.readableRecords(buffer); } public static final class TestBatch<T> { final long baseOffset; final int epoch; final long appendTimestamp; final List<T> records; TestBatch(long baseOffset, int epoch, long appendTimestamp, List<T> records) { this.baseOffset = baseOffset; this.epoch = epoch; this.appendTimestamp = appendTimestamp; this.records = records; } @Override public String toString() { return String.format( "TestBatch(baseOffset=%s, epoch=%s, records=%s)", baseOffset, epoch, records ); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TestBatch<?> testBatch = (TestBatch<?>) o; return baseOffset == testBatch.baseOffset && epoch == testBatch.epoch && Objects.equals(records, testBatch.records); } @Override public int hashCode() { return Objects.hash(baseOffset, epoch, records); } static <T> TestBatch<T> from(Batch<T> batch) { return new TestBatch<>(batch.baseOffset(), batch.epoch(), batch.appendTimestamp(), batch.records()); } } }
guozhangwang/kafka
raft/src/test/java/org/apache/kafka/raft/internals/RecordsIteratorTest.java
Java
apache-2.0
8,200
/* * 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.uima.fit.factory.testAes; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.component.ViewCreatorAnnotator; import org.apache.uima.fit.descriptor.SofaCapability; import org.apache.uima.jcas.JCas; /** */ @SofaCapability(inputSofas = CAS.NAME_DEFAULT_SOFA, outputSofas = ViewNames.REVERSE_VIEW) public class Annotator3 extends JCasAnnotator_ImplBase { @Override public void process(JCas jCas) throws AnalysisEngineProcessException { try { jCas = jCas.getView(CAS.NAME_DEFAULT_SOFA); String text = jCas.getDocumentText(); String reverseText = reverse(text); JCas reverseView = ViewCreatorAnnotator.createViewSafely(jCas, ViewNames.REVERSE_VIEW); reverseView.setDocumentText(reverseText); } catch (CASException e) { throw new AnalysisEngineProcessException(e); } } private String reverse(String string) { int stringLength = string.length(); StringBuffer returnValue = new StringBuffer(); for (int i = stringLength - 1; i >= 0; i--) { returnValue.append(string.charAt(i)); } return returnValue.toString(); } }
apache/uima-uimafit
uimafit-core/src/test/java/org/apache/uima/fit/factory/testAes/Annotator3.java
Java
apache-2.0
2,107
/* * 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.geode.distributed; import static java.lang.System.lineSeparator; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.apache.commons.lang3.StringUtils.defaultIfBlank; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.StringUtils.lowerCase; import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE; import static org.apache.geode.distributed.ConfigurationProperties.NAME; import static org.apache.geode.distributed.ConfigurationProperties.SERVER_BIND_ADDRESS; import static org.apache.geode.internal.lang.StringUtils.wrap; import static org.apache.geode.internal.lang.SystemUtils.CURRENT_DIRECTORY; import static org.apache.geode.internal.process.ProcessLauncherContext.OVERRIDDEN_DEFAULTS_PREFIX; import static org.apache.geode.internal.util.IOUtils.tryGetCanonicalPathElseGetAbsolutePath; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.ServiceLoader; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Supplier; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.logging.log4j.Logger; import org.apache.geode.SystemFailure; import org.apache.geode.annotations.Immutable; import org.apache.geode.annotations.VisibleForTesting; import org.apache.geode.annotations.internal.MakeNotStatic; import org.apache.geode.cache.Cache; import org.apache.geode.cache.Region; import org.apache.geode.cache.control.ResourceManager; import org.apache.geode.cache.partition.PartitionRegionHelper; import org.apache.geode.cache.server.CacheServer; import org.apache.geode.distributed.internal.DefaultServerLauncherCacheProvider; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.internal.GemFireVersion; import org.apache.geode.internal.cache.AbstractCacheServer; import org.apache.geode.internal.cache.CacheConfig; import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.control.InternalResourceManager; import org.apache.geode.internal.cache.tier.sockets.CacheServerHelper; import org.apache.geode.internal.inet.LocalHostUtil; import org.apache.geode.internal.lang.ObjectUtils; import org.apache.geode.internal.process.ConnectionFailedException; import org.apache.geode.internal.process.ControlNotificationHandler; import org.apache.geode.internal.process.ControllableProcess; import org.apache.geode.internal.process.FileAlreadyExistsException; import org.apache.geode.internal.process.FileControllableProcess; import org.apache.geode.internal.process.MBeanInvocationFailedException; import org.apache.geode.internal.process.PidUnavailableException; import org.apache.geode.internal.process.ProcessController; import org.apache.geode.internal.process.ProcessControllerFactory; import org.apache.geode.internal.process.ProcessControllerParameters; import org.apache.geode.internal.process.ProcessLauncherContext; import org.apache.geode.internal.process.ProcessType; import org.apache.geode.internal.process.UnableToControlProcessException; import org.apache.geode.lang.AttachAPINotFoundException; import org.apache.geode.logging.internal.executors.LoggingThread; import org.apache.geode.logging.internal.log4j.api.LogService; import org.apache.geode.management.internal.i18n.CliStrings; import org.apache.geode.management.internal.util.HostUtils; import org.apache.geode.management.internal.util.JsonUtil; import org.apache.geode.pdx.PdxSerializer; import org.apache.geode.security.AuthenticationRequiredException; import org.apache.geode.security.GemFireSecurityException; import org.apache.geode.util.internal.GeodeGlossary; /** * The ServerLauncher class is a launcher class with main method to start a Geode Server (implying * a Geode Cache Server process). * * @see AbstractLauncher * @see LocatorLauncher * @since GemFire 7.0 */ @SuppressWarnings("unused") public class ServerLauncher extends AbstractLauncher<String> { private static final Logger log = LogService.getLogger(); @Immutable private static final Map<String, String> helpMap; static { Map<String, String> help = new HashMap<>(); help.put("launcher", "A Geode launcher used to start, stop and determine a Server's status."); help.put(Command.START.getName(), String.format( "Starts a Server running in the current working directory listening on the default port (%s) bound to all IP addresses available to the localhost. The Server must be given a member name in the Geode cluster. The default server-bind-address and server-port may be overridden using the corresponding command-line options.", String.valueOf(getDefaultServerPort()))); help.put(Command.STATUS.getName(), "Displays the status of a Server given any combination of the member name/ID, PID, or the directory in which the Server is running."); help.put(Command.STOP.getName(), "Stops a running Server given given a member name/ID, PID, or the directory in which the Server is running."); help.put(Command.VERSION.getName(), "Displays Geode product version information."); help.put("assign-buckets", "Causes buckets to be assigned to the partitioned regions in the Geode cache on Server start."); help.put("debug", "Displays verbose information during the invocation of the launcher."); help.put("delete-pid-file-on-stop", "Specifies that this Server's PID file should be deleted on stop. The default is to not delete this Server's PID file until JVM exit if --delete-pid-file-on-stop is not specified."); help.put("dir", "Specifies the working directory where the Server is running. Defaults to the current working directory."); help.put("disable-default-server", "Disables the addition of a default Geode cache server."); help.put("force", "Enables any existing Server PID file to be overwritten on start. The default is to throw an error if a PID file already exists and --force is not specified."); help.put("help", "Causes Geode to print out information instead of performing the command. This option is supported by all commands."); help.put("member", "Identifies the Server by member name or ID in the Geode cluster."); help.put("pid", "Indicates the OS process ID of the running Server."); help.put("rebalance", "An option to cause the Geode cache's partitioned regions to be rebalanced on start."); help.put("redirect-output", "An option to cause the Server to redirect standard out and standard error to the Geode log file."); help.put(SERVER_BIND_ADDRESS, "Specifies the IP address on which to bind, or on which the Server is bound, listening for client requests. Defaults to all IP addresses available to the localhost."); help.put("hostname-for-clients", "An option to specify the hostname or IP address to send to clients so they can connect to this Server. The default is to use the IP address to which the Server is bound."); help.put("server-port", String.format( "Specifies the port on which the Server is listening for client requests. Defaults to %s.", String.valueOf(getDefaultServerPort()))); helpMap = Collections.unmodifiableMap(help); } @Immutable private static final Map<Command, String> usageMap; static { Map<Command, String> usage = new TreeMap<>(); usage.put(Command.START, "start <member-name> [--assign-buckets] [--disable-default-server] [--rebalance] [--server-bind-address=<IP-address>] [--server-port=<port>] [--force] [--debug] [--help]"); usage.put(Command.STATUS, "status [--member=<member-ID/Name>] [--pid=<process-ID>] [--dir=<Server-working-directory>] [--debug] [--help]"); usage.put(Command.STOP, "stop [--member=<member-ID/Name>] [--pid=<process-ID>] [--dir=<Server-working-directory>] [--debug] [--help]"); usage.put(Command.VERSION, "version"); usageMap = Collections.unmodifiableMap(usage); } private static final String DEFAULT_SERVER_LOG_EXT = ".log"; private static final String DEFAULT_SERVER_LOG_NAME = "gemfire"; private static final String SERVER_SERVICE_NAME = "Server"; @MakeNotStatic private static final AtomicReference<ServerLauncher> INSTANCE = new AtomicReference<>(); @Immutable private static final ServerLauncherCacheProvider DEFAULT_CACHE_PROVIDER = new DefaultServerLauncherCacheProvider(); private static final Logger logger = LogService.getLogger(); private volatile boolean debug; private final ControlNotificationHandler controlHandler; private final AtomicBoolean starting = new AtomicBoolean(false); private final boolean assignBuckets; private final boolean deletePidFileOnStop; private final boolean disableDefaultServer; private final boolean force; private final boolean help; private final boolean rebalance; private final boolean redirectOutput; private volatile Cache cache; private final CacheConfig cacheConfig; private final Command command; private final InetAddress serverBindAddress; private final Integer pid; private final Integer serverPort; private final Properties distributedSystemProperties; private final String memberName; private final String springXmlLocation; private final String workingDirectory; // NOTE in addition to debug, the other shared, mutable state private volatile String statusMessage; private final Float criticalHeapPercentage; private final Float evictionHeapPercentage; private final Float criticalOffHeapPercentage; private final Float evictionOffHeapPercentage; private final String hostNameForClients; private final Integer maxConnections; private final Integer maxMessageCount; private final Integer messageTimeToLive; private final Integer socketBufferSize; private final Integer maxThreads; private volatile ControllableProcess process; private final ServerControllerParameters controllerParameters; private final Runnable startupCompletionAction; private final Consumer<Throwable> startupExceptionAction; private final ServerLauncherCacheProvider serverLauncherCacheProvider; private final Supplier<ControllableProcess> controllableProcessFactory; /** * Launches a Geode Server from the command-line configured with the given arguments. * * @param args the command-line arguments used to configure the Geode Server at runtime. */ public static void main(final String... args) { try { new Builder(args).build().run(); } catch (AttachAPINotFoundException handled) { System.err.println(handled.getMessage()); } } private static Integer getDefaultServerPort() { return Integer.getInteger(AbstractCacheServer.TEST_OVERRIDE_DEFAULT_PORT_PROPERTY, CacheServer.DEFAULT_PORT); } /** * Gets the instance of the ServerLauncher used to launch the Geode Cache Server, or null if * this VM does not have an instance of ServerLauncher indicating no Geode Cache Server is * running. * * @return the instance of ServerLauncher used to launcher a Geode Cache Server in this VM. */ public static ServerLauncher getInstance() { return INSTANCE.get(); } /** * Gets the ServerState for this process or null if this process was not launched using this VM's * ServerLauncher reference . * * @return the ServerState for this process or null. */ public static ServerState getServerState() { return getInstance() != null ? getInstance().status() : null; } /** * Private constructor used to properly construct an immutable instance of the ServerLauncher * using a Builder. The Builder is used to configure a ServerLauncher instance. The Builder can * process user input from the command-line or be used programmatically to properly construct an * instance of the ServerLauncher using the API. * * @param builder an instance of ServerLauncher.Builder for configuring and constructing an * instance of the ServerLauncher. * @see ServerLauncher.Builder */ private ServerLauncher(final Builder builder) { cache = builder.getCache(); cacheConfig = builder.getCacheConfig(); command = builder.getCommand(); assignBuckets = Boolean.TRUE.equals(builder.getAssignBuckets()); setDebug(Boolean.TRUE.equals(builder.getDebug())); deletePidFileOnStop = Boolean.TRUE.equals(builder.getDeletePidFileOnStop()); disableDefaultServer = Boolean.TRUE.equals(builder.getDisableDefaultServer()); distributedSystemProperties = builder.getDistributedSystemProperties(); force = Boolean.TRUE.equals(builder.getForce()); help = Boolean.TRUE.equals(builder.getHelp()); hostNameForClients = builder.getHostNameForClients(); memberName = builder.getMemberName(); pid = builder.getPid(); rebalance = Boolean.TRUE.equals(builder.getRebalance()); redirectOutput = Boolean.TRUE.equals(builder.getRedirectOutput()); serverBindAddress = builder.getServerBindAddress(); serverPort = builder.getServerPort(); springXmlLocation = builder.getSpringXmlLocation(); workingDirectory = builder.getWorkingDirectory(); criticalHeapPercentage = builder.getCriticalHeapPercentage(); evictionHeapPercentage = builder.getEvictionHeapPercentage(); criticalOffHeapPercentage = builder.getCriticalOffHeapPercentage(); evictionOffHeapPercentage = builder.getEvictionOffHeapPercentage(); maxConnections = builder.getMaxConnections(); maxMessageCount = builder.getMaxMessageCount(); maxThreads = builder.getMaxThreads(); messageTimeToLive = builder.getMessageTimeToLive(); socketBufferSize = builder.getSocketBufferSize(); controllerParameters = new ServerControllerParameters(); startupCompletionAction = builder.getStartupCompletionAction(); startupExceptionAction = builder.getStartupExceptionAction(); controlHandler = new ControlNotificationHandler() { @Override public void handleStop() { if (isStoppable()) { stopInProcess(); } } @Override public ServiceState<?> handleStatus() { return statusInProcess(); } }; serverLauncherCacheProvider = builder.getServerLauncherCacheProvider(); controllableProcessFactory = builder.getControllableProcessFactory(); Integer serverPort = builder.isServerPortSetByUser() && this.serverPort != null ? this.serverPort : null; String serverBindAddress = builder.isServerBindAddressSetByUser() && this.serverBindAddress != null ? this.serverBindAddress.getHostAddress() : null; ServerLauncherParameters.INSTANCE .withPort(serverPort) .withMaxThreads(maxThreads) .withBindAddress(serverBindAddress) .withMaxConnections(maxConnections) .withMaxMessageCount(maxMessageCount) .withSocketBufferSize(socketBufferSize) .withMessageTimeToLive(messageTimeToLive) .withHostnameForClients(hostNameForClients) .withDisableDefaultServer(disableDefaultServer); } /** * Gets a reference to the {@code Cache} that was created by this {@code ServerLauncher}. * * @return a reference to the Cache * @see Cache */ public Cache getCache() { if (cache != null) { boolean isReconnecting = cache.isReconnecting(); if (isReconnecting) { Cache newCache = cache.getReconnectedCache(); if (newCache != null) { cache = newCache; } } } return cache; } /** * Gets the CacheConfig object used to configure additional Geode Cache components and features * (e.g. PDX). * * @return a CacheConfig object with additional Geode Cache configuration meta-data used on * startup to configure the Cache. */ public CacheConfig getCacheConfig() { final CacheConfig copy = new CacheConfig(); copy.setDeclarativeConfig(cacheConfig); return copy; } /** * Gets an identifier that uniquely identifies and represents the Server associated with this * launcher. * * @return a String value identifier to uniquely identify the Server and it's launcher. * @see #getServerBindAddressAsString() * @see #getServerPortAsString() */ public String getId() { final StringBuilder buffer = new StringBuilder(ServerState.getServerBindAddressAsString(this)); final String serverPort = ServerState.getServerPortAsString(this); if (isNotBlank(serverPort)) { buffer.append("[").append(serverPort).append("]"); } return buffer.toString(); } /** * Get the Server launcher command used to invoke the Server. * * @return the Server launcher command used to invoke the Server. * @see ServerLauncher.Command */ public Command getCommand() { return command; } /** * Determines whether buckets should be assigned to partitioned regions in the cache upon Server * start. * * @return a boolean indicating if buckets should be assigned upon Server start. */ public boolean isAssignBuckets() { return assignBuckets; } /** * Determines whether a default cache server will be added when the Geode Server comes online. * * @return a boolean value indicating whether to add a default cache server. */ public boolean isDisableDefaultServer() { return disableDefaultServer; } /** * Determines whether the PID file is allowed to be overwritten when the Server is started and a * PID file already exists in the Server's specified working directory. * * @return boolean indicating if force has been enabled. */ public boolean isForcing() { return force; } /** * Determines whether this launcher will be used to display help information. If so, then none of * the standard Server launcher commands will be used to affect the state of the Server. A * launcher is said to be 'helping' if the user entered the "--help" option (switch) on the * command-line. * * @return a boolean value indicating if this launcher is used for displaying help information. * @see ServerLauncher.Command */ public boolean isHelping() { return help; } /** * Determines whether a rebalance operation on the cache will occur upon starting the Geode * server using this launcher. * * @return a boolean indicating if the cache will be rebalance when the Geode server starts. */ public boolean isRebalancing() { return rebalance; } /** * Determines whether this launcher will redirect output to system logs when starting a new Server * process. * * @return a boolean value indicating if this launcher will redirect output to system logs when * starting a new Server process */ public boolean isRedirectingOutput() { return redirectOutput; } /** * Gets the name of the log file used to log information about this Server. * * @return a String value indicating the name of this Server's log file. */ @Override public String getLogFileName() { return defaultIfBlank(getMemberName(), DEFAULT_SERVER_LOG_NAME).concat(DEFAULT_SERVER_LOG_EXT); } /** * Gets the name of this member (this Server) in the Geode distributed system as determined by * the 'name' Geode property. * * @return a String indicating the name of the member (this Server) in the Geode distributed * system. */ @Override public String getMemberName() { return defaultIfBlank(memberName, super.getMemberName()); } /** * Gets the user-specified process ID (PID) of the running Server that ServerLauncher uses to * issue status and stop commands to the Server. * * @return an Integer value indicating the process ID (PID) of the running Server. */ @Override public Integer getPid() { return pid; } /** * Gets the Geode Distributed System (cluster) Properties. * * @return a Properties object containing the configuration settings for the Geode Distributed * System (cluster). * @see Properties */ public Properties getProperties() { return (Properties) distributedSystemProperties.clone(); } /** * Gets the IP address to which the Server is bound listening for and accepting cache client * connections. This property should not be confused with 'bindAddress' ServerLauncher property, * which is the port for binding the Server's ServerSocket used in distribution and messaging * between the peers of the Geode distributed system. * * @return an InetAddress indicating the IP address that the Server is bound to listening for and * accepting cache client connections in a client/server topology. */ public InetAddress getServerBindAddress() { return serverBindAddress; } /** * Gets the host, as either hostname or IP address, on which the Server was bound and running. An * attempt is made to get the canonical hostname for IP address to which the Server was bound for * accepting client requests. If the server bind address is null or localhost is unknown, then a * default String value of "localhost/127.0.0.1" is returned. * * Note, this information is purely information and should not be used to re-construct state or * for other purposes. * * @return the hostname or IP address of the host running the Server, based on the bind-address, * or 'localhost/127.0.0.1' if the bind address is null and localhost is unknown. * @see InetAddress * @see #getServerBindAddress() */ public String getServerBindAddressAsString() { try { if (getServerBindAddress() != null) { return getServerBindAddress().getCanonicalHostName(); } return LocalHostUtil.getCanonicalLocalHostName(); } catch (UnknownHostException handled) { // Returning localhost/127.0.0.1 implies the serverBindAddress was null and no IP address // for localhost could be found return "localhost/127.0.0.1"; } } /** * Gets the port on which the Server is listening for cache client connections. This property * should not be confused with the 'port' ServerLauncher property, which is used by the Server to * set the 'tcp-port' distribution config property and is used by the ServerSocket for peer * distribution and messaging. * * @return an Integer value indicating the port the Server is listening on for cache client * connections in the client/server topology. */ public Integer getServerPort() { return serverPort; } /** * Gets the server port on which the Server is listening for client requests represented as a * String value. * * @return a String representing the server port on which the Server is listening for client * requests. * @see #getServerPort() */ public String getServerPortAsString() { Integer v1 = getServerPort(); return (v1 != null ? v1 : getDefaultServerPort()).toString(); } /** * Gets the name for a Geode Server. * * @return a String indicating the name for a Geode Server. */ @Override public String getServiceName() { return SERVER_SERVICE_NAME; } /** * Gets the location of the Spring XML configuration meta-data file used to bootstrap, configure * and initialize the Geode Server on start. * <p> * * @return a String indicating the location of the Spring XML configuration file. * @see ServerLauncher.Builder#getSpringXmlLocation() */ public String getSpringXmlLocation() { return springXmlLocation; } /** * Determines whether this Geode Server was configured and initialized with Spring configuration * meta-data. * <p> * * @return a boolean value indicating whether this Geode Server was configured with Spring * configuration meta-data. */ public boolean isSpringXmlLocationSpecified() { return isNotBlank(springXmlLocation); } /** * Gets the working directory pathname in which the Server will be run. * * @return a String value indicating the pathname of the Server's working directory. */ @Override public String getWorkingDirectory() { return workingDirectory; } public Float getCriticalHeapPercentage() { return criticalHeapPercentage; } public Float getEvictionHeapPercentage() { return evictionHeapPercentage; } public Float getCriticalOffHeapPercentage() { return criticalOffHeapPercentage; } public Float getEvictionOffHeapPercentage() { return evictionOffHeapPercentage; } public String getHostNameForClients() { return hostNameForClients; } public Integer getMaxConnections() { return maxConnections; } public Integer getMaxMessageCount() { return maxMessageCount; } public Integer getMessageTimeToLive() { return messageTimeToLive; } public Integer getMaxThreads() { return maxThreads; } public Integer getSocketBufferSize() { return socketBufferSize; } private static final String TWO_NEW_LINES = lineSeparator() + lineSeparator(); /** * Displays help for the specified Server launcher command to standard err. If the Server launcher * command is unspecified, then usage information is displayed instead. * * @param command the Server launcher command in which to display help information. * @see #usage() */ public void help(final Command command) { if (Command.isUnspecified(command)) { usage(); } else { info(wrap(helpMap.get(command.getName()), 80, "")); info(TWO_NEW_LINES + "usage: " + TWO_NEW_LINES); info(wrap("> java ... " + getClass().getName() + ' ' + usageMap.get(command), 80, "\t\t")); info(TWO_NEW_LINES + "options: " + TWO_NEW_LINES); for (final String option : command.getOptions()) { info(wrap("--" + option + ": " + helpMap.get(option) + lineSeparator(), 80, "\t")); } info(TWO_NEW_LINES); } } /** * Displays usage information on the proper invocation of the ServerLauncher from the command-line * to standard err. * * @see #help(ServerLauncher.Command) */ public void usage() { info(wrap(helpMap.get("launcher"), 80, "\t")); info(TWO_NEW_LINES + "START" + TWO_NEW_LINES); help(Command.START); info("STATUS" + TWO_NEW_LINES); help(Command.STATUS); info("STOP" + TWO_NEW_LINES); help(Command.STOP); } /** * A Runnable method used to invoke the Geode server (cache server) with the specified command. * From run, a user can invoke 'start', 'status', 'stop' and 'version'. Note, that 'version' is * also a command-line option, but can be treated as a "command" as well. * * @see Runnable */ @Override public void run() { if (!isHelping()) { switch (getCommand()) { case START: info(start()); waitOnServer(); break; case STATUS: info(status()); break; case STOP: info(stop()); break; case VERSION: info(version()); break; default: usage(); } } else { help(getCommand()); } } /** * Gets a File reference with the path to the PID file for the Server. * * @return a File reference to the path of the Server's PID file. */ protected File getServerPidFile() { return new File(getWorkingDirectory(), ProcessType.SERVER.getPidFileName()); } /** * Determines whether a Geode Cache Server can be started with this instance of ServerLauncher. * * @return a boolean indicating whether a Geode Cache Server can be started with this instance * of ServerLauncher, which is true if the ServerLauncher has not already started a Server * or a Server is not already running. * @see #start() */ private boolean isStartable() { return !isRunning() && starting.compareAndSet(false, true); } /** * Invokes the 'start' command and operation to startup a Geode server (a cache server). Note, * this method will cause the JVM to block upon server start, providing the calling Thread is a * non-daemon Thread. * * @see #run() */ public ServerState start() { long startTime = System.currentTimeMillis(); if (isStartable()) { INSTANCE.compareAndSet(null, this); try { process = getControllableProcess(); if (!isDisableDefaultServer()) { assertPortAvailable(getServerBindAddress(), getServerPort()); } SystemFailure.setExitOK(true); ProcessLauncherContext.set(isRedirectingOutput(), getOverriddenDefaults(), (String statusMessage) -> { debug("Callback setStatus(String) called with message (%1$s)...", statusMessage); this.statusMessage = statusMessage; }); try { final Properties gemfireProperties = getDistributedSystemProperties(getProperties()); cache = createCache(gemfireProperties); // Set the resource manager options if (criticalHeapPercentage != null) { cache.getResourceManager().setCriticalHeapPercentage(getCriticalHeapPercentage()); } if (evictionHeapPercentage != null) { cache.getResourceManager().setEvictionHeapPercentage(getEvictionHeapPercentage()); } if (criticalOffHeapPercentage != null) { cache.getResourceManager() .setCriticalOffHeapPercentage(getCriticalOffHeapPercentage()); } if (evictionOffHeapPercentage != null) { cache.getResourceManager() .setEvictionOffHeapPercentage(getEvictionOffHeapPercentage()); } cache.setIsServer(true); startCacheServer(cache); assignBuckets(cache); rebalance(cache); } finally { ProcessLauncherContext.remove(); } awaitStartupTasks(cache, startTime); debug("Running Server on (%1$s) in (%2$s) as (%3$s)...", getId(), getWorkingDirectory(), getMember()); running.set(true); return new ServerState(this, Status.ONLINE); } catch (AuthenticationRequiredException e) { failOnStart(e); throw new AuthenticationRequiredException( "user/password required. Please start your server with --user and --password. " + e.getMessage()); } catch (GemFireSecurityException e) { failOnStart(e); throw new GemFireSecurityException(e.getMessage()); } catch (IOException e) { failOnStart(e); throw new RuntimeException( String.format("An IO error occurred while starting a %s in %s on %s: %s", getServiceName(), getWorkingDirectory(), getId(), e.getMessage()), e); } catch (FileAlreadyExistsException e) { failOnStart(e); throw new RuntimeException( String.format("A PID file already exists and a %s may be running in %s on %s.", getServiceName(), getWorkingDirectory(), getId()), e); } catch (PidUnavailableException e) { failOnStart(e); throw new RuntimeException( String.format("The process ID could not be determined while starting %s %s in %s: %s", getServiceName(), getId(), getWorkingDirectory(), e.getMessage()), e); } catch (RuntimeException | Error e) { failOnStart(e); throw e; } catch (Exception e) { failOnStart(e); throw new RuntimeException(e); } finally { starting.set(false); } } throw new IllegalStateException( String.format("A %s is already running in %s on %s.", getServiceName(), getWorkingDirectory(), getId())); } Cache createCache(Properties gemfireProperties) { Iterable<ServerLauncherCacheProvider> loader = getServerLauncherCacheProviders(); for (ServerLauncherCacheProvider provider : loader) { Cache cache = provider.createCache(gemfireProperties, this); if (cache != null) { return cache; } } return DEFAULT_CACHE_PROVIDER.createCache(gemfireProperties, this); } private Iterable<ServerLauncherCacheProvider> getServerLauncherCacheProviders() { return serverLauncherCacheProvider != null ? Collections.singleton(serverLauncherCacheProvider) : ServiceLoader.load(ServerLauncherCacheProvider.class); } /** * A helper method to ensure the same sequence of actions are taken when the Server fails to start * caused by some exception. * * @param cause the Throwable thrown during the startup operation on the Server. */ private void failOnStart(final Throwable cause) { if (cache != null) { cache.close(); cache = null; } if (process != null) { process.stop(deletePidFileOnStop); process = null; } INSTANCE.compareAndSet(this, null); running.set(false); } /** * Determines whether the specified Cache has any CacheServers. * * @param cache the Cache to check for existing CacheServers. * @return a boolean value indicating if any CacheServers were added to the Cache. */ protected boolean isServing(final Cache cache) { return !cache.getCacheServers().isEmpty(); } /** * Determines whether to continue waiting and keep the Geode non-Server data member running. * * @param cache the Cache associated with this Geode (non-Server) data member. * @return a boolean value indicating whether the Geode data member should continue running, as * determined by the running flag and a connection to the distributed system (Geode * cluster). */ boolean isWaiting(final Cache cache) { return isRunning() && (cache.getDistributedSystem().isConnected() || cache.isReconnecting()); } /** * Causes the calling Thread to block until the Geode Cache Server/Data Member stops. */ public void waitOnServer() { assert getCache() != null : "The Cache Server must first be started with a call to start!"; if (!isServing(getCache())) { Throwable cause = null; try { while (isWaiting(getCache())) { try { synchronized (this) { wait(500L); } } catch (InterruptedException handled) { // loop back around } } } catch (RuntimeException e) { cause = e; throw e; } finally { failOnStart(cause); } } } /** * Determines whether a default server (a cache server) should be created on startup as determined * by the absence of specifying the --disable-default-server command-line option (switch). In * addition, a default cache server is started only if no cache servers have been added to the * Cache by way of cache.xml. * * @param cache the reference to the Cache to check for any existing cache servers. * @return a boolean indicating whether a default server should be added to the Cache. * @see #isDisableDefaultServer() */ protected boolean isDefaultServerEnabled(final Cache cache) { return cache.getCacheServers().isEmpty() && !isDisableDefaultServer(); } /** * If the default server (cache server) has not been disabled and no prior cache servers were * added to the cache, then this method will add a cache server to the Cache and start the server * Thread on the specified bind address and port. * * @param cache the Cache to which the server will be added. * @throws IOException if the Cache server fails to start due to IO error. */ private void startCacheServer(final Cache cache) throws IOException { if (isDefaultServerEnabled(cache)) { final String serverBindAddress = getServerBindAddress() == null ? null : getServerBindAddress().getHostAddress(); final Integer serverPort = getServerPort(); final CacheServer cacheServer = cache.addCacheServer(); cacheServer.setBindAddress(serverBindAddress); cacheServer.setPort(serverPort); if (getMaxThreads() != null) { cacheServer.setMaxThreads(getMaxThreads()); } if (getMaxConnections() != null) { cacheServer.setMaxConnections(getMaxConnections()); } if (getMaxMessageCount() != null) { cacheServer.setMaximumMessageCount(getMaxMessageCount()); } if (getMessageTimeToLive() != null) { cacheServer.setMessageTimeToLive(getMessageTimeToLive()); } if (getSocketBufferSize() != null) { cacheServer.setSocketBufferSize(getSocketBufferSize()); } if (getHostNameForClients() != null) { cacheServer.setHostnameForClients(getHostNameForClients()); } CacheServerHelper.setIsDefaultServer(cacheServer); cacheServer.start(); } } private void awaitStartupTasks(Cache cache, long startTime) { Runnable afterStartup = startupCompletionAction == null ? () -> logStartCompleted(startTime) : startupCompletionAction; Consumer<Throwable> exceptionAction = startupExceptionAction == null ? (throwable) -> logStartCompletedWithError(startTime, throwable) : startupExceptionAction; CompletableFuture<Void> startupTasks = ((InternalResourceManager) cache.getResourceManager()) .allOfStartupTasks(); startupTasks .thenRun(afterStartup) .exceptionally((throwable) -> { exceptionAction.accept(throwable); return null; }) .join(); } private void logStartCompleted(long startTime) { long startupDuration = System.currentTimeMillis() - startTime; log.info("Server {} startup completed in {} ms", memberName, startupDuration); } private void logStartCompletedWithError(long startTime, Throwable throwable) { long startupDuration = System.currentTimeMillis() - startTime; log.error("Server {} startup completed in {} ms with error: {}", memberName, startupDuration, throwable, throwable); } /** * Causes a rebalance operation to occur on the given Cache. * * @param cache the reference to the Cache to rebalance. * @see ResourceManager#createRebalanceFactory() */ private void rebalance(final Cache cache) { if (isRebalancing()) { cache.getResourceManager().createRebalanceFactory().start(); } } /** * Determines whether the user indicated that buckets should be assigned on cache server start * using the --assign-buckets command-line option (switch) at the command-line as well as whether * the option is technically allowed. The option is only allowed if the instance of the Cache is * the internal GemFireCacheImpl at present. * * @param cache the Cache reference to check for instance type. * @return a boolean indicating if bucket assignment is both enabled and allowed. * @see #isAssignBuckets() */ private boolean isAssignBucketsAllowed(final Cache cache) { return isAssignBuckets() && cache instanceof GemFireCacheImpl; } /** * Assigns buckets to individual Partitioned Regions of the Cache. * * @param cache the Cache who's Partitioned Regions are accessed to assign buckets to. * @see PartitionRegionHelper#assignBucketsToPartitions(Region) */ private void assignBuckets(final Cache cache) { if (isAssignBucketsAllowed(cache)) { for (PartitionedRegion region : ((InternalCache) cache).getPartitionedRegions()) { PartitionRegionHelper.assignBucketsToPartitions(region); } } } /** * Determines whether the Server is the process of starting or is already running. * * @return a boolean indicating if the Server is starting or is already running. */ protected boolean isStartingOrRunning() { return starting.get() || isRunning(); } /** * Invokes the 'status' command and operation to check the status of a Geode server (a cache * server). */ public ServerState status() { final ServerLauncher launcher = getInstance(); // if this instance is running then return local status if (isStartingOrRunning()) { debug( "Getting status from the ServerLauncher instance that actually launched the Geode Cache Server.%n"); return new ServerState(this, isRunning() ? Status.ONLINE : Status.STARTING); } if (isPidInProcess() && launcher != null) { return launcher.statusInProcess(); } if (getPid() != null) { debug("Getting Server status using process ID (%1$s)%n", getPid()); return statusWithPid(); } // attempt to get status using workingDirectory if (getWorkingDirectory() != null) { debug("Getting Server status using working directory (%1$s)%n", getWorkingDirectory()); return statusWithWorkingDirectory(); } debug("This ServerLauncher was not the instance used to launch the Geode Cache Server, and " + "neither PID nor working directory were specified; the Server's state is unknown.%n"); return new ServerState(this, Status.NOT_RESPONDING); } private ServerState statusInProcess() { if (isStartingOrRunning()) { debug( "Getting status from the ServerLauncher instance that actually launched the Geode Cache Server.%n"); return new ServerState(this, isRunning() ? Status.ONLINE : Status.STARTING); } return new ServerState(this, Status.NOT_RESPONDING); } private ServerState statusWithPid() { try { final ProcessController controller = new ProcessControllerFactory() .createProcessController(controllerParameters, getPid()); controller.checkPidSupport(); final String statusJson = controller.status(); return ServerState.fromJson(statusJson); } catch (ConnectionFailedException handled) { // failed to attach to server JVM return createNoResponseState(handled, "Failed to connect to server with process id " + getPid()); } catch (IOException | MBeanInvocationFailedException | UnableToControlProcessException | InterruptedException | TimeoutException handled) { return createNoResponseState(handled, "Failed to communicate with server with process id " + getPid()); } } private ServerState statusWithWorkingDirectory() { int parsedPid = 0; try { final ProcessController controller = new ProcessControllerFactory().createProcessController(controllerParameters, new File(getWorkingDirectory()), ProcessType.SERVER.getPidFileName()); parsedPid = controller.getProcessId(); // note: in-process request will go infinite loop unless we do the following if (parsedPid == identifyPid()) { final ServerLauncher runningLauncher = getInstance(); if (runningLauncher != null) { return runningLauncher.statusInProcess(); } } final String statusJson = controller.status(); return ServerState.fromJson(statusJson); } catch (ConnectionFailedException handled) { // failed to attach to server JVM return createNoResponseState(handled, "Failed to connect to server with process id " + parsedPid); } catch (FileNotFoundException handled) { // could not find pid file return createNoResponseState(handled, "Failed to find process file " + ProcessType.SERVER.getPidFileName() + " in " + getWorkingDirectory()); } catch (IOException | MBeanInvocationFailedException | UnableToControlProcessException | TimeoutException handled) { return createNoResponseState(handled, "Failed to communicate with server with process id " + parsedPid); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); return createNoResponseState(handled, "Interrupted while trying to communicate with server with process id " + parsedPid); } catch (PidUnavailableException handled) { // couldn't determine pid from within server JVM return createNoResponseState(handled, "Failed to find usable process id within file " + ProcessType.SERVER.getPidFileName() + " in " + getWorkingDirectory()); } } /** * Determines whether the Server can be stopped in-process, such as when a Server is embedded in * an application and the ServerLauncher API is being used. * * @return a boolean indicating whether the Server can be stopped in-process (the application's * process with an embedded Server). */ private boolean isStoppable() { return isRunning() && getCache() != null; } /** * Invokes the 'stop' command and operation to stop a Geode server (a cache server). */ public ServerState stop() { final ServerLauncher launcher = getInstance(); // if this instance is running then stop it if (isStoppable()) { return stopInProcess(); } // if in-process but difference instance of ServerLauncher if (isPidInProcess() && launcher != null) { return launcher.stopInProcess(); } // attempt to stop using pid if provided if (getPid() != null) { return stopWithPid(); } // attempt to stop using workingDirectory if (getWorkingDirectory() != null) { return stopWithWorkingDirectory(); } return new ServerState(this, Status.NOT_RESPONDING); } private ServerState stopInProcess() { if (isStoppable()) { if (cache.isReconnecting()) { cache.getDistributedSystem().stopReconnecting(); } // Another case of needing to use a non-daemon thread to keep the JVM alive until a clean // shutdown can be performed. If not, the JVM may exit too early causing the member to be // seen as having crashed and not cleanly departed. Thread t = new LoggingThread("ServerLauncherStopper", false, this::doStopInProcess); t.start(); try { t.join(); } catch (InterruptedException ignore) { // no matter, we're shutting down... } // note: other thread may return Status.NOT_RESPONDING now INSTANCE.compareAndSet(this, null); running.set(false); return new ServerState(this, Status.STOPPED); } return new ServerState(this, Status.NOT_RESPONDING); } private void doStopInProcess() { cache.close(); cache = null; if (process != null) { process.stop(deletePidFileOnStop); process = null; } } private ServerState stopWithPid() { try { final ProcessController controller = new ProcessControllerFactory() .createProcessController(controllerParameters, getPid()); controller.checkPidSupport(); controller.stop(); return new ServerState(this, Status.STOPPED); } catch (ConnectionFailedException handled) { // failed to attach to server JVM return createNoResponseState(handled, "Failed to connect to server with process id " + getPid()); } catch (IOException | MBeanInvocationFailedException | UnableToControlProcessException handled) { return createNoResponseState(handled, "Failed to communicate with server with process id " + getPid()); } } private ServerState stopWithWorkingDirectory() { int parsedPid = 0; try { final ProcessController controller = new ProcessControllerFactory().createProcessController(controllerParameters, new File(getWorkingDirectory()), ProcessType.SERVER.getPidFileName()); parsedPid = controller.getProcessId(); // NOTE in-process request will go infinite loop unless we do the following if (parsedPid == identifyPid()) { final ServerLauncher runningLauncher = getInstance(); if (runningLauncher != null) { return runningLauncher.stopInProcess(); } } controller.stop(); return new ServerState(this, Status.STOPPED); } catch (ConnectionFailedException handled) { // failed to attach to server JVM return createNoResponseState(handled, "Failed to connect to server with process id " + parsedPid); } catch (FileNotFoundException handled) { // could not find pid file return createNoResponseState(handled, "Failed to find process file " + ProcessType.SERVER.getPidFileName() + " in " + getWorkingDirectory()); } catch (IOException | MBeanInvocationFailedException | UnableToControlProcessException handled) { return createNoResponseState(handled, "Failed to communicate with server with process id " + parsedPid); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); return createNoResponseState(handled, "Interrupted while trying to communicate with server with process id " + parsedPid); } catch (PidUnavailableException handled) { // couldn't determine pid from within server JVM return createNoResponseState(handled, "Failed to find usable process id within file " + ProcessType.SERVER.getPidFileName() + " in " + getWorkingDirectory()); } catch (TimeoutException handled) { return createNoResponseState(handled, "Timed out trying to find usable process id within file " + ProcessType.SERVER.getPidFileName() + " in " + getWorkingDirectory()); } } private ServerState createNoResponseState(final Exception cause, final String errorMessage) { debug(ExceptionUtils.getStackTrace(cause) + errorMessage); return new ServerState(this, Status.NOT_RESPONDING, errorMessage); } private Properties getOverriddenDefaults() throws IOException { final Properties overriddenDefaults = new Properties(); overriddenDefaults.setProperty(OVERRIDDEN_DEFAULTS_PREFIX.concat(LOG_FILE), getLogFile().getCanonicalPath()); for (String key : System.getProperties().stringPropertyNames()) { if (key.startsWith(OVERRIDDEN_DEFAULTS_PREFIX)) { overriddenDefaults.setProperty(key, System.getProperty(key)); } } return overriddenDefaults; } private ControllableProcess getControllableProcess() throws IOException, FileAlreadyExistsException, PidUnavailableException { return controllableProcessFactory != null ? controllableProcessFactory.get() : new FileControllableProcess(controlHandler, new File(getWorkingDirectory()), ProcessType.SERVER, isForcing()); } private class ServerControllerParameters implements ProcessControllerParameters { @Override public File getPidFile() { return getServerPidFile(); } @Override public File getDirectory() { return new File(getWorkingDirectory()); } @Override public int getProcessId() { return getPid(); } @Override public ProcessType getProcessType() { return ProcessType.SERVER; } @Override public ObjectName getNamePattern() { try { return ObjectName.getInstance("GemFire:type=Member,*"); } catch (MalformedObjectNameException | NullPointerException handled) { return null; } } @Override public String getPidAttribute() { return "ProcessId"; } @Override public String getStopMethod() { return "shutDownMember"; } @Override public String getStatusMethod() { return "status"; } @Override public String[] getAttributes() { return new String[] {"Server"}; } @Override public Object[] getValues() { return new Object[] {Boolean.TRUE}; } } /** * The Builder class, modeled after the Builder creational design pattern, is used to construct a * properly configured and initialized instance of the ServerLauncher to control and run Geode * servers (in particular, cache servers). */ public static class Builder { @Immutable protected static final Command DEFAULT_COMMAND = Command.UNSPECIFIED; private boolean serverBindAddressSetByUser; private boolean serverPortSetByUser; private Boolean assignBuckets; private Boolean debug; private Boolean deletePidFileOnStop; private Boolean disableDefaultServer; private Boolean force; private Boolean help; private Boolean rebalance; private Boolean redirectOutput; private Cache cache; private final CacheConfig cacheConfig = new CacheConfig(); private Command command; private InetAddress serverBindAddress; private Integer pid; private Integer serverPort; private final Properties distributedSystemProperties = new Properties(); private String memberName; private String springXmlLocation; private String workingDirectory; private Float criticalHeapPercentage; private Float evictionHeapPercentage; private Float criticalOffHeapPercentage; private Float evictionOffHeapPercentage; private String hostNameForClients; private Integer loadPollInterval; private Integer maxConnections; private Integer maxMessageCount; private Integer messageTimeToLive; private Integer socketBufferSize; private Integer maxThreads; private Runnable startupCompletionAction; private Consumer<Throwable> startupExceptionAction; private ServerLauncherCacheProvider serverLauncherCacheProvider; private Supplier<ControllableProcess> controllableProcessFactory; /** * Default constructor used to create an instance of the Builder class for programmatical * access. */ public Builder() { // nothing } /** * Constructor used to create and configure an instance of the Builder class with the specified * arguments, passed in from the command-line when launching an instance of this class from the * command-line using the Java launcher. * * @param args the array of arguments used to configure the Builder. * @see #parseArguments(String...) */ public Builder(final String... args) { parseArguments(args != null ? args : new String[0]); } /** * Gets an instance of the JOptSimple OptionParser to parse the command-line arguments for * Server. * * @return an instance of the JOptSimple OptionParser configured with the command-line options * used by the Server. */ private OptionParser getParser() { OptionParser parser = new OptionParser(true); parser.accepts("assign-buckets"); parser.accepts("debug"); parser.accepts("dir").withRequiredArg().ofType(String.class); parser.accepts("disable-default-server"); parser.accepts("force"); parser.accepts("help"); parser.accepts("member").withRequiredArg().ofType(String.class); parser.accepts("pid").withRequiredArg().ofType(Integer.class); parser.accepts("rebalance"); parser.accepts("redirect-output"); parser.accepts(SERVER_BIND_ADDRESS).withRequiredArg().ofType(String.class); parser.accepts("server-port").withRequiredArg().ofType(Integer.class); parser.accepts("spring-xml-location").withRequiredArg().ofType(String.class); parser.accepts("version"); parser.accepts(CliStrings.START_SERVER__CRITICAL__HEAP__PERCENTAGE).withRequiredArg() .ofType(Float.class); parser.accepts(CliStrings.START_SERVER__EVICTION__HEAP__PERCENTAGE).withRequiredArg() .ofType(Float.class); parser.accepts(CliStrings.START_SERVER__CRITICAL_OFF_HEAP_PERCENTAGE).withRequiredArg() .ofType(Float.class); parser.accepts(CliStrings.START_SERVER__EVICTION_OFF_HEAP_PERCENTAGE).withRequiredArg() .ofType(Float.class); parser.accepts(CliStrings.START_SERVER__MAX__CONNECTIONS).withRequiredArg() .ofType(Integer.class); parser.accepts(CliStrings.START_SERVER__MAX__MESSAGE__COUNT).withRequiredArg() .ofType(Integer.class); parser.accepts(CliStrings.START_SERVER__MAX__THREADS).withRequiredArg().ofType(Integer.class); parser.accepts(CliStrings.START_SERVER__MESSAGE__TIME__TO__LIVE).withRequiredArg() .ofType(Integer.class); parser.accepts(CliStrings.START_SERVER__SOCKET__BUFFER__SIZE).withRequiredArg() .ofType(Integer.class); parser.accepts(CliStrings.START_SERVER__HOSTNAME__FOR__CLIENTS).withRequiredArg() .ofType(String.class); return parser; } /** * Parses the list of arguments to configure this Builder with the intent of constructing a * Server launcher to invoke a Cache Server. This method is called to parse the arguments * specified by the user on the command-line. * * @param args the array of arguments used to configure this Builder and create an instance of * ServerLauncher. */ void parseArguments(final String... args) { try { OptionSet options = getParser().parse(args); parseCommand(args); parseMemberName(args); setAssignBuckets(options.has("assign-buckets")); setDebug(options.has("debug")); setDeletePidFileOnStop(options.has("delete-pid-file-on-stop")); setDisableDefaultServer(options.has("disable-default-server")); setForce(options.has("force")); setHelp(options.has("help")); setRebalance(options.has("rebalance")); setRedirectOutput(options.has("redirect-output")); if (options.hasArgument(CliStrings.START_SERVER__CRITICAL__HEAP__PERCENTAGE)) { setCriticalHeapPercentage(Float.parseFloat(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__CRITICAL__HEAP__PERCENTAGE)))); } if (options.hasArgument(CliStrings.START_SERVER__EVICTION__HEAP__PERCENTAGE)) { setEvictionHeapPercentage(Float.parseFloat(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__EVICTION__HEAP__PERCENTAGE)))); } if (options.hasArgument(CliStrings.START_SERVER__CRITICAL_OFF_HEAP_PERCENTAGE)) { setCriticalOffHeapPercentage(Float.parseFloat(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__CRITICAL_OFF_HEAP_PERCENTAGE)))); } if (options.hasArgument(CliStrings.START_SERVER__EVICTION_OFF_HEAP_PERCENTAGE)) { setEvictionOffHeapPercentage(Float.parseFloat(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__EVICTION_OFF_HEAP_PERCENTAGE)))); } if (options.hasArgument(CliStrings.START_SERVER__MAX__CONNECTIONS)) { setMaxConnections(Integer.parseInt( ObjectUtils.toString(options.valueOf(CliStrings.START_SERVER__MAX__CONNECTIONS)))); } if (options.hasArgument(CliStrings.START_SERVER__MAX__MESSAGE__COUNT)) { setMaxMessageCount(Integer.parseInt( ObjectUtils.toString(options.valueOf(CliStrings.START_SERVER__MAX__MESSAGE__COUNT)))); } if (options.hasArgument(CliStrings.START_SERVER__MESSAGE__TIME__TO__LIVE)) { setMessageTimeToLive(Integer.parseInt(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__MESSAGE__TIME__TO__LIVE)))); } if (options.hasArgument(CliStrings.START_SERVER__SOCKET__BUFFER__SIZE)) { setSocketBufferSize(Integer.parseInt(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__SOCKET__BUFFER__SIZE)))); } if (options.hasArgument(CliStrings.START_SERVER__MAX__THREADS)) { setMaxThreads(Integer.parseInt( ObjectUtils.toString(options.valueOf(CliStrings.START_SERVER__MAX__THREADS)))); } if (!isHelping()) { if (options.has("dir")) { setWorkingDirectory(ObjectUtils.toString(options.valueOf("dir"))); } if (options.has("pid")) { setPid((Integer) options.valueOf("pid")); } if (options.has(SERVER_BIND_ADDRESS)) { setServerBindAddress(ObjectUtils.toString(options.valueOf(SERVER_BIND_ADDRESS))); } if (options.has("server-port")) { setServerPort((Integer) options.valueOf("server-port")); } if (options.has("spring-xml-location")) { setSpringXmlLocation(ObjectUtils.toString(options.valueOf("spring-xml-location"))); } if (options.has("version")) { setCommand(Command.VERSION); } } // why are these option not inside the 'if (!isHelping())' conditional block? if (options.hasArgument(CliStrings.START_SERVER__CRITICAL__HEAP__PERCENTAGE)) { setCriticalHeapPercentage(Float.parseFloat(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__CRITICAL__HEAP__PERCENTAGE)))); } if (options.hasArgument(CliStrings.START_SERVER__EVICTION__HEAP__PERCENTAGE)) { setEvictionHeapPercentage(Float.parseFloat(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__EVICTION__HEAP__PERCENTAGE)))); } if (options.hasArgument(CliStrings.START_SERVER__MAX__CONNECTIONS)) { setMaxConnections(Integer.parseInt( ObjectUtils.toString(options.valueOf(CliStrings.START_SERVER__MAX__CONNECTIONS)))); } if (options.hasArgument(CliStrings.START_SERVER__MAX__MESSAGE__COUNT)) { setMaxMessageCount(Integer.parseInt( ObjectUtils.toString(options.valueOf(CliStrings.START_SERVER__MAX__MESSAGE__COUNT)))); } if (options.hasArgument(CliStrings.START_SERVER__MAX__THREADS)) { setMaxThreads(Integer.parseInt( ObjectUtils.toString(options.valueOf(CliStrings.START_SERVER__MAX__THREADS)))); } if (options.hasArgument(CliStrings.START_SERVER__MESSAGE__TIME__TO__LIVE)) { setMessageTimeToLive(Integer.parseInt(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__MESSAGE__TIME__TO__LIVE)))); } if (options.hasArgument(CliStrings.START_SERVER__SOCKET__BUFFER__SIZE)) { setSocketBufferSize(Integer.parseInt(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__SOCKET__BUFFER__SIZE)))); } if (options.hasArgument(CliStrings.START_SERVER__HOSTNAME__FOR__CLIENTS)) { setHostNameForClients(ObjectUtils .toString(options.valueOf(CliStrings.START_SERVER__HOSTNAME__FOR__CLIENTS))); } } catch (OptionException e) { throw new IllegalArgumentException( String.format("An error occurred while parsing command-line arguments for the %s: %s", "Server", e.getMessage()), e); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } /** * Iterates the list of arguments in search of the target Server launcher command. * * @param args an array of arguments from which to search for the Server launcher command. * @see ServerLauncher.Command#valueOfName(String) * @see #parseArguments(String...) */ protected void parseCommand(final String... args) { if (args != null) { for (String arg : args) { Command command = Command.valueOfName(arg); if (command != null) { setCommand(command); break; } } } } /** * Iterates the list of arguments in search of the Server's Geode member name. If the argument * does not start with '-' or is not the name of a Server launcher command, then the value is * presumed to be the member name for the Server in Geode. * * @param args the array of arguments from which to search for the Server's member name in * Geode. * @see ServerLauncher.Command#isCommand(String) * @see #parseArguments(String...) */ protected void parseMemberName(final String... args) { if (args != null) { for (String arg : args) { if (!(arg.startsWith(OPTION_PREFIX) || Command.isCommand(arg))) { setMemberName(arg); break; } } } } /** * Gets the CacheConfig object used to configure PDX on the Geode Cache by the Builder. * * @return the CacheConfig object used to configure PDX on the Geode Cache by the Builder. */ CacheConfig getCacheConfig() { return cacheConfig; } /** * Gets the Server launcher command used during the invocation of the ServerLauncher. * * @return the Server launcher command used to invoke (run) the ServerLauncher class. * @see #setCommand(ServerLauncher.Command) * @see ServerLauncher.Command */ public Command getCommand() { return command != null ? command : DEFAULT_COMMAND; } /** * Sets the Sever launcher command used during the invocation of the ServerLauncher * * @param command the targeted Server launcher command used during the invocation (run) of * ServerLauncher. * @return this Builder instance. * @see #getCommand() * @see ServerLauncher.Command */ public Builder setCommand(final Command command) { this.command = command; return this; } /** * Determines whether buckets should be assigned to partitioned regions in the cache upon Server * start. * * @return a boolean indicating if buckets should be assigned upon Server start. * @see #setAssignBuckets(Boolean) */ public Boolean getAssignBuckets() { return assignBuckets; } /** * Sets whether buckets should be assigned to partitioned regions in the cache upon Server * start. * * @param assignBuckets a boolean indicating if buckets should be assigned upon Server start. * @return this Builder instance. * @see #getAssignBuckets() */ public Builder setAssignBuckets(final Boolean assignBuckets) { this.assignBuckets = assignBuckets; return this; } @VisibleForTesting Cache getCache() { return cache; } @VisibleForTesting Builder setCache(final Cache cache) { this.cache = cache; return this; } /** * Determines whether the new instance of the ServerLauncher will be set to debug mode. * * @return a boolean value indicating whether debug mode is enabled or disabled. * @see #setDebug(Boolean) */ public Boolean getDebug() { return debug; } /** * Sets whether the new instance of the ServerLauncher will be set to debug mode. * * @param debug a boolean value indicating whether debug mode is to be enabled or disabled. * @return this Builder instance. * @see #getDebug() */ public Builder setDebug(final Boolean debug) { this.debug = debug; return this; } /** * Determines whether the Geode Server should delete the pid file when its service stops or when * the JVM exits. * * @return a boolean value indicating if the pid file should be deleted when this service stops * or when the JVM exits. * @see #setDeletePidFileOnStop(Boolean) */ public Boolean getDeletePidFileOnStop() { return deletePidFileOnStop; } /** * Sets whether the Geode Server should delete the pid file when its service stops or when the * JVM exits. * * @param deletePidFileOnStop a boolean value indicating if the pid file should be deleted when * this service stops or when the JVM exits. * @return this Builder instance. * @see #getDeletePidFileOnStop() */ public Builder setDeletePidFileOnStop(final Boolean deletePidFileOnStop) { this.deletePidFileOnStop = deletePidFileOnStop; return this; } /** * Determines whether a default cache server will be added when the Geode Server comes online. * * @return a boolean value indicating whether to add a default cache server. * @see #setDisableDefaultServer(Boolean) */ public Boolean getDisableDefaultServer() { return disableDefaultServer; } /** * Sets a boolean value indicating whether to add a default cache when the Geode Server comes * online. * * @param disableDefaultServer a boolean value indicating whether to add a default cache server. * @return this Builder instance. * @see #getDisableDefaultServer() */ public Builder setDisableDefaultServer(final Boolean disableDefaultServer) { this.disableDefaultServer = disableDefaultServer; return this; } /** * Gets the Geode Distributed System (cluster) Properties configuration. * * @return a Properties object containing configuration settings for the Geode Distributed * System (cluster). * @see Properties */ public Properties getDistributedSystemProperties() { return distributedSystemProperties; } /** * Gets the boolean value used by the Server to determine if it should overwrite the PID file if * it already exists. * * @return the boolean value specifying whether or not to overwrite the PID file if it already * exists. * @see #setForce(Boolean) */ public Boolean getForce() { return force != null ? force : DEFAULT_FORCE; } /** * Sets the boolean value used by the Server to determine if it should overwrite the PID file if * it already exists. * * @param force a boolean value indicating whether to overwrite the PID file when it already * exists. * @return this Builder instance. * @see #getForce() */ public Builder setForce(final Boolean force) { this.force = force; return this; } /** * Determines whether the new instance of the ServerLauncher will be used to output help * information for either a specific command, or for using ServerLauncher in general. * * @return a boolean value indicating whether help will be output during the invocation of the * ServerLauncher. * @see #setHelp(Boolean) */ public Boolean getHelp() { return help; } /** * Determines whether help has been enabled. * * @return a boolean indicating if help was enabled. */ protected boolean isHelping() { return Boolean.TRUE.equals(getHelp()); } /** * Sets whether the new instance of ServerLauncher will be used to output help information for * either a specific command, or for using ServerLauncher in general. * * @param help a boolean indicating whether help information is to be displayed during * invocation of ServerLauncher. * @return this Builder instance. * @see #getHelp() */ public Builder setHelp(final Boolean help) { this.help = help; return this; } /** * Determines whether a rebalance operation on the cache will occur upon starting the Geode * server. * * @return a boolean indicating if the cache will be rebalance when the Geode server starts. * @see #setRebalance(Boolean) */ public Boolean getRebalance() { return rebalance; } /** * Set a boolean value indicating whether a rebalance operation on the cache should occur upon * starting the Geode server. * * @param rebalance a boolean indicating if the cache will be rebalanced when the Geode server * starts. * @return this Builder instance. * @see #getRebalance() */ public Builder setRebalance(final Boolean rebalance) { this.rebalance = rebalance; return this; } /** * Gets the member name of this Server in Geode. * * @return a String indicating the member name of this Server in Geode. * @see #setMemberName(String) */ public String getMemberName() { return memberName; } /** * Sets the member name of the Server in Geode. * * @param memberName a String indicating the member name of this Server in Geode. * @return this Builder instance. * @throws IllegalArgumentException if the member name is invalid. * @see #getMemberName() */ public Builder setMemberName(final String memberName) { if (isBlank(memberName)) { throw new IllegalArgumentException("The Server member name must be specified."); } this.memberName = memberName; return this; } /** * Gets the process ID (PID) of the running Server indicated by the user as an argument to the * ServerLauncher. This PID is used by the Server launcher to determine the Server's status, or * invoke shutdown on the Server. * * @return a user specified Integer value indicating the process ID of the running Server. * @see #setPid(Integer) */ public Integer getPid() { return pid; } /** * Sets the process ID (PID) of the running Server indicated by the user as an argument to the * ServerLauncher. This PID will be used by the Server launcher to determine the Server's * status, or invoke shutdown on the Server. * * @param pid a user specified Integer value indicating the process ID of the running Server. * @return this Builder instance. * @throws IllegalArgumentException if the process ID (PID) is not valid (greater than zero if * not null). * @see #getPid() */ public Builder setPid(final Integer pid) { if (pid != null && pid < 0) { throw new IllegalArgumentException( "A process ID (PID) must be a non-negative integer value."); } this.pid = pid; return this; } /** * Determines whether the new instance of ServerLauncher will redirect output to system logs * when starting a Server. * * @return a boolean value indicating if output will be redirected to system logs when starting * a Server * @see #setRedirectOutput(Boolean) */ public Boolean getRedirectOutput() { return redirectOutput; } /** * Determines whether redirecting of output has been enabled. * * @return a boolean indicating if redirecting of output was enabled. */ private boolean isRedirectingOutput() { return Boolean.TRUE.equals(getRedirectOutput()); } /** * Sets whether the new instance of ServerLauncher will redirect output to system logs when * starting a Server. * * @param redirectOutput a boolean value indicating if output will be redirected to system logs * when starting a Server. * @return this Builder instance. * @see #getRedirectOutput() */ public Builder setRedirectOutput(final Boolean redirectOutput) { this.redirectOutput = redirectOutput; return this; } /** * Gets the IP address to which the Server will be bound listening for and accepting cache * client connections in a client/server topology. * * @return an InetAddress indicating the IP address that the Server is bound to listening for * and accepting cache client connections in a client/server topology. * @see #setServerBindAddress(String) */ public InetAddress getServerBindAddress() { return serverBindAddress; } boolean isServerBindAddressSetByUser() { return serverBindAddressSetByUser; } /** * Sets the IP address to which the Server will be bound listening for and accepting cache * client connections in a client/server topology. * * @param serverBindAddress a String specifying the IP address or hostname that the Server will * be bound to listen for and accept cache client connections in a client/server * topology. * @return this Builder instance. * @throws IllegalArgumentException wrapping the UnknownHostException if the IP address or * hostname for the server bind address is unknown. * @see #getServerBindAddress() */ public Builder setServerBindAddress(final String serverBindAddress) { if (isBlank(serverBindAddress)) { this.serverBindAddress = null; return this; } // NOTE only set the 'bind address' if the user specified a value try { InetAddress bindAddress = InetAddress.getByName(serverBindAddress); if (LocalHostUtil.isLocalHost(bindAddress)) { this.serverBindAddress = bindAddress; serverBindAddressSetByUser = true; return this; } throw new IllegalArgumentException( serverBindAddress + " is not an address for this machine."); } catch (UnknownHostException e) { throw new IllegalArgumentException( String.format("The hostname/IP address to which the %s will be bound is unknown.", "Server"), e); } } /** * Gets the port on which the Server will listen for and accept cache client connections in a * client/server topology. * * @return an Integer value specifying the port the Server will listen on and accept cache * client connections in a client/server topology. * @see #setServerPort(Integer) */ public Integer getServerPort() { return serverPort != null ? serverPort : getDefaultServerPort(); } boolean isServerPortSetByUser() { return serverPortSetByUser; } /** * Sets the port on which the Server will listen for and accept cache client connections in a * client/server topology. * * @param serverPort an Integer value specifying the port the Server will listen on and accept * cache client connections in a client/server topology. * @return this Builder instance. * @throws IllegalArgumentException if the port number is not valid. * @see #getServerPort() */ public Builder setServerPort(final Integer serverPort) { if (serverPort == null) { this.serverPort = null; serverPortSetByUser = false; return this; } if (serverPort < 0 || serverPort > 65535) { throw new IllegalArgumentException( "The port on which the Server will listen must be between 1 and 65535 inclusive."); } if (serverPort == 0) { this.serverPort = 0; serverPortSetByUser = false; } else { this.serverPort = serverPort; serverPortSetByUser = true; } return this; } /** * Gets the location of the Spring XML configuration meta-data file used to bootstrap, configure * and initialize the Geode Server on start. * <p> * * @return a String indicating the location of the Spring XML configuration file. * @see #setSpringXmlLocation(String) */ public String getSpringXmlLocation() { return springXmlLocation; } /** * Sets the location of the Spring XML configuration meta-data file used to bootstrap, configure * and initialize the Geode Server on start. * <p> * * @param springXmlLocation a String indicating the location of the Spring XML configuration * file. * @return this Builder instance. * @see #getSpringXmlLocation() */ public Builder setSpringXmlLocation(final String springXmlLocation) { this.springXmlLocation = springXmlLocation; return this; } /** * Gets the working directory pathname in which the Server will be ran. If the directory is * unspecified, then working directory defaults to the current directory. * * @return a String indicating the working directory pathname. * @see #setWorkingDirectory(String) */ public String getWorkingDirectory() { return tryGetCanonicalPathElseGetAbsolutePath( new File(defaultIfBlank(workingDirectory, DEFAULT_WORKING_DIRECTORY))); } /** * Sets the working directory in which the Server will be ran. This also the directory in which * all Server files (such as log and license files) will be written. If the directory is * unspecified, then the working directory defaults to the current directory. * * @param workingDirectory a String indicating the pathname of the directory in which the Server * will be ran. * @return this Builder instance. * @throws IllegalArgumentException wrapping a FileNotFoundException if the working directory * pathname cannot be found. * @see #getWorkingDirectory() * @see FileNotFoundException */ public Builder setWorkingDirectory(final String workingDirectory) { if (!new File(defaultIfBlank(workingDirectory, DEFAULT_WORKING_DIRECTORY)).isDirectory()) { throw new IllegalArgumentException( String.format(AbstractLauncher.WORKING_DIRECTORY_NOT_FOUND_ERROR_MESSAGE, "Server"), new FileNotFoundException(workingDirectory)); } this.workingDirectory = workingDirectory; return this; } public Float getCriticalHeapPercentage() { return criticalHeapPercentage; } public Builder setCriticalHeapPercentage(final Float criticalHeapPercentage) { if (criticalHeapPercentage != null) { if (criticalHeapPercentage < 0 || criticalHeapPercentage > 100.0f) { throw new IllegalArgumentException( String.format("Critical heap percentage (%1$s) must be between 0 and 100!", criticalHeapPercentage)); } } this.criticalHeapPercentage = criticalHeapPercentage; return this; } public Float getCriticalOffHeapPercentage() { return criticalOffHeapPercentage; } public Builder setCriticalOffHeapPercentage(final Float criticalOffHeapPercentage) { if (criticalOffHeapPercentage != null) { if (criticalOffHeapPercentage < 0 || criticalOffHeapPercentage > 100.0f) { throw new IllegalArgumentException( String.format("Critical off-heap percentage (%1$s) must be between 0 and 100!", criticalOffHeapPercentage)); } } this.criticalOffHeapPercentage = criticalOffHeapPercentage; return this; } public Float getEvictionHeapPercentage() { return evictionHeapPercentage; } public Builder setEvictionHeapPercentage(final Float evictionHeapPercentage) { if (evictionHeapPercentage != null) { if (evictionHeapPercentage < 0 || evictionHeapPercentage > 100.0f) { throw new IllegalArgumentException( String.format("Eviction heap percentage (%1$s) must be between 0 and 100!", evictionHeapPercentage)); } } this.evictionHeapPercentage = evictionHeapPercentage; return this; } public Float getEvictionOffHeapPercentage() { return evictionOffHeapPercentage; } public Builder setEvictionOffHeapPercentage(final Float evictionOffHeapPercentage) { if (evictionOffHeapPercentage != null) { if (evictionOffHeapPercentage < 0 || evictionOffHeapPercentage > 100.0f) { throw new IllegalArgumentException( String.format("Eviction off-heap percentage (%1$s) must be between 0 and 100", evictionOffHeapPercentage)); } } this.evictionOffHeapPercentage = evictionOffHeapPercentage; return this; } public String getHostNameForClients() { return hostNameForClients; } public Builder setHostNameForClients(String hostNameForClients) { if (isBlank(hostNameForClients)) { throw new IllegalArgumentException( "The hostname used by clients to connect to the Server must have an argument if the " + "--hostname-for-clients command-line option is specified!"); } this.hostNameForClients = hostNameForClients; return this; } public Integer getMaxConnections() { return maxConnections; } public Builder setMaxConnections(Integer maxConnections) { if (maxConnections != null && maxConnections < 1) { throw new IllegalArgumentException( String.format("Max Connections (%1$s) must be greater than 0!", maxConnections)); } this.maxConnections = maxConnections; return this; } public Integer getMaxMessageCount() { return maxMessageCount; } public Builder setMaxMessageCount(Integer maxMessageCount) { if (maxMessageCount != null && maxMessageCount < 1) { throw new IllegalArgumentException( String.format("Max Message Count (%1$s) must be greater than 0!", maxMessageCount)); } this.maxMessageCount = maxMessageCount; return this; } public Integer getMaxThreads() { return maxThreads; } public Builder setMaxThreads(Integer maxThreads) { if (maxThreads != null && maxThreads < 1) { throw new IllegalArgumentException( String.format("Max Threads (%1$s) must be greater than 0!", maxThreads)); } this.maxThreads = maxThreads; return this; } public Integer getMessageTimeToLive() { return messageTimeToLive; } public Builder setMessageTimeToLive(Integer messageTimeToLive) { if (messageTimeToLive != null && messageTimeToLive < 1) { throw new IllegalArgumentException(String .format("Message Time To Live (%1$s) must be greater than 0!", messageTimeToLive)); } this.messageTimeToLive = messageTimeToLive; return this; } public Integer getSocketBufferSize() { return socketBufferSize; } public Builder setSocketBufferSize(Integer socketBufferSize) { if (socketBufferSize != null && socketBufferSize < 1) { throw new IllegalArgumentException(String.format( "The Server's Socket Buffer Size (%1$s) must be greater than 0!", socketBufferSize)); } this.socketBufferSize = socketBufferSize; return this; } /** * Sets a Geode Distributed System Property. * * @param propertyName a String indicating the name of the Geode Distributed System property * as described in {@link ConfigurationProperties} * @param propertyValue a String value for the Geode Distributed System property. * @return this Builder instance. */ public Builder set(final String propertyName, final String propertyValue) { distributedSystemProperties.setProperty(propertyName, propertyValue); return this; } /** * add the properties in the Gemfire Distributed System Property * * @param properties a property object that holds one or more Gemfire Distributed System * properties as described in {@link ConfigurationProperties} * @return this Builder instance * @since Geode 1.12 */ public Builder set(final Properties properties) { distributedSystemProperties.putAll(properties); return this; } /** * Sets whether the PDX type meta-data should be persisted to disk. * * @param persistent a boolean indicating whether PDX type meta-data should be persisted to * disk. * @return this Builder instance. */ public Builder setPdxPersistent(final boolean persistent) { cacheConfig.setPdxPersistent(persistent); return this; } /** * Sets the Geode Disk Store to be used to persist PDX type meta-data. * * @param pdxDiskStore a String indicating the name of the Geode Disk Store to use to store * PDX type meta-data * @return this Builder instance. */ public Builder setPdxDiskStore(final String pdxDiskStore) { cacheConfig.setPdxDiskStore(pdxDiskStore); return this; } /** * Sets whether fields in the PDX instance should be ignored when unread. * * @param ignore a boolean indicating whether unread fields in the PDX instance should be * ignored. * @return this Builder instance. */ public Builder setPdxIgnoreUnreadFields(final boolean ignore) { cacheConfig.setPdxIgnoreUnreadFields(ignore); return this; } /** * Sets whether PDX instances should be returned as is when Region.get(key:String):Object is * called. * * @param readSerialized a boolean indicating whether the PDX instance should be returned from a * call to Region.get(key:String):Object * @return this Builder instance. */ public Builder setPdxReadSerialized(final boolean readSerialized) { cacheConfig.setPdxReadSerialized(readSerialized); return this; } /** * Set the PdxSerializer to use to serialize POJOs to the Geode Cache Region or when sent * between peers, client/server, or during persistence to disk. * * @param pdxSerializer the PdxSerializer that is used to serialize application domain objects * into PDX. * @return this Builder instance. */ public Builder setPdxSerializer(final PdxSerializer pdxSerializer) { cacheConfig.setPdxSerializer(pdxSerializer); return this; } /** * Validates the configuration settings and properties of this Builder, ensuring that all * invariants have been met. Currently, the only invariant constraining the Builder is that the * user must specify the member name for the Server in the Geode distributed system as a * command-line argument, or by setting the memberName property programmatically using the * corresponding setter method. * * @throws IllegalStateException if the Builder is not properly configured. */ protected void validate() { if (!isHelping()) { validateOnStart(); validateOnStatus(); validateOnStop(); } } /** * Validates the arguments passed to the Builder when the 'start' command has been issued. * * @see ServerLauncher.Command#START */ void validateOnStart() { if (Command.START == getCommand()) { if (isBlank(getMemberName()) && !isSet(System.getProperties(), GeodeGlossary.GEMFIRE_PREFIX + NAME) && !isSet(getDistributedSystemProperties(), NAME) && !isSet(loadGemFireProperties(DistributedSystem.getPropertyFileURL()), NAME)) { throw new IllegalStateException( String.format( MEMBER_NAME_ERROR_MESSAGE, "Server", "Server")); } if (!CURRENT_DIRECTORY.equalsIgnoreCase(getWorkingDirectory())) { throw new IllegalStateException( String.format( AbstractLauncher.WORKING_DIRECTORY_OPTION_NOT_VALID_ERROR_MESSAGE, "Server", "Server")); } } } /** * Validates the arguments passed to the Builder when the 'status' command has been issued. * * @see ServerLauncher.Command#STATUS */ void validateOnStatus() { if (Command.STATUS == getCommand()) { // do nothing } } /** * Validates the arguments passed to the Builder when the 'stop' command has been issued. * * @see ServerLauncher.Command#STOP */ void validateOnStop() { if (Command.STOP == getCommand()) { // do nothing } } /** * Validates the Builder configuration settings and then constructs an instance of the * ServerLauncher class to invoke operations on a Geode Server. * * @return a newly constructed instance of the ServerLauncher configured with this Builder. * @see #validate() * @see ServerLauncher */ public ServerLauncher build() { validate(); return new ServerLauncher(this); } /** * Sets the action to run when the server is online. * * @param startupCompletionAction the action to run * @return this builder */ Builder setStartupCompletionAction(Runnable startupCompletionAction) { this.startupCompletionAction = startupCompletionAction; return this; } /** * Gets the action to run when the server is online. * * @return the action to run */ Runnable getStartupCompletionAction() { return startupCompletionAction; } /** * Sets the action to run when server startup completes with errors. * * @param startupExceptionAction the action to run * @return this builder */ Builder setStartupExceptionAction(Consumer<Throwable> startupExceptionAction) { this.startupExceptionAction = startupExceptionAction; return this; } /** * Gets the action to run when server startup completed with errors. * * @return the action to run */ Consumer<Throwable> getStartupExceptionAction() { return startupExceptionAction; } /** * Sets the ServerLauncherCacheProvider to use when creating the cache. * * @param serverLauncherCacheProvider the cache provider to use * @return this builder */ Builder setServerLauncherCacheProvider( ServerLauncherCacheProvider serverLauncherCacheProvider) { this.serverLauncherCacheProvider = serverLauncherCacheProvider; return this; } /** * Gets the ServerLauncherCacheProvider to use when creating the cache. * * @return the cache provider */ ServerLauncherCacheProvider getServerLauncherCacheProvider() { return serverLauncherCacheProvider; } /** * Sets the factory to use to get a {@code ControllableProcess} when starting the server. * * @param controllableProcessFactory the controllable process factory to use * @return this builder */ Builder setControllableProcessFactory( Supplier<ControllableProcess> controllableProcessFactory) { this.controllableProcessFactory = controllableProcessFactory; return this; } /** * Gets the factory used to get a {@code ControllableProcess} when starting the server. * * @return the controllable process factory */ Supplier<ControllableProcess> getControllableProcessFactory() { return controllableProcessFactory; } } /** * An enumerated type representing valid commands to the Server launcher. */ public enum Command { START("start", "assign-buckets", "disable-default-server", "rebalance", SERVER_BIND_ADDRESS, "server-port", "force", "debug", "help"), STATUS("status", "member", "pid", "dir", "debug", "help"), STOP("stop", "member", "pid", "dir", "debug", "help"), UNSPECIFIED("unspecified"), VERSION("version"); private final List<String> options; private final String name; Command(final String name, final String... options) { assert isNotBlank(name) : "The name of the command must be specified!"; this.name = name; this.options = options != null ? Collections.unmodifiableList(Arrays.asList(options)) : Collections.emptyList(); } /** * Determines whether the specified name refers to a valid Server launcher command, as defined * by this enumerated type. * * @param name a String value indicating the potential name of a Server launcher command. * @return a boolean indicating whether the specified name for a Server launcher command is * valid. */ public static boolean isCommand(final String name) { return valueOfName(name) != null; } /** * Determines whether the given Server launcher command has been properly specified. The command * is deemed unspecified if the reference is null or the Command is UNSPECIFIED. * * @param command the Server launcher command. * @return a boolean value indicating whether the Server launcher command is unspecified. * @see Command#UNSPECIFIED */ public static boolean isUnspecified(final Command command) { return command == null || command.isUnspecified(); } /** * Looks up a Server launcher command by name. The equality comparison on name is * case-insensitive. * * @param name a String value indicating the name of the Server launcher command. * @return an enumerated type representing the command name or null if the no such command with * the specified name exists. */ public static Command valueOfName(final String name) { for (final Command command : values()) { if (command.getName().equalsIgnoreCase(name)) { return command; } } return null; } /** * Gets the name of the Server launcher command. * * @return a String value indicating the name of the Server launcher command. */ public String getName() { return name; } /** * Gets a set of valid options that can be used with the Server launcher command when used from * the command-line. * * @return a Set of Strings indicating the names of the options available to the Server launcher * command. */ public List<String> getOptions() { return options; } /** * Determines whether this Server launcher command has the specified command-line option. * * @param option a String indicating the name of the command-line option to this command. * @return a boolean value indicating whether this command has the specified named command-line * option. */ public boolean hasOption(final String option) { return getOptions().contains(lowerCase(option)); } /** * Convenience method for determining whether this is the UNSPECIFIED Server launcher command. * * @return a boolean indicating if this command is UNSPECIFIED. * @see #UNSPECIFIED */ public boolean isUnspecified() { return this == UNSPECIFIED; } /** * Gets the String representation of this Server launcher command. * * @return a String value representing this Server launcher command. */ @Override public String toString() { return getName(); } } /** * The ServerState is an immutable type representing the state of the specified Server at any * given moment in time. The state of the Server is assessed at the exact moment an instance of * this class is constructed. * * @see AbstractLauncher.ServiceState */ public static class ServerState extends ServiceState<String> { /** * Unmarshals a ServerState instance from the JSON String. * * @return a ServerState value unmarshalled from the JSON String. */ public static ServerState fromJson(final String json) { try { final JsonNode jsonObject = new ObjectMapper().readTree(json); final Status status = Status.valueOfDescription(jsonObject.get(JSON_STATUS).asText()); final List<String> jvmArguments = JsonUtil.toStringList(jsonObject.get(JSON_JVMARGUMENTS)); return new ServerState(status, jsonObject.get(JSON_STATUSMESSAGE).asText(), jsonObject.get(JSON_TIMESTAMP).asLong(), jsonObject.get(JSON_LOCATION).asText(), jsonObject.get(JSON_PID).asInt(), jsonObject.get(JSON_UPTIME).asLong(), jsonObject.get(JSON_WORKINGDIRECTORY).asText(), jvmArguments, jsonObject.get(JSON_CLASSPATH).asText(), jsonObject.get(JSON_GEMFIREVERSION).asText(), jsonObject.get(JSON_JAVAVERSION).asText(), jsonObject.get(JSON_LOGFILE).asText(), jsonObject.get(JSON_HOST).asText(), jsonObject.get(JSON_PORT).asText(), jsonObject.get(JSON_MEMBERNAME).asText()); } catch (Exception e) { throw new IllegalArgumentException("Unable to create ServerStatus from JSON: " + json, e); } } public static ServerState fromDirectory(final String workingDirectory, final String memberName) { ServerState serverState = new ServerLauncher.Builder().setWorkingDirectory(workingDirectory) .setDisableDefaultServer(true).build().status(); if (ObjectUtils.equals(serverState.getMemberName(), memberName)) { return serverState; } return new ServerState(new ServerLauncher.Builder().build(), Status.NOT_RESPONDING); } public ServerState(final ServerLauncher launcher, final Status status) { this(status, launcher.statusMessage, System.currentTimeMillis(), launcher.getId(), identifyPid(), ManagementFactory.getRuntimeMXBean().getUptime(), launcher.getWorkingDirectory(), ManagementFactory.getRuntimeMXBean().getInputArguments(), System.getProperty("java.class.path"), GemFireVersion.getGemFireVersion(), System.getProperty("java.version"), getServerLogFileCanonicalPath(launcher), getServerBindAddressAsString(launcher), getServerPortAsString(launcher), launcher.getMemberName()); } public ServerState(final ServerLauncher launcher, final Status status, final String errorMessage) { this(status, errorMessage, System.currentTimeMillis(), getServerLocation(launcher), null, 0L, launcher.getWorkingDirectory(), ManagementFactory.getRuntimeMXBean().getInputArguments(), null, GemFireVersion.getGemFireVersion(), System.getProperty("java.version"), null, getServerBindAddressAsString(launcher), launcher.getServerPortAsString(), null); } /* * Guards against throwing NPEs due to incorrect or missing host information while constructing * error states */ private static String getServerLocation(ServerLauncher launcher) { if (launcher.getServerPort() == null) { return launcher.getId(); } if (launcher.getServerBindAddress() == null) { return HostUtils.getLocatorId(HostUtils.getLocalHost(), launcher.getServerPort()); } return HostUtils.getServerId(launcher.getServerBindAddress().getCanonicalHostName(), launcher.getServerPort()); } protected ServerState(final Status status, final String statusMessage, final long timestamp, final String serverLocation, final Integer pid, final Long uptime, final String workingDirectory, final List<String> jvmArguments, final String classpath, final String gemfireVersion, final String javaVersion, final String logFile, final String host, final String port, final String memberName) { super(status, statusMessage, timestamp, serverLocation, pid, uptime, workingDirectory, jvmArguments, classpath, gemfireVersion, javaVersion, logFile, host, port, memberName); } private static String getServerLogFileCanonicalPath(final ServerLauncher launcher) { final InternalDistributedSystem system = InternalDistributedSystem.getAnyInstance(); if (system != null) { final File logFile = system.getConfig().getLogFile(); if (logFile != null && logFile.isFile()) { final String logFileCanonicalPath = tryGetCanonicalPathElseGetAbsolutePath(logFile); if (isNotBlank(logFileCanonicalPath)) { return logFileCanonicalPath; } } } return launcher.getLogFileCanonicalPath(); } private static String getServerBindAddressAsString(final ServerLauncher launcher) { final InternalCache internalCache = GemFireCacheImpl.getInstance(); if (internalCache != null) { final List<CacheServer> csList = internalCache.getCacheServers(); if (csList != null && !csList.isEmpty()) { final CacheServer cs = csList.get(0); final String serverBindAddressAsString = cs.getBindAddress(); if (isNotBlank(serverBindAddressAsString)) { return serverBindAddressAsString; } } } return launcher.getServerBindAddressAsString(); } private static String getServerPortAsString(final ServerLauncher launcher) { final InternalCache internalCache = GemFireCacheImpl.getInstance(); if (internalCache != null) { final List<CacheServer> csList = internalCache.getCacheServers(); if (csList != null && !csList.isEmpty()) { final CacheServer cs = csList.get(0); final String portAsString = String.valueOf(cs.getPort()); if (isNotBlank(portAsString)) { return portAsString; } } } return launcher.isDisableDefaultServer() ? EMPTY : launcher.getServerPortAsString(); } @Override protected String getServiceName() { return SERVER_SERVICE_NAME; } } }
smgoller/geode
geode-core/src/main/java/org/apache/geode/distributed/ServerLauncher.java
Java
apache-2.0
106,858
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.cp.internal.session; import com.hazelcast.cp.CPGroupId; /** * Used by services to validate and trigger session activity */ public interface SessionAccessor { /** * Checks if there is an active session with the given id in the Raft group * * @return true if the session is found, false otherwise */ boolean isActive(CPGroupId groupId, long sessionId); /** * Performs a heartbeat for the given session id in the Raft group. * * @throws IllegalStateException if there is no {@link RaftSessionRegistry} * initialized for the Raft group * @throws SessionExpiredException if there is no active session * with the given id in the Raft group */ void heartbeat(CPGroupId groupId, long sessionId); }
mesutcelik/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/session/SessionAccessor.java
Java
apache-2.0
1,432
/// Package log provides a useful logging subsystem for Hologram tools. // // By default, it will log INFO-level messages to the system log and standard out, // but DEBUG-level messages can be output to these sinks as well. By defaut DEBUG // messages are suppressed. // // Messages emitted to the terminal are colourised for easy visual parsing, if the // terminal supports it. The following colours are used: // * Info: White // * Warning: Yellow // * Error: Red // * Debug: Cyan // // The log format is as follows: // // [WARNING] 06/11/2014 18:22:34Z Message text. // [ERROR ] 06/11/2014 18:22:56Z Time to fail. // // Copyright 2014 AdRoll, 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 log import ( "fmt" "runtime" ) var ( internalLog *logMux debugMode bool ) /* Initialize some package-level setup so you can import and go. */ func init() { internalLog = NewMux() internalLog.Add(NewSyslogSink()) internalLog.Add(NewColourisedTerminalSink()) } /* Sink implementers provide processing logic for messages emitted by Hologram programs. */ type Sink interface { Info(message string) Warning(message string) Error(message string) Debug(message string) } /* These functions delegate to the package-level logged automatically created so that we have a very simple API to get started with. */ func Info(message string, v ...interface{}) { // Prepend the log message with information about the calling function. var fileMessage string if debugMode { _, f, l, _ := runtime.Caller(1) fileMessage = fmt.Sprintf("(%s:%d) %s", f, l, message) } else { fileMessage = message } internalLog.Info(fileMessage, v...) } func Warning(message string, v ...interface{}) { // Prepend the log message with information about the calling function. var fileMessage string if debugMode { _, f, l, _ := runtime.Caller(1) fileMessage = fmt.Sprintf("(%s:%d) %s", f, l, message) } else { fileMessage = message } internalLog.Warning(fileMessage, v...) } func Errorf(message string, v ...interface{}) { // Prepend the log message with information about the calling function. var fileMessage string if debugMode { _, f, l, _ := runtime.Caller(1) fileMessage = fmt.Sprintf("(%s:%d) %s", f, l, message) } else { fileMessage = message } internalLog.Error(fileMessage, v...) } func Debug(message string, v ...interface{}) { // Prepend the log message with information about the calling function. var fileMessage string if debugMode { _, f, l, _ := runtime.Caller(1) fileMessage = fmt.Sprintf("(%s:%d) %s", f, l, message) } else { fileMessage = message } internalLog.Debug(fileMessage, v...) } /* DebugMode sets the debug mode option for this built-in logger. */ func DebugMode(status bool) { internalLog.DebugMode(status) debugMode = status }
copumpkin/hologram
log/log.go
GO
apache-2.0
3,311
/* <![CDATA[ */ (function($){ "use strict"; $(document).ready(function(){ /* FitVid ================================================== */ $(".ut-video").fitVids(); /* Animated Skillbar ================================================== */ $(".ut-skill-active").each(function(i, el){ var el = $(el), bar_width = el.data('width'); if ( el.visible(true) && !el.hasClass('ut-already-visible') ) { el.stop(true, true).animate({width : bar_width+"%"} , 1000 ); el.addClass('ut-already-visible'); } }); /* Milestone Counter - animate when visible on load ================================================== */ $('.ut-counter').each(function(i, el){ var counter = $(el).data('counter'); if ( $(el).visible(true) && !$(el).hasClass('ut-already-counted') ) { setTimeout ( function () { $(el).addClass('ut-already-counted'); $(el).find('.ut-count').countTo({ from: 0, to: counter, speed: 2000, refreshInterval: 100 }); }, 1000 ); } }); var win = $(window), allMods = $(".ut-animate-image, .ut-counter, .ut-skill-active"); /* Image already visible when page is loaded ================================================== */ $(".ut-animate-image").each(function(i, el) { if ($(el).visible(true)) { var el = $(el), effecttype = el.data('effecttype'); if( effecttype === 'image' ) { var effect = el.data('effect'); if ( el.visible(true) ) { el.addClass( effect ); } else { el.removeClass( effect + " ut-already-visible"); } } } }); /* Run Site Effect Animation ================================================== */ win.scroll( function(event) { allMods.each(function(i, el) { var el = $(el), effecttype = el.data('effecttype'); if( effecttype === 'image' ) { var effect = el.data('effect'); if ( el.visible(true) && !el.hasClass( effect ) ) { el.addClass( effect ); } else if( !el.visible(true) ) { el.removeClass( effect ); } } if( effecttype === 'skillbar' ) { var bar_width = el.data('width'); if ( el.visible(true) && !el.hasClass('ut-already-visible') ) { el.addClass("ut-already-visible"); el.stop(true, true).animate({width : bar_width+"%"} , 1000 ); } else if( !el.visible(true) ) { el.removeClass("ut-already-visible"); el.css("width" , 0); } } if( effecttype === 'counter') { var counter = el.data('counter'); if ( el.visible(true) && !$(el).hasClass('ut-already-counted') ) { el.addClass('ut-already-counted'); el.find('.ut-count').countTo({ from: 0, to: counter, speed: 2000, refreshInterval: 100 }); } } }); }); }); $.fn.countTo = function (options) { options = options || {}; return $(this).each(function () { // set options for current element var settings = $.extend({}, $.fn.countTo.defaults, { from: $(this).data('from'), to: $(this).data('to'), speed: $(this).data('speed'), refreshInterval: $(this).data('refresh-interval'), decimals: $(this).data('decimals') }, options); // how many times to update the value, and how much to increment the value on each update var loops = Math.ceil(settings.speed / settings.refreshInterval), increment = (settings.to - settings.from) / loops; // references & variables that will change with each update var self = this, $self = $(this), loopCount = 0, value = settings.from, data = $self.data('countTo') || {}; $self.data('countTo', data); // if an existing interval can be found, clear it first if (data.interval) { clearInterval(data.interval); } data.interval = setInterval(updateTimer, settings.refreshInterval); // initialize the element with the starting value render(value); function updateTimer() { value += increment; loopCount++; render(value); if (typeof(settings.onUpdate) == 'function') { settings.onUpdate.call(self, value); } if (loopCount >= loops) { // remove the interval $self.removeData('countTo'); clearInterval(data.interval); value = settings.to; if (typeof(settings.onComplete) == 'function') { settings.onComplete.call(self, value); } } } function render(value) { var formattedValue = settings.formatter.call(self, value, settings); $self.html(formattedValue); } }); }; $.fn.countTo.defaults = { from: 0, // the number the element should start at to: 0, // the number the element should end at speed: 1000, // how long it should take to count between the target numbers refreshInterval: 100, // how often the element should be updated decimals: 0, // the number of decimal places to show formatter: formatter, // handler for formatting the value before rendering onUpdate: null, // callback method for every time the element is updated onComplete: null // callback method for when the element finishes updating }; function formatter(value, settings) { return value.toFixed(settings.decimals); } })(jQuery); /* ]]> */
carlagiannina/cg
wp-content/plugins/ut-shortcodes/js/ut.scplugin.js
JavaScript
artistic-2.0
5,711
/* ¿´³ÌÐòд½á¹û */ class SwitchTest { public static void main(String[] args) { /* int x = 2; int y = 3; switch(x){ default: y++; break; case 3: y++; case 4: y++; } System.out.println("y="+y); */ int x = 2; int y = 3; switch(x){ default: y++; case 3: y++; case 4: y++; } System.out.println("y="+y); } }
DuGuQiuBai/Java
day03/code/06_选择结构(switch语句)/SwitchTest.java
Java
artistic-2.0
377
package Zeta::IPC::SHM; use strict; use warnings; use Errno; use IPC::SysV qw(S_IRUSR S_IWUSR IPC_CREAT IPC_EXCL); use Carp qw/confess/; use Data::Dump; ##################################################### # $class->($key,$size); ##################################################### sub new { my $class = shift; my ( $key, $size ) = @_; unless ( defined $key ) { confess "shmget key undefined"; } my $id = shmget( $key, $size, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL ); unless ( defined $id ) { if ( $!{EEXIST} ) { $id = shmget( $key, 0, S_IRUSR | S_IWUSR ); unless ( defined $id ) { confess "shmget error: [$!]"; } } else { confess "shmget error: [$!]"; } } unless ($id) { confess( "shmget error:[$!] with:\n" . Data::Dump->dump( \@_ ) ); } bless \$id, $class; } ##################################################### # $class->attach($key); ##################################################### sub attach { my $class = shift; my $key = shift; unless ( defined $key ) { confess "invalid key"; return; } my $id = shmget( $key, 0, S_IRUSR | S_IWUSR ); unless ($id) { confess "can not shmat($key)"; } bless \$id, $class; } ##################################################### # $shm->write($mref, $offset, $len); ##################################################### sub write { my $self = shift; my ( $mref, $offset, $len ) = @_; unless ( shmwrite( $$self, $$mref, $offset, $len ) ) { confess("shmwrite error:[$!]"); } return $self; } ##################################################### # $shm->read($mref, offset, $length); ##################################################### sub read { my $self = shift; my ( $mref, $offset, $len ) = @_; unless ( defined $mref && defined $offset && $len > 0 ) { confess "error offset needed:\n" . Data::Dump->dump( \@_ ); } unless ( shmread( $$self, $$mref, $offset, $len ) ) { confess("shmread error:[$!]"); } return $self; } 1; __END__ =head1 NAME Zeta::IPC::SHM - a simple wrapper for shmget shmwrite shmread =head1 SYNOPSIS #!/usr/bin/perl -w use strict; use Zeta::IPC::SHM; my $shm1 = Zeta::IPC::SHM->new(99990000,1024); my $shm2 = Zeta::IPC::SHM->attach(99990000); my $data; $shm1->write(\("this is a test"), 10, 20); # offset = 10, length = 20 $shm2->read(\$data, 10, 20); # offset = 10, length = 20 warn "read: [$data]\n"; exit 0; =head1 API new attach read write =head1 Author & Copyright zcman2005@gmail.com =cut
epiphyllum/zeta
lib/Zeta/IPC/SHM.pm
Perl
artistic-2.0
2,732
//---------------------------------------------- // Behaviour Machine // Copyright © 2014 Anderson Campos Cardoso //---------------------------------------------- using UnityEngine; using System.Collections; namespace BehaviourMachine { /// <summary> /// OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider. /// </summary> [NodeInfo( category = "Function/", icon = "Function", description = "OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider", url = "http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnCollisionStay.html")] public class OnCollisionStay : FunctionNode { /// <summary> /// Stores the other game object. /// </summary> [VariableInfo(requiredField = false, nullLabel = "Don't Store", canBeConstant = false, tooltip = "Stores the other game object")] public GameObjectVar other; public override void Reset () { base.Reset(); other = new ConcreteGameObjectVar(); } public override void OnEnable () { if (this.enabled) { this.blackboard.onCollisionStay += CollisionStay; m_Registered = true; } } public override void OnDisable () { this.blackboard.onCollisionStay -= CollisionStay; m_Registered = false; } /// <summary> /// Callback registered to get blackboard.onCollisionStay events. /// </summary> void CollisionStay (Collision collision) { other.Value = collision.gameObject; // Tick children this.OnTick(); } } }
maxrevilo/Mazzaroth
Assets/Plugins/BehaviourMachine/Source/Nodes/Functions/OnCollisionStay.cs
C#
artistic-2.0
1,820
--- id: 160-Zend_Form-Webinar-Wednesday author: matthew title: 'Zend_Form Webinar Wednesday' draft: false public: true created: '2008-03-03T17:00:26-05:00' updated: '2008-03-06T06:29:49-05:00' tags: - php - webinar - 'zend framework' --- Just an FYI for anyone interested: I'll be performing a webinar for this week's Zend Wednesday Webinar series on [Zend_Form](http://framework.zend.com/manual/en/zend.form.html). You can get details on the webinar and how to register for it at [the Zend_Form webinar information page](http://www.zend.com/en/company/news/event/webinar-zend-framework-forms). I'll be covering the design of `Zend_Form`, the basic usage and various classes and plugins available, and internationalization of your forms. Please join me Wednesday at noon EST!
vrkansagara/mwop.net
data/blog/2008/160-Zend_Form-Webinar-Wednesday.md
Markdown
bsd-2-clause
789
<div> <b>{{ obj }}</b> {{ tostring(*ar.summary_row(obj)) }} (<a href="{{ obj.publisher_url() }}">permalink</a> | {{ tostring(ar.obj2html(obj, "edit")) }}) </div>
lino-framework/lino
lino/modlib/publisher/config/publisher/item.pub.html
HTML
bsd-2-clause
162
<!DOCTYPE html> <html> <head> <title>Phantomas Web Designer</title> <meta charset="utf-8"> <link rel="icon" href="icons/favicon.ico"> <link rel="stylesheet" href="css/normalize.css" /> <link rel="stylesheet" href="css/w3.css" /> <link rel="stylesheet" href="css/main.css" /> <link rel="stylesheet" href="css/icons.css"> <script type="text/javascript" src="lib/three.min.js"></script> <script type="text/javascript" src="lib/TrackballControls.js"></script> <script type="text/javascript" src="lib/TransformControls.js"></script> <script type="text/javascript" src="js/FiberSource.js"></script> <script type="text/javascript" src="js/MeshSource.js"></script> <script type="text/javascript" src="js/Phantom.js"></script> <script type="text/javascript" src="js/dragAndDrop.js"></script> <script type="text/javascript" src="js/load.js"></script> <script type="text/javascript" src="js/save.js"></script> <script type="text/javascript" src="js/axes.js"></script> <script type="text/javascript" src="js/main.js"></script> <script type="text/javascript" src="gui/handlers.js"></script> <script type="text/javascript" src="gui/resize.js"></script> <script type="text/javascript" src="gui/status.js"></script> <script type="text/javascript" src="gui/setup.js"></script> <script type="text/javascript" src="gui/stylehandlers.js"></script> <script type="text/javascript" src="gui/fiberedit.js"></script> <script type="text/javascript" src="gui/regionedit.js"></script> <script type="text/javascript" src="gui/cpedit.js"></script> </head> <body> <div id="leftGUI"> <!-- Title code from http://stackoverflow.com/questions/2812770/add-centered-text-to-the-middle-of-a-hr-like-line --> <div style="width: 100%; height: 8px; border-bottom: 1px solid white; text-align: center"> <span style="background-color: #000000; padding: 0 10px"> Fibers </span> </div> <ul id="fiberSelector" style="width:120px;" onmouseout="guiStatus.retrieve();"> </ul><br> <div style="width: 100%; height: 8px; border-bottom: 1px solid white; text-align: center"> <span style="background-color: #000000; padding: 0 10px"> Isotropic Regions </span> </div> <ul id="regionSelector" style="width:120px" onmouseout="guiStatus.retrieve();"> </ul> <div id="editGUI"> </div> </div> <div id="container"> </div> <div id="rightGUI"> <button id='switchViewButton' title="Preview (P)" class='w3-btn w3-border-top w3-border-left w3-border-right w3-hover-aqua w3-block w3-ripple' onclick="switchViewButton();"> <i class="icons">&#xE9CE;</i></button> <button id='skeletonButton' title="View skeleton (V)" class='w3-btn w3-border w3-hover-grey w3-block w3-ripple' onclick="toggleSkeleton();"> <i class="icons">&#xE902;</i></button> <br> <ul> <li> <button id='toggleAxesButton' title="Axes (A)" style='margin-bottom: 5px' class='w3-btn w3-border w3-hover-deep-purple w3-block w3-ripple' onclick='toggleAxes()'> <i class="icons">&#xE22D;</i></button> </li> <li> <input type='button' class="w3-button w3-blue w3-block" value='zy' title="X Plane (X)" onclick='moveCameraZY();'> </li> <li> <input type='button' class="w3-button w3-green w3-block" value='xz' title="Y Plane (Y)" onclick='moveCameraXZ();'> </li> <li> <input type='button' class="w3-button w3-red w3-block" value='xy' title="Z Plane (Z)" onclick='moveCameraXY();'> </li> </ul> <br> <label> <i class="icons">&#xE91C;<span style='font-family:default;'>(%)</span></i> </label> <input id='opacitySelector' class="w3-input w3-border field" style='width:100%' type="number" min='0' max='50' step='5' onchange='opacitySelectChange(this);' /> <div id="bottomButtons"> <button class="w3-button w3-grey w3-hover-green w3-ripple w3-block" onclick="saveClick();" title="Save (S)"> <i class="icons">&#xE9C7;</i></button> </div> </div> <a id="downloadAnchorElem" style="display:none"> <!-- Must stay empty, to be used for pushing phantom download --> </a> </body> </html>
ecaruyer/phantomas-web
phantomas.html
HTML
bsd-2-clause
4,294
/** ****************************************************************************** * File Name : DAC.h * Date : 18/01/2015 10:00:30 * Description : This file provides code for the configuration * of the DAC instances. ****************************************************************************** * * COPYRIGHT(c) 2015 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifdef USE_GEN #ifndef __DAC_H #define __DAC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f3xx_hal.h" //extern DAC_HandleTypeDef hdac; void MX_DAC1_Init(void); void MX_DAC2_Init(void); void DAC_DMA_Reconfig(uint8_t chan, uint32_t *buff, uint32_t len); void DACDisableOutput(void); void DACEnableOutput(void); void DACSetOutputBuffer(void); void DACUnsetOutputBuffer(void); void GeneratingEnable (void); void GeneratingDisable (void); #ifdef __cplusplus } #endif #endif /*__DAC_H */ /** * @} */ /** * @} */ #endif //USE_GEN /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
jirik09/Instrulab
V2/Projects/STM32F303 Nucleo32/Inc/dac.h
C
bsd-2-clause
2,832
# $FreeBSD: soc2013/dpl/head/usr.bin/rwall/Makefile 125476 2004-02-04 11:59:08Z ru $ PROG = rwall .include <bsd.prog.mk>
dplbsd/zcaplib
head/usr.bin/rwall/Makefile
Makefile
bsd-2-clause
123
class Libsndfile < Formula desc "C library for files containing sampled sound" homepage "http://www.mega-nerd.com/libsndfile/" url "https://github.com/erikd/libsndfile/releases/download/v1.0.30/libsndfile-1.0.30.tar.bz2" sha256 "ec898634766595438142c76cf3bdd46b77305d4a295dd16b29d024122d7a4b3f" license "LGPL-2.1-or-later" livecheck do url :homepage regex(/href=.*?libsndfile[._-]v?([\d.]+)\.t/i) end bottle do cellar :any sha256 "bf93a0083eecbcadc7eb391b9f429e0f55c4f571b5f4d9104cfaf60f8e5932dc" => :catalina sha256 "ef1bd6eb6f6d33e22a05116b0893d85422e3ad7fced4252eace97232e523075d" => :mojave sha256 "9d7d184ccf41eff27b8425a8fd50d60fa8a383338efcd0dcf7121f0ce7e3545c" => :high_sierra end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "flac" depends_on "libogg" depends_on "libvorbis" depends_on "opus" def install system "autoreconf", "-fvi" system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do output = shell_output("#{bin}/sndfile-info #{test_fixtures("test.wav")}") assert_match "Duration : 00:00:00.064", output end end
jvillard/homebrew-core
Formula/libsndfile.rb
Ruby
bsd-2-clause
1,273
/* * Copyright (C) 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if ENABLE(MEDIA_STREAM) #include "RTCOfferAnswerOptions.h" #include <wtf/text/WTFString.h> namespace WebCore { PassRefPtr<RTCOfferAnswerOptions> RTCOfferAnswerOptions::create(const Dictionary& options, ExceptionCode& ec) { RefPtr<RTCOfferAnswerOptions> offerAnswerOptions = adoptRef(new RTCOfferAnswerOptions()); String requestIdentity; if (!offerAnswerOptions->initialize(options)) { // FIXME: https://webkit.org/b/129800 // According to the spec, the error is going to be defined yet, so let's use TYPE_MISMATCH_ERR for now. ec = TYPE_MISMATCH_ERR; return nullptr; } return offerAnswerOptions.release(); } bool RTCOfferAnswerOptions::initialize(const Dictionary& options) { if (!m_private) m_private = RTCOfferAnswerOptionsPrivate::create(); String requestIdentity; if (!options.isUndefinedOrNull() && (!options.get("requestIdentity", requestIdentity) || requestIdentity.isEmpty())) return false; m_private->setRequestIdentity(requestIdentity); return true; } PassRefPtr<RTCOfferOptions> RTCOfferOptions::create(const Dictionary& options, ExceptionCode& ec) { RefPtr<RTCOfferOptions> offerOptions = adoptRef(new RTCOfferOptions()); if (!offerOptions->initialize(options)) { // FIXME: https://webkit.org/b/129800 // According to the spec, the error is going to be defined yet, so let's use TYPE_MISMATCH_ERR for now. ec = TYPE_MISMATCH_ERR; return nullptr; } return offerOptions.release(); } bool RTCOfferOptions::initialize(const Dictionary& options) { RefPtr<RTCOfferOptionsPrivate> optionsPrivate = RTCOfferOptionsPrivate::create(); m_private = optionsPrivate; if (options.isUndefinedOrNull()) return true; if (!RTCOfferAnswerOptions::initialize(options)) return false; String offerToReceiveVideoStr; bool numberConversionSuccess; if (!options.get("offerToReceiveVideo", offerToReceiveVideoStr)) return false; int64_t intConversionResult = offerToReceiveVideoStr.toInt64Strict(&numberConversionSuccess); if (!numberConversionSuccess) return false; optionsPrivate->setOfferToReceiveVideo(intConversionResult); String offerToReceiveAudioStr; if (!options.get("offerToReceiveAudio", offerToReceiveAudioStr)) return false; intConversionResult = offerToReceiveAudioStr.toInt64Strict(&numberConversionSuccess); if (!numberConversionSuccess) return false; optionsPrivate->setOfferToReceiveAudio(intConversionResult); bool voiceActivityDetection; if (options.get("voiceActivityDetection", voiceActivityDetection)) optionsPrivate->setVoiceActivityDetection(voiceActivityDetection); bool iceRestart; if (options.get("iceRestart", iceRestart)) optionsPrivate->setIceRestart(iceRestart); return true; } } // namespace WebCore #endif // ENABLE(MEDIA_STREAM)
aosm/WebCore
Modules/mediastream/RTCOfferAnswerOptions.cpp
C++
bsd-2-clause
4,306
#region FreeBSD // Copyright (c) 2013, The Tribe // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Linq; using System.Text; using HBase.Stargate.Client.Models; using HBase.Stargate.Client.Properties; namespace HBase.Stargate.Client.Api { /// <summary> /// Provides a basic implementation of <see cref="IResourceBuilder" />. /// </summary> public class ResourceBuilder : IResourceBuilder { private const string _wildCard = "*"; private const string _appendSegmentFormat = "/{0}"; private const string _appendQualifierFormat = ":{0}"; private const string _appendRangeFormat = ",{0}"; private const string _appendMaxVersionsFormat = "?v={0}"; private const string _schema = "schema"; private const string _scanner = "scanner"; private readonly IStargateOptions _options; /// <summary> /// Initializes a new instance of the <see cref="ResourceBuilder" /> class. /// </summary> /// <param name="options">The HBase Stargate options.</param> public ResourceBuilder(IStargateOptions options) { _options = options; } /// <summary> /// Builds a cell or row query URI. /// </summary> /// <param name="query"></param> public string BuildCellOrRowQuery(CellQuery query) { if (!query.CanDescribeTable()) { throw new ArgumentException(Resources.ResourceBuilder_MinimumForCellOrRowQueryNotMet); } return BuildFromCellQuery(query).ToString(); } /// <summary> /// Builds a delete-item URI. /// </summary> /// <param name="identifier">The identifier.</param> public string BuildDeleteItem(Identifier identifier) { if (!identifier.CanDescribeRow()) { throw new ArgumentException(Resources.ResourceBuilder_MinimumForDeleteItemNotMet); } return BuildFromIdentifier(identifier).ToString(); } /// <summary> /// Builds a batch insert URI. /// </summary> /// <param name="identifier">The identifier.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public string BuildBatchInsert(Identifier identifier) { if (!identifier.CanDescribeTable()) { throw new ArgumentException(Resources.ResourceBuilder_MinimumForBatchInsertNotMet); } return new StringBuilder(identifier.Table).AppendFormat(_appendSegmentFormat, _options.FalseRowKey).ToString(); } /// <summary> /// Builds a table creation URI. /// </summary> /// <param name="tableSchema">The table schema.</param> public string BuildTableSchemaAccess(TableSchema tableSchema) { if (tableSchema == null || string.IsNullOrEmpty(tableSchema.Name)) { throw new ArgumentException(Resources.ResourceBuilder_MinimumForSchemaUpdateNotMet); } return new StringBuilder(tableSchema.Name).AppendFormat(_appendSegmentFormat, _schema).ToString(); } /// <summary> /// Builds a scanner creation URI. /// </summary> /// <param name="scannerOptions">Name of the table.</param> public string BuildScannerCreate(ScannerOptions scannerOptions) { if (scannerOptions == null || string.IsNullOrEmpty(scannerOptions.TableName)) { throw new ArgumentException(Resources.ResourceBuilder_MinimumForScannerNotMet); } return new StringBuilder(scannerOptions.TableName).AppendFormat(_appendSegmentFormat, _scanner).ToString(); } /// <summary> /// Builds a single value storage URI. /// </summary> /// <param name="identifier">The identifier.</param> /// <param name="forReading"> /// if set to <c>true</c> this resource will be used for reading. /// </param> public string BuildSingleValueAccess(Identifier identifier, bool forReading = false) { if (!identifier.CanDescribeCell()) { throw new ArgumentException(Resources.ResourceBuilder_MinimumForSingleValueAccessNotMet); } StringBuilder builder = BuildFromIdentifier(identifier); return (forReading ? SetMaxVersions(1, builder) : builder).ToString(); } private static StringBuilder BuildFromIdentifier(Identifier identifier) { bool hasTimestamp = identifier.Timestamp.HasValue; StringBuilder uriBuilder = BuildFromDescriptor(identifier); bool columnMissing = identifier.CellDescriptor == null || string.IsNullOrEmpty(identifier.CellDescriptor.Column); if (columnMissing && !hasTimestamp) { return uriBuilder; } uriBuilder.AppendFormat(_appendSegmentFormat, columnMissing ? _wildCard : identifier.CellDescriptor.Column); if (!columnMissing && !string.IsNullOrEmpty(identifier.CellDescriptor.Qualifier)) { uriBuilder.AppendFormat(_appendQualifierFormat, identifier.CellDescriptor.Qualifier); } if (hasTimestamp) { uriBuilder.AppendFormat(_appendSegmentFormat, identifier.Timestamp); } return uriBuilder; } private static StringBuilder BuildFromCellQuery(CellQuery query) { bool hasTimestamp = query.EndTimestamp.HasValue && (!query.BeginTimestamp.HasValue || query.BeginTimestamp.Value < query.EndTimestamp.Value); StringBuilder uriBuilder = BuildFromDescriptor(query); bool columnsMissing = query.Cells == null || query.Cells.All(cell => string.IsNullOrEmpty(cell.Column)); if (columnsMissing && !hasTimestamp) { return SetMaxVersions(query.MaxVersions, uriBuilder); } if (!columnsMissing) { HBaseCellDescriptor[] validCells = query.Cells.Where(cell => !string.IsNullOrEmpty(cell.Column)).ToArray(); HBaseCellDescriptor firstCell = validCells.First(); uriBuilder.AppendFormat(_appendSegmentFormat, firstCell.Column); if (!string.IsNullOrEmpty(firstCell.Qualifier)) { uriBuilder.AppendFormat(_appendQualifierFormat, firstCell.Qualifier); } foreach (HBaseCellDescriptor cell in validCells.Skip(1)) { uriBuilder.AppendFormat(_appendRangeFormat, cell.Column); if (!string.IsNullOrEmpty(cell.Qualifier)) { uriBuilder.AppendFormat(_appendQualifierFormat, cell.Qualifier); } } } else { uriBuilder.AppendFormat(_appendSegmentFormat, _wildCard); } if (hasTimestamp) { if (query.BeginTimestamp.HasValue) { uriBuilder.AppendFormat(_appendSegmentFormat, query.BeginTimestamp); uriBuilder.AppendFormat(_appendRangeFormat, query.EndTimestamp); } else { uriBuilder.AppendFormat(_appendSegmentFormat, query.EndTimestamp); } } return SetMaxVersions(query.MaxVersions, uriBuilder); } private static StringBuilder SetMaxVersions(int? maxVersions, StringBuilder uriBuilder) { if (maxVersions.HasValue) { uriBuilder.AppendFormat(_appendMaxVersionsFormat, maxVersions); } return uriBuilder; } private static StringBuilder BuildFromDescriptor(HBaseDescriptor identifier) { return new StringBuilder(identifier.Table) .AppendFormat(_appendSegmentFormat, string.IsNullOrEmpty(identifier.Row) ? _wildCard : identifier.Row); } } }
TheTribe/hadoop-client
src/HBase.Stargate.Client/Api/ResourceBuilder.cs
C#
bsd-2-clause
8,148
-- Copyright (C) 2017-2018 by chrono -- curl 127.1/req_body -d 'xxxx' ngx.req.read_body() local data = ngx.req.get_body_data() if data then ngx.say("body: ", data) else local name = ngx.req.get_body_file() local f = io.open(name, "r") data = f:read("*a") f:close() end ngx.req.set_body_data('yyyy') local data = ngx.req.get_body_data() ngx.say("body: ", data) ngx.req.set_body_file("/tmp/map.list") local data = ngx.req.get_body_data() ngx.say("body: ", data or "-") ngx.req.init_body() ngx.req.append_body('aaa') ngx.req.append_body('bbb') ngx.req.finish_body() local data = ngx.req.get_body_data() ngx.say("body: ", data) --[[ local f = io.open("/tmp/map.list", "r") data = f:read("*a") f:close() ngx.say(data or "-") --]]
chronolaw/openresty_guide
service/http/req_body.lua
Lua
bsd-2-clause
771
# typed: false # frozen_string_literal: true require "cmd/shared_examples/args_parse" describe "Homebrew.deps_args" do it_behaves_like "parseable arguments" end describe "brew deps", :integration_test do it "outputs all of a Formula's dependencies and their dependencies on separate lines" do setup_test_formula "foo" setup_test_formula "bar" setup_test_formula "baz", <<~RUBY url "https://brew.sh/baz-1.0" depends_on "bar" RUBY expect { brew "deps", "baz" } .to be_a_success .and output("bar\nfoo\n").to_stdout .and not_to_output.to_stderr end end
konqui/brew
Library/Homebrew/test/cmd/deps_spec.rb
Ruby
bsd-2-clause
609
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_COCOA_OMNIBOX_OMNIBOX_VIEW_MAC_H_ #define CHROME_BROWSER_UI_COCOA_OMNIBOX_OMNIBOX_VIEW_MAC_H_ #import <Cocoa/Cocoa.h> #include <stddef.h> #include <memory> #include "base/macros.h" #include "base/strings/string16.h" #include "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.h" #include "components/omnibox/browser/omnibox_view.h" #include "components/security_state/security_state_model.h" #include "third_party/skia/include/core/SkColor.h" class CommandUpdater; class OmniboxPopupView; class Profile; namespace content { class WebContents; } namespace ui { class Clipboard; } // Implements OmniboxView on an AutocompleteTextField. class OmniboxViewMac : public OmniboxView, public AutocompleteTextFieldObserver { public: static SkColor BaseTextColorSkia(bool in_dark_mode); static NSColor* BaseTextColor(bool in_dark_mode); static NSColor* GetSecureTextColor( security_state::SecurityStateModel::SecurityLevel security_level, bool in_dark_mode); OmniboxViewMac(OmniboxEditController* controller, Profile* profile, CommandUpdater* command_updater, AutocompleteTextField* field); ~OmniboxViewMac() override; // For use when switching tabs, this saves the current state onto the tab so // that it can be restored during a later call to Update(). void SaveStateToTab(content::WebContents* tab); // Called when the window's active tab changes. void OnTabChanged(const content::WebContents* web_contents); // Called to clear the saved state for |web_contents|. void ResetTabState(content::WebContents* web_contents); // OmniboxView: void Update() override; void OpenMatch(const AutocompleteMatch& match, WindowOpenDisposition disposition, const GURL& alternate_nav_url, const base::string16& pasted_text, size_t selected_line) override; base::string16 GetText() const override; void SetWindowTextAndCaretPos(const base::string16& text, size_t caret_pos, bool update_popup, bool notify_text_changed) override; void EnterKeywordModeForDefaultSearchProvider() override; bool IsSelectAll() const override; bool DeleteAtEndPressed() override; void GetSelectionBounds(base::string16::size_type* start, base::string16::size_type* end) const override; void SelectAll(bool reversed) override; void RevertAll() override; void UpdatePopup() override; void CloseOmniboxPopup() override; void SetFocus() override; void ApplyCaretVisibility() override; void OnTemporaryTextMaybeChanged(const base::string16& display_text, bool save_original_selection, bool notify_text_changed) override; bool OnInlineAutocompleteTextMaybeChanged(const base::string16& display_text, size_t user_text_length) override; void OnInlineAutocompleteTextCleared() override; void OnRevertTemporaryText() override; void OnBeforePossibleChange() override; bool OnAfterPossibleChange(bool allow_keyword_ui_change) override; gfx::NativeView GetNativeView() const override; gfx::NativeView GetRelativeWindowForPopup() const override; void SetGrayTextAutocompletion(const base::string16& input) override; base::string16 GetGrayTextAutocompletion() const override; int GetTextWidth() const override; int GetWidth() const override; bool IsImeComposing() const override; // Implement the AutocompleteTextFieldObserver interface. NSRange SelectionRangeForProposedRange(NSRange proposed_range) override; void OnControlKeyChanged(bool pressed) override; bool CanCopy() override; base::scoped_nsobject<NSPasteboardItem> CreatePasteboardItem() override; void CopyToPasteboard(NSPasteboard* pboard) override; void OnPaste() override; bool CanPasteAndGo() override; int GetPasteActionStringId() override; void OnPasteAndGo() override; void OnFrameChanged() override; void ClosePopup() override; void OnDidBeginEditing() override; void OnBeforeChange() override; void OnDidChange() override; void OnDidEndEditing() override; void OnInsertText() override; void OnDidDrawRect() override; bool OnDoCommandBySelector(SEL cmd) override; void OnSetFocus(bool control_down) override; void OnKillFocus() override; void OnMouseDown(NSInteger button_number) override; // Helper for LocationBarViewMac. Optionally selects all in |field_|. void FocusLocation(bool select_all); // Helper to get the font to use in the field, exposed for the // popup. static NSFont* GetNormalFieldFont(); static NSFont* GetBoldFieldFont(); static NSFont* GetLargeFont(); static NSFont* GetSmallFont(); // If |resource_id| has a PDF image which can be used, return it. // Otherwise return the PNG image from the resource bundle. static NSImage* ImageForResource(int resource_id); // Color used to draw suggest text. static NSColor* SuggestTextColor(); AutocompleteTextField* field() const { return field_; } private: // Called when the user hits backspace in |field_|. Checks whether // keyword search is being terminated. Returns true if the // backspace should be intercepted (not forwarded on to the standard // machinery). bool OnBackspacePressed(); // Returns the field's currently selected range. Only valid if the // field has focus. NSRange GetSelectedRange() const; // Returns the field's currently marked range. Only valid if the field has // focus. NSRange GetMarkedRange() const; // Returns true if |field_| is first-responder in the window. Used // in various DCHECKS to make sure code is running in appropriate // situations. bool IsFirstResponder() const; // If |model_| believes it has focus, grab focus if needed and set // the selection to |range|. Otherwise does nothing. void SetSelectedRange(const NSRange range); // Update the field with |display_text| and highlight the host and scheme (if // it's an URL or URL-fragment). Resets any suggest text that may be present. void SetText(const base::string16& display_text); // Internal implementation of SetText. Does not reset the suggest text before // setting the display text. Most callers should use |SetText()| instead. void SetTextInternal(const base::string16& display_text); // Update the field with |display_text| and set the selection. void SetTextAndSelectedRange(const base::string16& display_text, const NSRange range); // Pass the current content of |field_| to SetText(), maintaining // any selection. Named to be consistent with GTK and Windows, // though here we cannot really do the in-place operation they do. void EmphasizeURLComponents() override; // Apply our font and paragraph style to |attributedString|. void ApplyTextStyle(NSMutableAttributedString* attributedString); // Calculates text attributes according to |display_text| and applies them // to the given |attributedString| object. void ApplyTextAttributes(const base::string16& display_text, NSMutableAttributedString* attributedString); // Return the number of UTF-16 units in the current buffer, excluding the // suggested text. int GetOmniboxTextLength() const override; NSUInteger GetTextLength() const; // Returns true if the caret is at the end of the content. bool IsCaretAtEnd() const; // Announce that an inline autocomplete is available for screenreaders. void AnnounceAutocompleteForScreenReader(const base::string16& text); Profile* profile_; std::unique_ptr<OmniboxPopupView> popup_view_; AutocompleteTextField* field_; // owned by tab controller // Selection at the point where the user started using the // arrows to move around in the popup. NSRange saved_temporary_selection_; // Tracking state before and after a possible change for reporting // to model_. State state_before_change_; NSRange marked_range_before_change_; // Was delete pressed? bool delete_was_pressed_; // Was the delete key pressed with an empty selection at the end of the edit? bool delete_at_end_pressed_; base::string16 suggest_text_; // State used to coalesce changes to text and selection to avoid drawing // transient state. bool in_coalesced_update_block_; bool do_coalesced_text_update_; base::string16 coalesced_text_update_; bool do_coalesced_range_update_; NSRange coalesced_range_update_; // The time of the first character insert operation that has not yet been // painted. Used to measure omnibox responsiveness with a histogram. base::TimeTicks insert_char_time_; DISALLOW_COPY_AND_ASSIGN(OmniboxViewMac); }; #endif // CHROME_BROWSER_UI_COCOA_OMNIBOX_OMNIBOX_VIEW_MAC_H_
ssaroha/node-webrtc
third_party/webrtc/include/chromium/src/chrome/browser/ui/cocoa/omnibox/omnibox_view_mac.h
C
bsd-2-clause
9,138
package cn.com.newcapec.citycard.common.po; import cn.com.newcapec.citycard.common.po.base.BaseTLog; public class TLog extends BaseTLog { private static final long serialVersionUID = 1L; /*[CONSTRUCTOR MARKER BEGIN]*/ public TLog () { super(); } /** * Constructor for primary key */ public TLog (java.lang.Integer id) { super(id); } /** * Constructor for required fields */ public TLog ( java.lang.Integer id, java.lang.String operator, java.lang.String module, java.lang.String action, java.lang.String logContent, java.util.Date logDate) { super ( id, operator, module, action, logContent, logDate); } /*[CONSTRUCTOR MARKER END]*/ }
zhangjunfang/eclipse-dir
eCardCity2.0/0.ecardcity-makecard/src/main/java/cn/com/newcapec/citycard/common/po/TLog.java
Java
bsd-2-clause
698
from django.test import TestCase from threadlocals.threadlocals import set_current_user from django.contrib.auth import get_user_model from powerdns.models import ( Domain, DomainRequest, Record, RecordRequest, ) from .utils import ( ServiceFactory, assert_does_exist, assert_not_exists, ) class TestRequests(TestCase): """Tests for domain/record requests""" def setUp(self): self.user1 = get_user_model().objects.create_user( 'user1', 'user1@example.com', 'password' ) self.user2 = get_user_model().objects.create_user( 'user2', 'user2@example.com', 'password' ) self.domain = Domain.objects.create( name='example.com', type='NATIVE', owner=self.user1 ) self.record = Record.objects.create( domain=self.domain, name='forum.example.com', type='CNAME', content='phpbb.example.com', owner=self.user1, ) def test_subdomain_creation(self): set_current_user(self.user1) request = DomainRequest.objects.create( parent_domain=self.domain, target_name='subdomain.example.com', target_owner=self.user1, target_service=ServiceFactory(), ) request.accept() assert_does_exist( Domain, name='subdomain.example.com', owner=self.user1 ) def test_domain_change(self): request = DomainRequest.objects.create( domain=self.domain, target_name='example.com', target_type='MASTER', owner=self.user2, target_owner=self.user1, target_service=ServiceFactory(), ) request.accept() assert_does_exist( Domain, name='example.com', type='MASTER', owner=self.user1 ) assert_not_exists(Domain, name='example.com', type='NATIVE') def test_record_creation(self): request = RecordRequest.objects.create( domain=self.domain, target_type='CNAME', target_name='site.example.com', target_content='www.example.com', owner=self.user1, target_owner=self.user2, ) request.accept() assert_does_exist( Record, content='www.example.com', owner=self.user2, ) def test_record_change(self): request = RecordRequest.objects.create( domain=self.domain, record=self.record, target_type='CNAME', target_name='forum.example.com', target_content='djangobb.example.com', target_owner=self.user2, owner=self.user1, ) request.accept() assert_does_exist(Record, content='djangobb.example.com') assert_not_exists(Record, content='phpbb.example.com')
dominikkowalski/django-powerdns-dnssec
powerdns/tests/test_requests.py
Python
bsd-2-clause
2,984
/*- * Copyright (C) 2010-2014, Centre National de la Recherche Scientifique, * Institut Polytechnique de Bordeaux, * Universite de Bordeaux. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef KERNEL_ARCHITECTURE_SPARC_HH #define KERNEL_ARCHITECTURE_SPARC_HH #include <kernel/Architecture.hh> /** \brief Specification of the sparc architecture. */ class Architecture_SPARC : public Architecture { public: Architecture_SPARC (const endianness_t); }; #endif /* KERNEL_ARCHITECTURE_SPARC_HH */
jorik041/insight
src/kernel/Architecture_SPARC.hh
C++
bsd-2-clause
1,831
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" /> <title>Tests</title> <style type="text/css"> /* :Author: David Goodger (goodger@python.org) :Id: $Id: html4css1.css 7056 2011-06-17 10:50:48Z milde $ :Copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to customize this style sheet. */ /* used to remove borders from tables and images */ .borderless, table.borderless td, table.borderless th { border: 0 } table.borderless td, table.borderless th { /* Override padding for "table.docutils td" with "! important". The right padding separates the table cells. */ padding: 0 0.5em 0 0 ! important } .first { /* Override more specific margin styles with "! important". */ margin-top: 0 ! important } .last, .with-subtitle { margin-bottom: 0 ! important } .hidden { display: none } a.toc-backref { text-decoration: none ; color: black } blockquote.epigraph { margin: 2em 5em ; } dl.docutils dd { margin-bottom: 0.5em } object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] { overflow: hidden; } /* Uncomment (and remove this text!) to get bold-faced definition list terms dl.docutils dt { font-weight: bold } */ div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.admonition, div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.admonition p.admonition-title, div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } /* Uncomment (and remove this text!) to get reduced vertical space in compound paragraphs. div.compound .compound-first, div.compound .compound-middle { margin-bottom: 0.5em } div.compound .compound-last, div.compound .compound-middle { margin-top: 0.5em } */ div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em ; margin-right: 2em } div.footer, div.header { clear: both; font-size: smaller } div.line-block { display: block ; margin-top: 1em ; margin-bottom: 1em } div.line-block div.line-block { margin-top: 0 ; margin-bottom: 0 ; margin-left: 1.5em } div.sidebar { margin: 0 0 0.5em 1em ; border: medium outset ; padding: 1em ; background-color: #ffffee ; width: 40% ; float: right ; clear: right } div.sidebar p.rubric { font-family: sans-serif ; font-size: medium } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.section-subtitle, h2.section-subtitle, h3.section-subtitle, h4.section-subtitle, h5.section-subtitle, h6.section-subtitle { margin-top: 0.4em } h1.title { text-align: center } h2.subtitle { text-align: center } hr.docutils { width: 75% } img.align-left, .figure.align-left, object.align-left { clear: left ; float: left ; margin-right: 1em } img.align-right, .figure.align-right, object.align-right { clear: right ; float: right ; margin-left: 1em } img.align-center, .figure.align-center, object.align-center { display: block; margin-left: auto; margin-right: auto; } .align-left { text-align: left } .align-center { clear: both ; text-align: center } .align-right { text-align: right } /* reset inner alignment in figures */ div.align-right { text-align: inherit } /* div.align-center * { */ /* text-align: left } */ ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.attribution { text-align: right ; margin-left: 50% } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.label { white-space: nowrap } p.rubric { font-weight: bold ; font-size: larger ; color: maroon ; text-align: center } p.sidebar-title { font-family: sans-serif ; font-weight: bold ; font-size: larger } p.sidebar-subtitle { font-family: sans-serif ; font-weight: bold } p.topic-title { font-weight: bold } pre.address { margin-bottom: 0 ; margin-top: 0 ; font: inherit } pre.literal-block, pre.doctest-block, pre.math { margin-left: 2em ; margin-right: 2em } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.interpreted { font-family: sans-serif } span.option { white-space: nowrap } span.pre { white-space: pre } span.problematic { color: red } span.section-subtitle { /* font-size relative to parent (h1..h6 element) */ font-size: 80% } table.citation { border-left: solid 1px gray; margin-left: 1px } table.docinfo { margin: 2em 4em } table.docutils { margin-top: 0.5em ; margin-bottom: 0.5em } table.footnote { border-left: solid 1px black; margin-left: 1px } table.docutils td, table.docutils th, table.docinfo td, table.docinfo th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: top } table.docutils th.field-name, table.docinfo th.docinfo-name { font-weight: bold ; text-align: left ; white-space: nowrap ; padding-left: 0 } h1 tt.docutils, h2 tt.docutils, h3 tt.docutils, h4 tt.docutils, h5 tt.docutils, h6 tt.docutils { font-size: 100% } ul.auto-toc { list-style-type: none } </style> </head> <body> <div class="document" id="tests"> <h1 class="title">Tests</h1> <div class="contents topic" id="contents"> <p class="topic-title first">Contents</p> <ul class="simple"> <li><a class="reference internal" href="#a-brief-guide-to-running-tests" id="id1">A Brief Guide to Running Tests</a></li> <li><a class="reference internal" href="#a-brief-guide-to-writing-tests" id="id2">A Brief Guide to Writing Tests</a></li> </ul> </div> <div class="section" id="a-brief-guide-to-running-tests"> <span id="running"></span><h1><a class="toc-backref" href="#id1">A Brief Guide to Running Tests</a></h1> <p>After a successful &quot;<tt class="docutils literal">make</tt>&quot;, try &quot;<tt class="docutils literal">make check</tt>&quot;.</p> <p>It's possible to run test cases individually, and get verbose output when one fails, etc. For more information, see the &quot;Running test programs&quot; section of HACKING.</p> </div> <div class="section" id="a-brief-guide-to-writing-tests"> <span id="writing"></span><h1><a class="toc-backref" href="#id2">A Brief Guide to Writing Tests</a></h1> <p>Test programs live in <tt class="docutils literal">tests/</tt>. They mostly use a standard test harness, in <tt class="docutils literal">tests/harness/</tt>, which wraps each test, reports results, and generally packages things up nicely. The test harness counts how many testcases pass/fail/skip, catches signals and unhandled exceptions, and so forth. It can also also check for memory leaks and accesses to uninitialised values by making use of valgrind, for platforms which valgrind supports (configure automatically enables use of valgrind if a suitably recent version is detected).</p> <p>A typical test program has three parts: the tests themselves (at the top), a table of tests (at the bottom), and a tiny main which sets the test harness in motion. It uses the table to figure out what the tests are called, and what function to call to run them.</p> <p>The most important test system for most people will be <tt class="docutils literal">apitest</tt>. This also uses the test harness, but has several tables of tests to be run depending what facilities each backend supports. A lot of the work is done by macros and helper functions, which may make it hard to work out quite what is going on, but make life easier once you've grasped what's going on. The <tt class="docutils literal">main()</tt> function and other bits are in <tt class="docutils literal">apitest.cc</tt>, and tests themselves are in various other C++ files starting api_. Each one of these has its own tables for various different groups of tests (eg: <tt class="docutils literal">api_db.cc</tt>, which performs tests on the API that require a database backend, has basic tests, a few specialised groups that only contain one or two tests, tests that require a writable database, tests that require a local database, and finally tests that require a remote database).</p> <p>To add a new api test, figure out what the test will be dependent on and put it in the appropriate place (eg: if adding a test for a bug that occurs while writing to a database, you want a writable database, so you add a test to <tt class="docutils literal">api_db.cc</tt> and reference it in the <tt class="docutils literal">writabledb_tests</tt> table).</p> <p>Currently, there's <tt class="docutils literal">api_nodb.cc</tt> (no db required, largely testing query construction and boundary conditions), <tt class="docutils literal">api_posdb.cc</tt> (db with positional information required) and <tt class="docutils literal">api_db.cc</tt> (everything else, with lots of subgroups of tests). It's easiest to base a test on an existing one.</p> <p>You'll notice in <tt class="docutils literal">apitest.cc</tt> that it runs all appropriate test groups against each backend that is being built. The backends are inmemory, multi, brass, chert, flint, remoteprog and remotetcp. If you need to create a new test group with different requirements to any current ones, put it in the appropriate api_ file (or create a new one, and add it into Makefile.am) and remember to add the group to all pertinent backends in <tt class="docutils literal">apitest.cc</tt>.</p> <p>Incidentally, when fixing bugs, it's often better to write the test before fixing the bug. Firstly, it's easier to assure yourself that the bug is (a) genuine, and (b) fixed, because you see the test go from fail to pass (though sometimes you don't get the testcase quite right, so this isn't doesn't always work as well as it should). Secondly you're more likely to write the test carefully, because once you've fixed something there's often a feeling that you should commit it for the good of the world, which tends to distract you.</p> <p>The framework is done for you, so you don't need to worry about that much. You are responsible for doing two things:</p> <ol class="arabic simple"> <li>writing a minimal test or tests for the feature</li> <li>adding that test to the list of tests to be run</li> </ol> <p>Adding the test is simple. There's a test_desc array in each file that comprises a set of tests (I'll come to that in a minute), and you just add another entry. The entry is an array consisting of a name for the test and a pointer to the function that is the test. Easy. The procedure is even simpler for apitest tests - there you just use DEFINE_TESTCASE to define your new testcase, and a script picks it up and makes sure it is run.</p> <p>Look at the bottom of <tt class="docutils literal">tests/stemtest.cc</tt> for the test_desc array. Now look up about 20 lines to where the test functions are defined. You need to write a function like these which will return true or false depending on whether it failed or not.</p> <p>In addition, there are a bunch of macros to help you perform standards testing tasks. Things like TEST_EQUAL are all in <tt class="docutils literal">tests/harness/testsuite.h</tt>. They're pretty simple to use.</p> </div> </div> </body> </html>
iveteran/xapian-scws
xapian-core_scws-1.2.18/docs/tests.html
HTML
bsd-2-clause
12,511
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE TupleSections #-} #if MIN_VERSION_base(4,8,0) {-# LANGUAGE PatternSynonyms #-} #endif module Succinct.Sequence ( -- $intro WaveletTree(..), Encoding(..), buildOptimizedAlphabeticalSearchTree, huTucker, validHuTuckerTree, ) where import Control.Applicative import Control.Monad import Data.Profunctor import Data.Bifunctor import Data.Bits import qualified Data.Foldable as F import qualified Data.Traversable as T import Data.Ord import Data.List import Data.Function import Succinct.Tree.Types import Succinct.Dictionary.Builder import Succinct.Internal.Building import Succinct.Dictionary.Class import Succinct.Dictionary.Rank9 import Data.Bitraversable import qualified Data.PriorityQueue.FingerTree as PQ import qualified Data.Map as M import qualified Data.Sequence as S import qualified Data.IntSet as IS import qualified Data.Vector.Unboxed as V import qualified Data.Vector.Unboxed.Mutable as MV import Data.Maybe import Control.Monad.ST (runST) import Control.Monad.ST.Unsafe import Data.Monoid import Debug.Trace -- $setup -- >>> :set -XFlexibleContexts -- The members of the alphabet need an encoding newtype Encoding a = Encoding { runEncoding :: Labelled () a } deriving Show directionToBool :: Direction -> Bool #if MIN_VERSION_base(4,8,0) -- We have pattern synonyms newtype Direction = Direction Bool instance Show Direction where show (Direction False) = show "L" show (Direction True) = show "R" pattern L = Direction False pattern R = Direction True directionToBool (Direction x) = x #else data Direction = L | R deriving Show directionToBool L = False directionToBool R = True #endif -- endif MIN_VERSION_base(4,8,0) {-# INLINE directionToBool #-} -- | O(nlog(n)). Given elements in a dictionary and their probability of occuring, -- produce a huffman encoding. huffmanEncoding :: (Num n, Ord n, Functor m, Monad m) => [(a, n)] -> m (Encoding a) huffmanEncoding input = let initial = PQ.fromList $ fmap (\(a, b) -> (b, LabelledTip a)) input in Encoding <$> huffmanHeapToTree initial huffmanHeapToTree :: (Ord n, Num n, Monad m) => PQ.PQueue n (Labelled () a) -> m (Labelled () a) huffmanHeapToTree pq = case PQ.minViewWithKey pq of Just ((k, v), rest) -> case PQ.minViewWithKey rest of Just ((k2, v2), rest2) -> huffmanHeapToTree $ PQ.insert (k+k2) (LabelledBin () v v2) rest2 Nothing -> return v Nothing -> fail "huffmanEncoding: No elements received" buildHistogram :: (Ord a, Num n) => Builder a (M.Map a n) buildHistogram = Builder $ Building stop step start where stop = pure step x c = pure $ M.insertWith (+) c 1 x start = pure M.empty buildHuffmanEncoding :: forall a. (Ord a) => Builder a (Encoding a) buildHuffmanEncoding = fmap (fromJust . huffmanEncoding . M.toList) (buildHistogram :: Builder a (M.Map a Int)) -- | O(n^2). Given a list of characters of an alphabet with a -- frequency, produce an encoding that respects the order provided. -- TODO: this is an implementation of Knuth's O(n^2) dynamic -- programming solution. Hu-Tucker can solve this in O(nlogn) in -- general. buildOptimalAlphabeticSearchTree :: [(a, n)] -> Builder a (Encoding a) buildOptimalAlphabeticSearchTree = undefined diagonalIndex n i j | trace ("(i, j) = " <> show (i,j)) False = undefined diagonalIndex n i j = n * i - i * (i + 1) `div` 2 + j -- data KnuthBuilder s a = KnuthBuilder { weight :: V.STVector s a -- , root :: V.STVector s a -- , path :: V.STVector s a -- } foldableLength :: F.Foldable f => f a -> Int #if MIN_VERSION_base(4,8,0) foldableLength = F.length #else foldableLength = length . F.toList #endif -- --buildOptimalSearchTree :: (Functor f, F.Foldable f, n ~ Int) => f (a, n) -> Labelled () a -- buildOptimalSearchTree input = runST $ do -- let n = foldableLength input -- space = (n+1) * (n+2) `div` 2 -- index = diagonalIndex (n+1) -- get v (i, j) = if j < i then error (show (i, j)) else MV.read v (index i j) -- -- no checks -- grab v (i, j) = MV.read v (index i j) -- weight <- MV.new space -- root <- MV.replicate space (-1) -- path <- MV.new space -- forM_ (zip [1..n] $ F.toList $ fmap snd input) $ \(k, p) -> do -- let i = index k k -- MV.write weight i p -- MV.write root i k -- MV.write path i p -- MV.write path (index k (k-1)) 0 -- MV.write path (index (n+1) n) 0 -- forM_ [1..n-1] $ \diagonal -> do -- forM_ [1..n-diagonal] $ \j -> do -- let k = j + diagonal -- MV.write weight (index j k) =<< ((+) <$> (weight `get` (j, k-1)) <*> (weight `get` (k, k))) -- root1 <- root `get` (j, k-1) -- root2 <- root `get` (j+1, k) -- (p, _) <- F.minimumBy (comparing snd) <$> ( -- forM [root1..root2] $ \p -> do -- a <- path `grab` (j, p-1) -- b <- path `grab` (p+1, k) -- return (p, a + b)) -- unsafeIOToST $ putStrLn $ "p: " <> show p -- unsafeIOToST $ putStrLn $ "root" <> show (j,k) <> ": " <> show p -- MV.write root (index j k) p -- MV.write path (index j k) =<< liftA3 (\a b c -> a + b + c) (path `grab` (j, p-1)) (path `grab` (p+1, k)) (weight `get` (j, k)) -- let go (i, j) | i > j = error $ "creating tree found i > j: " <> show (i, j) -- go (i, j) | i == j = pure $ LabelledTip $ i-1 -- go (i, j) = do -- split <- root `grab` (i, j) -- LabelledBin (split - 1) <$> go (i, split-1) <*> go (split+1, j) -- let depth _ (i, j) | i > j = error $ "creating tree found i > j: " <> show (i, j) -- depth !d (i, j) | i == j = pure $ [(d, i-1)] -- depth !d (i, j) = do -- split <- root `grab` (i, j) -- lefties <- depth (d+1) (i, split-1) -- righties <- depth (d+1) (split+1, j) -- return $ [(d, split - 1)] ++ lefties ++ righties -- depth 0 (1, n) data Attraction = PreviousPrevious | Previous | Self | Next | NextNext deriving (Show, Eq, Ord) data Elem heap b a = Elem (Either a (heap b)) [Attraction] | LeftBoundary | RightBoundary deriving (Eq) instance (Show a, Show b, F.Foldable heap) => Show (Elem heap b a) where show (Elem (Left x) a) = "Elem " <> show x <> " " <> show a show (Elem (Right h) a) = "Elem " <> show (F.toList h) <> " " <> show a show LeftBoundary = "LeftBoundary" show RightBoundary = "RightBoundary" attraction (Elem _ a) = a attraction LeftBoundary = [Previous] attraction RightBoundary = [Next] isBoundary LeftBoundary = True isBoundary RightBoundary = True isBoundary _ = False decideAttraction xs = map f $ filter ok $ tails $ Nothing : fmap Just xs ++ [Nothing] where f (Nothing:_:_:_) = Next f (_:_:Nothing:_) = Previous f (Just a:Just _:Just c:_) = case compare a c of LT -> Previous _ -> Next ok (_:_:_:_) = True ok _ = False --huTucker :: huTucker = constructTree . breadthFirstSearch . buildOptimizedAlphabeticalSearchTree -- return tree in increasing depth breadthFirstSearch :: Labelled () a -> [(a, Int)] breadthFirstSearch t = go $ S.singleton (t, 0) where go to_visit = case S.viewl to_visit of S.EmptyL -> [] (LabelledTip a, !l) S.:< rest -> (a, l) : go rest (LabelledBin _ left right, !l) S.:< rest -> go (rest S.|> (left, l+1) S.|> (right, l+1)) pair :: [a] -> [(a, a)] pair [] = [] pair [x] = error "pair: odd man out" pair (a:b:rest) = (a, b) : pair rest iterateN :: Int -> (a -> a) -> (a -> a) iterateN n f = foldl (.) id $ replicate n f constructTree :: [((Int, a), Int)] -> Labelled () a constructTree = snd . pairUp . snd . foldl1 (\(old_level, acc) (new_level, new) -> (new_level, merge new $ iterateN (old_level - new_level) bin acc)) . map (\l -> (snd $ head l, map fst l)) . map (sortBy (comparing (fst.fst))) . reverse . groupBy ((==) `on` snd) . map (\((index, value), height) -> ((index, LabelledTip value), height)) where bin x = map (\((i,a), (_,b)) -> (i, LabelledBin () a b)) . pair $ x pairUp [] = error "nothing to pair" pairUp [x] = x pairUp xs = pairUp (bin xs) merge a b = sortBy (comparing fst) $ a <> b codewords :: Labelled () a -> [(a, [Bool])] codewords t = fmap (\(a, code) -> (a, reverse code)) $ go $ S.singleton (t, []) where go to_visit = case S.viewl to_visit of S.EmptyL -> [] (LabelledTip a, code) S.:< rest -> (a, code) : go rest (LabelledBin _ left right, code) S.:< rest -> go (rest S.|> (left, False:code) S.|> (right, True:code)) buildOptimizedAlphabeticalSearchTree :: forall a n. (Show a, Eq a, Show n, Ord n, Num n, Bounded n) => [(a, n)] -> Labelled () a buildOptimizedAlphabeticalSearchTree [] = error "Cannot build with empty list of elements" buildOptimizedAlphabeticalSearchTree input = go (repeat LeftBoundary) $ (<> repeat RightBoundary) $ fmap (\((a, freq), attract) -> Elem (Left (freq, LabelledTip a)) [attract]) $ zip input $ decideAttraction $ fmap snd $ input where go past [] = error $ "Internal error: empty future. Past: " <> show (takeWhile (not . isBoundary) past) go past (RightBoundary:_) = error $ "Internal error: no current. Past: " <> show (takeWhile (not . isBoundary) past) go (LeftBoundary:_) (Elem (Left (_, x)) _:RightBoundary:_) = x go (LeftBoundary:_) (Elem (Right h) _:RightBoundary:_) = fromJust $ huffmanHeapToTree h -- If the person I like likes me back, then we deal with it now. go past@(p:past1@(p2:ps)) (x:future@(next:future1@(next2:xs))) = case head $ attraction x of PreviousPrevious | NextNext `elem` attraction p2 -> combine ps (merge (contents p) (fix (contents p2) (contents x))) future Previous | Next `elem` attraction p -> combine past1 (fix (contents p) (contents x)) future Self | Elem (Right heap) _ <- x -> let heap' = case PQ.minViewWithKey heap of Just ((k, v), rest) -> case PQ.minViewWithKey rest of Just ((k2, v2), rest2) -> PQ.insert (k+k2) (LabelledBin () v v2) rest2 Nothing -> error "You shouldn't self attract if you only have one element in the heap" Nothing -> error "heap cannot be empty" in adjust past (Right heap') future Next | Previous `elem` attraction next -> combine past (fix (contents x) (contents next)) future1 NextNext | PreviousPrevious `elem` attraction next2 -> let c = merge (fix (contents x) (contents next2)) (contents next) in combine past c xs -- She loves me not _ -> go (x:past) future value (Elem (Left (freq, _)) _) = freq value (Elem (Right h) _) = heapValue h value RightBoundary = maxBound value LeftBoundary = maxBound contents (Elem x _) = x -- Guaranteed that heap is non-empty heapValue h = case PQ.minViewWithKey h of Just ((k, v), rest) -> k secondSmallestElement h = fst <$> (PQ.minViewWithKey =<< snd <$> PQ.minView h) combine past@(p:past2) x future@(f:future2) = case (isBlocked p, isBlocked f) of (False, False) -> adjust past2 (merge (contents p) $ merge x (contents f)) future2 (False, True) -> adjust past2 (merge (contents p) x) future (True, False) -> adjust past (merge x (contents f)) future2 (True, True) -> adjust past x future adjust past x future = let e = calculate past x future (a:past') = fixPast past (e:future) future' = e : fixFuture (e:past) future in go past' (a:future') fixPast rest@(LeftBoundary:_) _ = rest fixPast (Elem heap _:rest@(LeftBoundary:_)) future = calculate rest heap future : rest fixPast (e1@(Elem heap1 _):rest@(Elem heap2 _:rest2)) future = calculate rest heap1 future : calculate rest2 heap2 (e1 : future) : rest2 fixFuture _ rest@(RightBoundary:_) = rest fixFuture past (Elem heap _:rest@(RightBoundary:_)) = calculate past heap rest : rest fixFuture past (e1@(Elem heap1 _):rest@(Elem heap2 _:rest2)) = calculate past heap1 rest : calculate (e1 : past) heap2 rest2 : rest2 ff (Left x) = "Left " <> show x ff (Right x) = "Right " <> show (F.toList x) calculate (p:p2:_) heap (f:f2:_) = Elem heap $ if can_skip then best $ [(value p, Previous), (value f, Next)] ++ (if not $ isBlocked p then [(value p2, PreviousPrevious)] else []) ++ (if not $ isBlocked f then [(value f2, NextNext)] else []) else case secondSmallestValue of Just (k, _) -> best [(value p, Previous), (k, Self), (value f, Next)] Nothing -> best [(value p, Previous), (value f, Next)] where secondSmallestValue = case heap of Left _ -> Nothing Right h -> secondSmallestElement h can_skip = case heap of Left _ -> True Right _ -> False best = map snd . head . groupBy ((==) `on` fst) . sortBy (comparing fst) fix a = Right . fix' a fix' (Left (k1, v1)) (Left (k2, v2)) = PQ.singleton (k1 + k2) $ LabelledBin () v1 v2 fix' (Left (k1, v1)) (Right h) = case PQ.minViewWithKey h of Just ((k2, v2), rest) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) rest fix' (Right h) (Left (k2, v2)) = case PQ.minViewWithKey h of Just ((k1, v1), rest) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) rest fix' (Right h1) (Right h2) = case PQ.minViewWithKey h1 of Just ((k1, v1), rest) -> case PQ.minViewWithKey h2 of Just ((k2, v2), rest2) -> PQ.insert (k1 + k2) (LabelledBin () v1 v2) $ rest <> rest2 merge a b = Right $ f a <> f b where f = either (uncurry PQ.singleton) id isBlocked (Elem (Right _) _) = False isBlocked _ = True validHuTuckerTree :: (Eq a, Ord a) => Labelled () a -> Bool validHuTuckerTree t = let nodes = inOrderTraversal t in nodes == sort nodes inOrderTraversal :: Labelled () a -> [a] inOrderTraversal (LabelledTip a) = [a] inOrderTraversal (LabelledBin () l r) = inOrderTraversal l ++ inOrderTraversal r data WaveletTree f a = WaveletTree { bits :: Labelled f a , alphabet :: a -> Int -> Direction -- ^ For a given level, is the element to the right or to the left? } instance (Access Bool f, Ranked f) => F.Foldable (WaveletTree f) where foldMap f t = F.foldMap f $ map (t !) [0 .. size t - 1] -- mapBits f (WaveletTree bits alphabet) = WaveletTree (first f bits) alphabet instance (Access Bool f, Ranked f) => Access a (WaveletTree f a) where size (WaveletTree t _) = case t of LabelledTip _ -> 0 LabelledBin x _ _ -> size x (!) (WaveletTree t0 _) index0 = go t0 index0 where go t index = case t of LabelledTip a -> a LabelledBin x left right -> if x ! index then go right (rank1 x index) else go left (rank0 x index) instance (Access Bool f, Select0 f, Select1 f, Ranked f) => Dictionary a (WaveletTree f a) where rank a (WaveletTree t0 find) i0 = go 0 t0 i0 where finda = find a go level t i = case t of LabelledTip _ -> i LabelledBin x left right -> case finda level of L -> go (level+1) left (rank0 x i) R -> go (level+1) right (rank1 x i) select a (WaveletTree t0 find) i0 = findPath 0 t0 i0 where finda = find a findPath level t = case t of LabelledTip _ -> id LabelledBin x left right -> case finda level of L -> (select0 x) . findPath (level+1) left R -> (select1 x) . findPath (level+1) right -- $intro -- >>> :{ -- let abracadabraFind 'a' = const False -- abracadabraFind 'b' = odd -- abracadabraFind 'c' = (> 0) -- abracadabraFind 'd' = even -- abracadabraFind 'r' = const True -- :} -- -- >>> :{ -- let bin = LabelledBin () -- tip = LabelledTip -- abracadabraEncoding = -- bin (bin (tip 'a') (bin (tip 'b') (tip 'c'))) (bin (tip 'd') (tip 'r')) -- :} -- -- >>> :{ -- let (t, f) = (True, False) -- tree = LabelledBin (build [f, f, t, f, f, f, t, f, f, t, f]) -- -- a & (b & c) -- (LabelledBin (build [f, t, f, t, f, f, t, f]) (LabelledTip 'a') -- -- b & c -- (LabelledBin (build [f, t, f]) (LabelledTip 'b') (LabelledTip 'c'))) -- -- d & r -- (LabelledBin (build [t, f, t]) (LabelledTip 'd') (LabelledTip 'r')) -- exampleWaveletTree :: WaveletTree Rank9 Char -- exampleWaveletTree = WaveletTree tree abracadabraFind -- :} -- -- Inefficient foldable -- -- >>> F.toList exampleWaveletTree -- "abracadabra" -- -- >>> [(c, map (select c exampleWaveletTree) [1.. rank c exampleWaveletTree (size exampleWaveletTree)]) | c <- "abcdr"] -- [('a',[1,4,6,8,11]),('b',[2,9]),('c',[5]),('d',[7]),('r',[3,10])] -- -- >>> [(c, map (rank c exampleWaveletTree) [0.. size exampleWaveletTree]) | c <- "abcdr"] -- [('a',[0,1,1,1,2,2,3,3,4,4,4,5]),('b',[0,0,1,1,1,1,1,1,1,2,2,2]),('c',[0,0,0,0,0,1,1,1,1,1,1,1]),('d',[0,0,0,0,0,0,0,1,1,1,1,1]),('r',[0,0,0,1,1,1,1,1,1,1,2,2])] asListOfNumbers :: Access Bool t => t -> [Int] asListOfNumbers t = concat [ [x | t ! x] | x <- [0 .. size t - 1] ] buildWithEncoding :: forall a f. Buildable Bool f => Encoding a -> (a -> Int -> Direction) -> Builder a (Labelled f a) buildWithEncoding (Encoding e) f = Builder $ case builder :: Builder Bool f of Builder (Building stop' step' start') -> Building stop step start where start = bifor e (const start') pure stop x = bifor x stop' pure step x0 c0 = walk c0 0 x0 where walk _ _ a@(LabelledTip{}) = pure a walk c !l (LabelledBin v a b) = let dir = f c l q = LabelledBin <$> step' v (directionToBool dir) in case dir of L -> q <*> walk c (l+1) a <*> pure b R -> q <*> pure a <*> walk c (l+1) b decidingFunction :: Eq a => Encoding a -> (a -> Int -> Direction) decidingFunction (Encoding enc0) = \c -> let Just t = fmap reverse $ go enc0 c [] in (t !!) where go (LabelledTip c') c visited = do guard $ c == c' return $ visited go (LabelledBin _ l _) c visited | Just x <- go l c (L:visited ) = Just x go (LabelledBin _ _ r) c visited | Just x <- go r c (R:visited ) = Just x go _ _ _ = Nothing instance (Ord a, Buildable Bool f) => Buildable a (WaveletTree f a) where builder = runNonStreaming $ do enc <- NonStreaming $ buildHuffmanEncoding let fun = decidingFunction enc NonStreaming $ WaveletTree <$> buildWithEncoding enc fun <*> pure fun
Gabriel439/succinct
src/Succinct/Sequence.hs
Haskell
bsd-2-clause
19,162
/**************************************************************************** * mm/mm_heap/mm_realloc.c * * Copyright (C) 2007, 2009, 2013-2014 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <nuttx/mm/mm.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: mm_realloc * * Description: * If the reallocation is for less space, then: * * (1) the current allocation is reduced in size * (2) the remainder at the end of the allocation is returned to the * free list. * * If the request is for more space and the current allocation can be * extended, it will be extended by: * * (1) Taking the additional space from the following free chunk, or * (2) Taking the additional space from the preceding free chunk. * (3) Or both * * If the request is for more space but the current chunk cannot be * extended, then malloc a new buffer, copy the data into the new buffer, * and free the old buffer. * ****************************************************************************/ FAR void *mm_realloc(FAR struct mm_heap_s *heap, FAR void *oldmem, size_t size) { FAR struct mm_allocnode_s *oldnode; FAR struct mm_freenode_s *prev; FAR struct mm_freenode_s *next; size_t oldsize; size_t prevsize = 0; size_t nextsize = 0; FAR void *newmem; /* If oldmem is NULL, then realloc is equivalent to malloc */ if (!oldmem) { return mm_malloc(heap, size); } /* If size is zero, then realloc is equivalent to free */ if (size < 1) { mm_free(heap, oldmem); return NULL; } /* Adjust the size to account for (1) the size of the allocated node and * (2) to make sure that it is an even multiple of our granule size. */ size = MM_ALIGN_UP(size + SIZEOF_MM_ALLOCNODE); /* Map the memory chunk into an allocated node structure */ oldnode = (FAR struct mm_allocnode_s *)((FAR char*)oldmem - SIZEOF_MM_ALLOCNODE); /* We need to hold the MM semaphore while we muck with the nodelist. */ mm_takesemaphore(heap); /* Check if this is a request to reduce the size of the allocation. */ oldsize = oldnode->size; if (size <= oldsize) { /* Handle the special case where we are not going to change the size * of the allocation. */ if (size < oldsize) { mm_shrinkchunk(heap, oldnode, size); } /* Then return the original address */ mm_givesemaphore(heap); return oldmem; } /* This is a request to increase the size of the allocation, Get the * available sizes before and after the oldnode so that we can make the * best decision */ next = (FAR struct mm_freenode_s *)((FAR char*)oldnode + oldnode->size); if ((next->preceding & MM_ALLOC_BIT) == 0) { nextsize = next->size; } prev = (FAR struct mm_freenode_s *)((FAR char*)oldnode - (oldnode->preceding & ~MM_ALLOC_BIT)); if ((prev->preceding & MM_ALLOC_BIT) == 0) { prevsize = prev->size; } /* Now, check if we can extend the current allocation or not */ if (nextsize + prevsize + oldsize >= size) { size_t needed = size - oldsize; size_t takeprev = 0; size_t takenext = 0; /* Check if we can extend into the previous chunk and if the * previous chunk is smaller than the next chunk. */ if (prevsize > 0 && (nextsize >= prevsize || nextsize < 1)) { /* Can we get everything we need from the previous chunk? */ if (needed > prevsize) { /* No, take the whole previous chunk and get the * rest that we need from the next chunk. */ takeprev = prevsize; takenext = needed - prevsize; } else { /* Yes, take what we need from the previous chunk */ takeprev = needed; takenext = 0; } needed = 0; } /* Check if we can extend into the next chunk and if we still need * more memory. */ if (nextsize > 0 && needed) { /* Can we get everything we need from the next chunk? */ if (needed > nextsize) { /* No, take the whole next chunk and get the rest that we * need from the previous chunk. */ takeprev = needed - nextsize; takenext = nextsize; } else { /* Yes, take what we need from the previous chunk */ takeprev = 0; takenext = needed; } } /* Extend into the previous free chunk */ newmem = oldmem; if (takeprev) { FAR struct mm_allocnode_s *newnode; /* Remove the previous node. There must be a predecessor, but * there may not be a successor node. */ DEBUGASSERT(prev->blink); prev->blink->flink = prev->flink; if (prev->flink) { prev->flink->blink = prev->blink; } /* Extend the node into the previous free chunk */ newnode = (FAR struct mm_allocnode_s *)((FAR char*)oldnode - takeprev); /* Did we consume the entire preceding chunk? */ if (takeprev < prevsize) { /* No.. just take what we need from the previous chunk and put * it back into the free list */ prev->size -= takeprev; newnode->size = oldsize + takeprev; newnode->preceding = prev->size | MM_ALLOC_BIT; next->preceding = newnode->size | (next->preceding & MM_ALLOC_BIT); /* Return the previous free node to the nodelist (with the new size) */ mm_addfreechunk(heap, prev); /* Now we want to return newnode */ oldnode = newnode; } else { /* Yes.. update its size (newnode->preceding is already set) */ newnode->size += oldsize; newnode->preceding |= MM_ALLOC_BIT; next->preceding = newnode->size | (next->preceding & MM_ALLOC_BIT); } oldnode = newnode; oldsize = newnode->size; /* Now we have to move the user contents 'down' in memory. memcpy should * should be save for this. */ newmem = (FAR void*)((FAR char*)newnode + SIZEOF_MM_ALLOCNODE); memcpy(newmem, oldmem, oldsize - SIZEOF_MM_ALLOCNODE); } /* Extend into the next free chunk */ if (takenext) { FAR struct mm_freenode_s *newnode; FAR struct mm_allocnode_s *andbeyond; /* Get the chunk following the next node (which could be the tail * chunk) */ andbeyond = (FAR struct mm_allocnode_s*)((char*)next + nextsize); /* Remove the next node. There must be a predecessor, but there * may not be a successor node. */ DEBUGASSERT(next->blink); next->blink->flink = next->flink; if (next->flink) { next->flink->blink = next->blink; } /* Extend the node into the next chunk */ oldnode->size = oldsize + takenext; newnode = (FAR struct mm_freenode_s *)((char*)oldnode + oldnode->size); /* Did we consume the entire preceding chunk? */ if (takenext < nextsize) { /* No, take what we need from the next chunk and return it to * the free nodelist. */ newnode->size = nextsize - takenext; newnode->preceding = oldnode->size; andbeyond->preceding = newnode->size | (andbeyond->preceding & MM_ALLOC_BIT); /* Add the new free node to the nodelist (with the new size) */ mm_addfreechunk(heap, newnode); } else { /* Yes, just update some pointers. */ andbeyond->preceding = oldnode->size | (andbeyond->preceding & MM_ALLOC_BIT); } } mm_givesemaphore(heap); return newmem; } /* The current chunk cannot be extended. Just allocate a new chunk and copy */ else { /* Allocate a new block. On failure, realloc must return NULL but * leave the original memory in place. */ mm_givesemaphore(heap); newmem = (FAR void*)mm_malloc(heap, size); if (newmem) { memcpy(newmem, oldmem, oldsize); mm_free(heap, oldmem); } return newmem; } }
IUTInfoAix/terrarium_2015
nuttx/mm/mm_heap/mm_realloc.c
C
bsd-2-clause
11,301
import os import csv import pickle from indra.literature import id_lookup from indra.sources import trips, reach, index_cards from assembly_eval import have_file, run_assembly if __name__ == '__main__': pmc_ids = [s.strip() for s in open('pmcids.txt', 'rt').readlines()] # Load the REACH reading output with open('reach/reach_stmts_batch_4_eval.pkl') as f: reach_stmts = pickle.load(f) # Load the PMID to PMCID map pmcid_to_pmid = {} with open('pmc_batch_4_id_map.txt') as f: csvreader = csv.reader(f, delimiter='\t') for row in csvreader: pmcid_to_pmid[row[0]] = row[1] for pmcid in pmc_ids: print 'Processing %s...' % pmcid # Process TRIPS trips_fname = 'trips/' + pmcid + '.ekb' tp = trips.process_xml(open(trips_fname).read()) # Get REACH statements reach_stmts_for_pmcid = reach_stmts.get(pmcid_to_pmid[pmcid], []) if not reach_stmts_for_pmcid: print "No REACH statements for %s" % pmcid # Get NACTEM/ISI statements fname = 'nactem/' + pmcid + '.cards' if not os.path.exists(fname): nactem_stmts = [] else: icp = index_cards.process_json_file(fname, 'nactem') nactem_stmts = icp.statements # Combine all statements all_statements = tp.statements + reach_stmts_for_pmcid + nactem_stmts # Run assembly run_assembly(all_statements, 'combined', pmcid)
pvtodorov/indra
indra/benchmarks/assembly_eval/combine4/run_combined.py
Python
bsd-2-clause
1,490
/* ---------------------------------------------------------------------------- */ /* Atmel Microcontroller Software Support */ /* SAM Software Package License */ /* ---------------------------------------------------------------------------- */ /* Copyright (c) 2015, Atmel Corporation */ /* */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following condition is met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, */ /* this list of conditions and the disclaimer below. */ /* */ /* Atmel's name may not be used to endorse or promote products derived from */ /* this software without specific prior written permission. */ /* */ /* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR */ /* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE */ /* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */ /* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, */ /* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */ /* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING */ /* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, */ /* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* ---------------------------------------------------------------------------- */ #ifndef _SAM4C_MATRIX0_INSTANCE_ #define _SAM4C_MATRIX0_INSTANCE_ /* ========== Register definition for MATRIX0 peripheral ========== */ #if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_MATRIX0_MCFG (0x400E0200U) /**< \brief (MATRIX0) Master Configuration Register */ #define REG_MATRIX0_SCFG (0x400E0240U) /**< \brief (MATRIX0) Slave Configuration Register */ #define REG_MATRIX0_PRAS0 (0x400E0280U) /**< \brief (MATRIX0) Priority Register A for Slave 0 */ #define REG_MATRIX0_PRAS1 (0x400E0288U) /**< \brief (MATRIX0) Priority Register A for Slave 1 */ #define REG_MATRIX0_PRAS2 (0x400E0290U) /**< \brief (MATRIX0) Priority Register A for Slave 2 */ #define REG_MATRIX0_PRAS3 (0x400E0298U) /**< \brief (MATRIX0) Priority Register A for Slave 3 */ #define REG_MATRIX0_PRAS4 (0x400E02A0U) /**< \brief (MATRIX0) Priority Register A for Slave 4 */ #define REG_MATRIX0_PRAS5 (0x400E02A8U) /**< \brief (MATRIX0) Priority Register A for Slave 5 */ #define REG_MATRIX0_PRAS6 (0x400E02B0U) /**< \brief (MATRIX0) Priority Register A for Slave 6 */ #define REG_MATRIX0_PRAS7 (0x400E02B8U) /**< \brief (MATRIX0) Priority Register A for Slave 7 */ #define REG_MATRIX0_PRAS8 (0x400E02BCU) /**< \brief (MATRIX0) Priority Register A for Slave 8 */ #define REG_MATRIX0_SYSIO (0x400E0314U) /**< \brief (MATRIX0) System I/O Configuration Register */ #define REG_MATRIX0_SMCNFCS (0x400E031CU) /**< \brief (MATRIX0) SMC Nand Flash Chip Select Configuration Register */ #define REG_MATRIX0_CORE_DEBUG (0x400E0328U) /**< \brief (MATRIX0) Core Debug Configuration Register */ #define REG_MATRIX0_WPMR (0x400E03E4U) /**< \brief (MATRIX0) Write Protection Mode Register */ #define REG_MATRIX0_WPSR (0x400E03E8U) /**< \brief (MATRIX0) Write Protection Status Register */ #else #define REG_MATRIX0_MCFG (*(__IO uint32_t*)0x400E0200U) /**< \brief (MATRIX0) Master Configuration Register */ #define REG_MATRIX0_SCFG (*(__IO uint32_t*)0x400E0240U) /**< \brief (MATRIX0) Slave Configuration Register */ #define REG_MATRIX0_PRAS0 (*(__IO uint32_t*)0x400E0280U) /**< \brief (MATRIX0) Priority Register A for Slave 0 */ #define REG_MATRIX0_PRAS1 (*(__IO uint32_t*)0x400E0288U) /**< \brief (MATRIX0) Priority Register A for Slave 1 */ #define REG_MATRIX0_PRAS2 (*(__IO uint32_t*)0x400E0290U) /**< \brief (MATRIX0) Priority Register A for Slave 2 */ #define REG_MATRIX0_PRAS3 (*(__IO uint32_t*)0x400E0298U) /**< \brief (MATRIX0) Priority Register A for Slave 3 */ #define REG_MATRIX0_PRAS4 (*(__IO uint32_t*)0x400E02A0U) /**< \brief (MATRIX0) Priority Register A for Slave 4 */ #define REG_MATRIX0_PRAS5 (*(__IO uint32_t*)0x400E02A8U) /**< \brief (MATRIX0) Priority Register A for Slave 5 */ #define REG_MATRIX0_PRAS6 (*(__IO uint32_t*)0x400E02B0U) /**< \brief (MATRIX0) Priority Register A for Slave 6 */ #define REG_MATRIX0_PRAS7 (*(__IO uint32_t*)0x400E02B8U) /**< \brief (MATRIX0) Priority Register A for Slave 7 */ #define REG_MATRIX0_PRAS8 (*(__IO uint32_t*)0x400E02BCU) /**< \brief (MATRIX0) Priority Register A for Slave 8 */ #define REG_MATRIX0_SYSIO (*(__IO uint32_t*)0x400E0314U) /**< \brief (MATRIX0) System I/O Configuration Register */ #define REG_MATRIX0_SMCNFCS (*(__IO uint32_t*)0x400E031CU) /**< \brief (MATRIX0) SMC Nand Flash Chip Select Configuration Register */ #define REG_MATRIX0_CORE_DEBUG (*(__IO uint32_t*)0x400E0328U) /**< \brief (MATRIX0) Core Debug Configuration Register */ #define REG_MATRIX0_WPMR (*(__IO uint32_t*)0x400E03E4U) /**< \brief (MATRIX0) Write Protection Mode Register */ #define REG_MATRIX0_WPSR (*(__I uint32_t*)0x400E03E8U) /**< \brief (MATRIX0) Write Protection Status Register */ #endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ #endif /* _SAM4C_MATRIX0_INSTANCE_ */
AtmelUniversityFrance/SAM4E-XPRO
Examples/CMSIS/Device/ATMEL/sam4c32/include/instance/matrix0.h
C
bsd-2-clause
6,543
// // ColumnCanvasElement.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 4/12/13. // // #ifndef __G3MiOSSDK__ColumnCanvasElement__ #define __G3MiOSSDK__ColumnCanvasElement__ #include "GroupCanvasElement.hpp" #include "ICanvasUtils.hpp" class ColumnCanvasElement : public GroupCanvasElement { private: const HorizontalAlignment _elementAlign; protected: Vector2F* calculateExtent(ICanvas* canvas); public: ColumnCanvasElement(const Color& color = Color::transparent(), float margin = 0, float padding = 0, float cornerRadius = 0, const HorizontalAlignment elementAlign = Center) : GroupCanvasElement(color, margin, padding, cornerRadius), _elementAlign(elementAlign) { } virtual ~ColumnCanvasElement() { #ifdef JAVA_CODE super.dispose(); #endif } void rawDrawAt(float left, float top, const Vector2F& extent, ICanvas* canvas); }; #endif
AeroGlass/g3m
iOS/G3MiOSSDK/Commons/Basic/ColumnCanvasElement.hpp
C++
bsd-2-clause
1,017
/*- * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Rick Macklem at The University of Guelph. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)nfs_subs.c 8.8 (Berkeley) 5/22/95 */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: soc2013/dpl/head/sys/nfsserver/nfs_srvsubs.c 246812 2013-01-18 18:43:38Z jhb $"); /* * These functions support the macros and help fiddle mbuf chains for * the nfs op functions. They do things like create the rpc header and * copy data between mbuf chains and uio lists. */ #include "opt_inet6.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/bio.h> #include <sys/buf.h> #include <sys/proc.h> #include <sys/mount.h> #include <sys/vnode.h> #include <sys/namei.h> #include <sys/mbuf.h> #include <sys/refcount.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/malloc.h> #include <sys/module.h> #include <sys/sysent.h> #include <sys/syscall.h> #include <sys/sysproto.h> #include <vm/vm.h> #include <vm/vm_object.h> #include <vm/vm_extern.h> #include <vm/uma.h> #include <rpc/rpc.h> #include <nfs/nfsproto.h> #include <nfsserver/nfs.h> #include <nfs/xdr_subs.h> #include <nfsserver/nfsm_subs.h> #include <netinet/in.h> /* * Data items converted to xdr at startup, since they are constant * This is kinda hokey, but may save a little time doing byte swaps */ u_int32_t nfsrv_nfs_xdrneg1; u_int32_t nfsrv_nfs_true, nfsrv_nfs_false; /* And other global data */ static const nfstype nfsv2_type[9] = { NFNON, NFREG, NFDIR, NFBLK, NFCHR, NFLNK, NFNON, NFCHR, NFNON }; #define vtonfsv2_type(a) txdr_unsigned(nfsv2_type[((int32_t)(a))]) #define vtonfsv3_mode(m) txdr_unsigned((m) & ALLPERMS) int nfsrv_ticks; struct mtx nfsd_mtx; /* * Mapping of old NFS Version 2 RPC numbers to generic numbers. */ const int nfsrv_nfsv3_procid[NFS_NPROCS] = { NFSPROC_NULL, NFSPROC_GETATTR, NFSPROC_SETATTR, NFSPROC_NOOP, NFSPROC_LOOKUP, NFSPROC_READLINK, NFSPROC_READ, NFSPROC_NOOP, NFSPROC_WRITE, NFSPROC_CREATE, NFSPROC_REMOVE, NFSPROC_RENAME, NFSPROC_LINK, NFSPROC_SYMLINK, NFSPROC_MKDIR, NFSPROC_RMDIR, NFSPROC_READDIR, NFSPROC_FSSTAT, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, NFSPROC_NOOP, }; /* * and the reverse mapping from generic to Version 2 procedure numbers */ const int nfsrvv2_procid[NFS_NPROCS] = { NFSV2PROC_NULL, NFSV2PROC_GETATTR, NFSV2PROC_SETATTR, NFSV2PROC_LOOKUP, NFSV2PROC_NOOP, NFSV2PROC_READLINK, NFSV2PROC_READ, NFSV2PROC_WRITE, NFSV2PROC_CREATE, NFSV2PROC_MKDIR, NFSV2PROC_SYMLINK, NFSV2PROC_CREATE, NFSV2PROC_REMOVE, NFSV2PROC_RMDIR, NFSV2PROC_RENAME, NFSV2PROC_LINK, NFSV2PROC_READDIR, NFSV2PROC_NOOP, NFSV2PROC_STATFS, NFSV2PROC_NOOP, NFSV2PROC_NOOP, NFSV2PROC_NOOP, NFSV2PROC_NOOP, }; /* * Maps errno values to nfs error numbers. * Use 0 (which gets converted to NFSERR_IO) as the catch all for ones not * specifically defined in RFC 1094. */ static const u_char nfsrv_v2errmap[ELAST] = { NFSERR_PERM, NFSERR_NOENT, 0, 0, 0, NFSERR_NXIO, 0, 0, 0, 0, 0, 0, NFSERR_ACCES, 0, 0, 0, NFSERR_EXIST, 0, NFSERR_NODEV, NFSERR_NOTDIR, NFSERR_ISDIR, 0, 0, 0, 0, 0, NFSERR_FBIG, NFSERR_NOSPC, 0, NFSERR_ROFS, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NFSERR_NAMETOL, 0, 0, NFSERR_NOTEMPTY, 0, 0, NFSERR_DQUOT, NFSERR_STALE, 0 }; /* * Maps errno values to nfs error numbers. * Although it is not obvious whether or not NFS clients really care if * a returned error value is in the specified list for the procedure, the * safest thing to do is filter them appropriately. For Version 2, the * X/Open XNFS document is the only specification that defines error values * for each RPC (The RFC simply lists all possible error values for all RPCs), * so I have decided to not do this for Version 2. * The first entry is the default error return and the rest are the valid * errors for that RPC in increasing numeric order. */ static const short nfsv3err_null[] = { 0, 0, }; static const short nfsv3err_getattr[] = { NFSERR_IO, NFSERR_IO, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_setattr[] = { NFSERR_IO, NFSERR_PERM, NFSERR_IO, NFSERR_ACCES, NFSERR_INVAL, NFSERR_NOSPC, NFSERR_ROFS, NFSERR_DQUOT, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOT_SYNC, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_lookup[] = { NFSERR_IO, NFSERR_NOENT, NFSERR_IO, NFSERR_ACCES, NFSERR_NOTDIR, NFSERR_NAMETOL, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_access[] = { NFSERR_IO, NFSERR_IO, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_readlink[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_INVAL, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOTSUPP, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_read[] = { NFSERR_IO, NFSERR_IO, NFSERR_NXIO, NFSERR_ACCES, NFSERR_INVAL, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_write[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_INVAL, NFSERR_FBIG, NFSERR_NOSPC, NFSERR_ROFS, NFSERR_DQUOT, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_create[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_EXIST, NFSERR_NOTDIR, NFSERR_NOSPC, NFSERR_ROFS, NFSERR_NAMETOL, NFSERR_DQUOT, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOTSUPP, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_mkdir[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_EXIST, NFSERR_NOTDIR, NFSERR_NOSPC, NFSERR_ROFS, NFSERR_NAMETOL, NFSERR_DQUOT, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOTSUPP, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_symlink[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_EXIST, NFSERR_NOTDIR, NFSERR_NOSPC, NFSERR_ROFS, NFSERR_NAMETOL, NFSERR_DQUOT, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOTSUPP, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_mknod[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_EXIST, NFSERR_NOTDIR, NFSERR_NOSPC, NFSERR_ROFS, NFSERR_NAMETOL, NFSERR_DQUOT, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOTSUPP, NFSERR_SERVERFAULT, NFSERR_BADTYPE, 0, }; static const short nfsv3err_remove[] = { NFSERR_IO, NFSERR_NOENT, NFSERR_IO, NFSERR_ACCES, NFSERR_NOTDIR, NFSERR_ROFS, NFSERR_NAMETOL, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_rmdir[] = { NFSERR_IO, NFSERR_NOENT, NFSERR_IO, NFSERR_ACCES, NFSERR_EXIST, NFSERR_NOTDIR, NFSERR_INVAL, NFSERR_ROFS, NFSERR_NAMETOL, NFSERR_NOTEMPTY, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOTSUPP, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_rename[] = { NFSERR_IO, NFSERR_NOENT, NFSERR_IO, NFSERR_ACCES, NFSERR_EXIST, NFSERR_XDEV, NFSERR_NOTDIR, NFSERR_ISDIR, NFSERR_INVAL, NFSERR_NOSPC, NFSERR_ROFS, NFSERR_MLINK, NFSERR_NAMETOL, NFSERR_NOTEMPTY, NFSERR_DQUOT, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOTSUPP, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_link[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_EXIST, NFSERR_XDEV, NFSERR_NOTDIR, NFSERR_INVAL, NFSERR_NOSPC, NFSERR_ROFS, NFSERR_MLINK, NFSERR_NAMETOL, NFSERR_DQUOT, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_NOTSUPP, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_readdir[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_NOTDIR, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_BAD_COOKIE, NFSERR_TOOSMALL, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_readdirplus[] = { NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_NOTDIR, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_BAD_COOKIE, NFSERR_NOTSUPP, NFSERR_TOOSMALL, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_fsstat[] = { NFSERR_IO, NFSERR_IO, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_fsinfo[] = { NFSERR_STALE, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_pathconf[] = { NFSERR_STALE, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short nfsv3err_commit[] = { NFSERR_IO, NFSERR_IO, NFSERR_STALE, NFSERR_BADHANDLE, NFSERR_SERVERFAULT, 0, }; static const short *nfsrv_v3errmap[] = { nfsv3err_null, nfsv3err_getattr, nfsv3err_setattr, nfsv3err_lookup, nfsv3err_access, nfsv3err_readlink, nfsv3err_read, nfsv3err_write, nfsv3err_create, nfsv3err_mkdir, nfsv3err_symlink, nfsv3err_mknod, nfsv3err_remove, nfsv3err_rmdir, nfsv3err_rename, nfsv3err_link, nfsv3err_readdir, nfsv3err_readdirplus, nfsv3err_fsstat, nfsv3err_fsinfo, nfsv3err_pathconf, nfsv3err_commit, }; extern int (*nfsd_call_nfsserver)(struct thread *, struct nfssvc_args *); /* * Called once to initialize data structures... */ static int nfsrv_modevent(module_t mod, int type, void *data) { int error = 0; switch (type) { case MOD_LOAD: mtx_init(&nfsd_mtx, "nfsd_mtx", NULL, MTX_DEF); nfsrv_nfs_true = txdr_unsigned(TRUE); nfsrv_nfs_false = txdr_unsigned(FALSE); nfsrv_nfs_xdrneg1 = txdr_unsigned(-1); nfsrv_ticks = (hz * NFS_TICKINTVL + 500) / 1000; if (nfsrv_ticks < 1) nfsrv_ticks = 1; NFSD_LOCK(); nfsrv_init(0); /* Init server data structures */ NFSD_UNLOCK(); nfsd_call_nfsserver = nfssvc_nfsserver; break; case MOD_UNLOAD: if (nfsrv_numnfsd != 0) { error = EBUSY; break; } nfsd_call_nfsserver = NULL; callout_drain(&nfsrv_callout); mtx_destroy(&nfsd_mtx); break; default: error = EOPNOTSUPP; break; } return error; } static moduledata_t nfsserver_mod = { "nfsserver", nfsrv_modevent, NULL, }; DECLARE_MODULE(nfsserver, nfsserver_mod, SI_SUB_VFS, SI_ORDER_ANY); /* So that loader and kldload(2) can find us, wherever we are.. */ MODULE_VERSION(nfsserver, 1); MODULE_DEPEND(nfsserver, nfssvc, 1, 1, 1); MODULE_DEPEND(nfsserver, krpc, 1, 1, 1); MODULE_DEPEND(nfsserver, nfs_common, 1, 1, 1); /* * Set up nameidata for a lookup() call and do it. * * If pubflag is set, this call is done for a lookup operation on the * public filehandle. In that case we allow crossing mountpoints and * absolute pathnames. However, the caller is expected to check that * the lookup result is within the public fs, and deny access if * it is not. * * nfs_namei() clears out garbage fields that namei() might leave garbage. * This is mainly ni_vp and ni_dvp when an error occurs, and ni_dvp when no * error occurs but the parent was not requested. * * dirp may be set whether an error is returned or not, and must be * released by the caller. */ int nfs_namei(struct nameidata *ndp, struct nfsrv_descript *nfsd, fhandle_t *fhp, int len, struct nfssvc_sock *slp, struct sockaddr *nam, struct mbuf **mdp, caddr_t *dposp, struct vnode **retdirp, int v3, struct vattr *retdirattrp, int *retdirattr_retp, int pubflag) { int i, rem; struct mbuf *md; char *fromcp, *tocp, *cp; struct iovec aiov; struct uio auio; struct vnode *dp; int error, rdonly, linklen; struct componentname *cnp = &ndp->ni_cnd; int lockleaf = (cnp->cn_flags & LOCKLEAF) != 0; *retdirp = NULL; cnp->cn_flags |= NOMACCHECK; cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK); /* * Copy the name from the mbuf list to ndp->ni_pnbuf * and set the various ndp fields appropriately. */ fromcp = *dposp; tocp = cnp->cn_pnbuf; md = *mdp; rem = mtod(md, caddr_t) + md->m_len - fromcp; for (i = 0; i < len; i++) { while (rem == 0) { md = md->m_next; if (md == NULL) { error = EBADRPC; goto out; } fromcp = mtod(md, caddr_t); rem = md->m_len; } if (*fromcp == '\0' || (!pubflag && *fromcp == '/')) { error = EACCES; goto out; } *tocp++ = *fromcp++; rem--; } *tocp = '\0'; *mdp = md; *dposp = fromcp; len = nfsm_rndup(len)-len; if (len > 0) { if (rem >= len) *dposp += len; else if ((error = nfs_adv(mdp, dposp, len, rem)) != 0) goto out; } if (!pubflag && nfs_ispublicfh(fhp)) return (ESTALE); /* * Extract and set starting directory. */ error = nfsrv_fhtovp(fhp, 0, &dp, nfsd, slp, nam, &rdonly); if (error) goto out; if (dp->v_type != VDIR) { vput(dp); error = ENOTDIR; goto out; } if (rdonly) cnp->cn_flags |= RDONLY; /* * Set return directory. Reference to dp is implicitly transfered * to the returned pointer */ *retdirp = dp; if (v3) { *retdirattr_retp = VOP_GETATTR(dp, retdirattrp, ndp->ni_cnd.cn_cred); } VOP_UNLOCK(dp, 0); if (pubflag) { /* * Oh joy. For WebNFS, handle those pesky '%' escapes, * and the 'native path' indicator. */ cp = uma_zalloc(namei_zone, M_WAITOK); fromcp = cnp->cn_pnbuf; tocp = cp; if ((unsigned char)*fromcp >= WEBNFS_SPECCHAR_START) { switch ((unsigned char)*fromcp) { case WEBNFS_NATIVE_CHAR: /* * 'Native' path for us is the same * as a path according to the NFS spec, * just skip the escape char. */ fromcp++; break; /* * More may be added in the future, range 0x80-0xff */ default: error = EIO; uma_zfree(namei_zone, cp); goto out; } } /* * Translate the '%' escapes, URL-style. */ while (*fromcp != '\0') { if (*fromcp == WEBNFS_ESC_CHAR) { if (fromcp[1] != '\0' && fromcp[2] != '\0') { fromcp++; *tocp++ = HEXSTRTOI(fromcp); fromcp += 2; continue; } else { error = ENOENT; uma_zfree(namei_zone, cp); goto out; } } else *tocp++ = *fromcp++; } *tocp = '\0'; uma_zfree(namei_zone, cnp->cn_pnbuf); cnp->cn_pnbuf = cp; } ndp->ni_pathlen = (tocp - cnp->cn_pnbuf) + 1; ndp->ni_segflg = UIO_SYSSPACE; if (pubflag) { ndp->ni_rootdir = rootvnode; ndp->ni_loopcnt = 0; if (cnp->cn_pnbuf[0] == '/') dp = rootvnode; } else { cnp->cn_flags |= NOCROSSMOUNT; } /* * Initialize for scan, set ni_startdir and bump ref on dp again * because lookup() will dereference ni_startdir. */ cnp->cn_thread = curthread; VREF(dp); ndp->ni_startdir = dp; if (!lockleaf) cnp->cn_flags |= LOCKLEAF; for (;;) { cnp->cn_nameptr = cnp->cn_pnbuf; /* * Call lookup() to do the real work. If an error occurs, * ndp->ni_vp and ni_dvp are left uninitialized or NULL and * we do not have to dereference anything before returning. * In either case ni_startdir will be dereferenced and NULLed * out. */ error = lookup(ndp); if (error) break; /* * Check for encountering a symbolic link. Trivial * termination occurs if no symlink encountered. * Note: zfree is safe because error is 0, so we will * not zfree it again when we break. */ if ((cnp->cn_flags & ISSYMLINK) == 0) { if (cnp->cn_flags & (SAVENAME | SAVESTART)) cnp->cn_flags |= HASBUF; else uma_zfree(namei_zone, cnp->cn_pnbuf); if (ndp->ni_vp && !lockleaf) VOP_UNLOCK(ndp->ni_vp, 0); break; } /* * Validate symlink */ if ((cnp->cn_flags & LOCKPARENT) && ndp->ni_pathlen == 1) VOP_UNLOCK(ndp->ni_dvp, 0); if (!pubflag) { error = EINVAL; goto badlink2; } if (ndp->ni_loopcnt++ >= MAXSYMLINKS) { error = ELOOP; goto badlink2; } if (ndp->ni_pathlen > 1) cp = uma_zalloc(namei_zone, M_WAITOK); else cp = cnp->cn_pnbuf; aiov.iov_base = cp; aiov.iov_len = MAXPATHLEN; auio.uio_iov = &aiov; auio.uio_iovcnt = 1; auio.uio_offset = 0; auio.uio_rw = UIO_READ; auio.uio_segflg = UIO_SYSSPACE; auio.uio_td = NULL; auio.uio_resid = MAXPATHLEN; error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred); if (error) { badlink1: if (ndp->ni_pathlen > 1) uma_zfree(namei_zone, cp); badlink2: vput(ndp->ni_vp); vrele(ndp->ni_dvp); break; } linklen = MAXPATHLEN - auio.uio_resid; if (linklen == 0) { error = ENOENT; goto badlink1; } if (linklen + ndp->ni_pathlen >= MAXPATHLEN) { error = ENAMETOOLONG; goto badlink1; } /* * Adjust or replace path */ if (ndp->ni_pathlen > 1) { bcopy(ndp->ni_next, cp + linklen, ndp->ni_pathlen); uma_zfree(namei_zone, cnp->cn_pnbuf); cnp->cn_pnbuf = cp; } else cnp->cn_pnbuf[linklen] = '\0'; ndp->ni_pathlen += linklen; /* * Cleanup refs for next loop and check if root directory * should replace current directory. Normally ni_dvp * becomes the new base directory and is cleaned up when * we loop. Explicitly null pointers after invalidation * to clarify operation. */ vput(ndp->ni_vp); ndp->ni_vp = NULL; if (cnp->cn_pnbuf[0] == '/') { vrele(ndp->ni_dvp); ndp->ni_dvp = ndp->ni_rootdir; VREF(ndp->ni_dvp); } ndp->ni_startdir = ndp->ni_dvp; ndp->ni_dvp = NULL; } if (!lockleaf) cnp->cn_flags &= ~LOCKLEAF; /* * nfs_namei() guarentees that fields will not contain garbage * whether an error occurs or not. This allows the caller to track * cleanup state trivially. */ out: if (error) { uma_zfree(namei_zone, cnp->cn_pnbuf); ndp->ni_vp = NULL; ndp->ni_dvp = NULL; ndp->ni_startdir = NULL; cnp->cn_flags &= ~HASBUF; } else if ((ndp->ni_cnd.cn_flags & (WANTPARENT|LOCKPARENT)) == 0) { ndp->ni_dvp = NULL; } return (error); } /* * A fiddled version of m_adj() that ensures null fill to a long * boundary and only trims off the back end */ void nfsm_adj(struct mbuf *mp, int len, int nul) { struct mbuf *m; int count, i; char *cp; /* * Trim from tail. Scan the mbuf chain, * calculating its length and finding the last mbuf. * If the adjustment only affects this mbuf, then just * adjust and return. Otherwise, rescan and truncate * after the remaining size. */ count = 0; m = mp; for (;;) { count += m->m_len; if (m->m_next == NULL) break; m = m->m_next; } if (m->m_len > len) { m->m_len -= len; if (nul > 0) { cp = mtod(m, caddr_t)+m->m_len-nul; for (i = 0; i < nul; i++) *cp++ = '\0'; } return; } count -= len; if (count < 0) count = 0; /* * Correct length for chain is "count". * Find the mbuf with last data, adjust its length, * and toss data from remaining mbufs on chain. */ for (m = mp; m; m = m->m_next) { if (m->m_len >= count) { m->m_len = count; if (nul > 0) { cp = mtod(m, caddr_t)+m->m_len-nul; for (i = 0; i < nul; i++) *cp++ = '\0'; } if (m->m_next != NULL) { m_freem(m->m_next); m->m_next = NULL; } break; } count -= m->m_len; } } /* * Make these functions instead of macros, so that the kernel text size * doesn't get too big... */ void nfsm_srvwcc(struct nfsrv_descript *nfsd, int before_ret, struct vattr *before_vap, int after_ret, struct vattr *after_vap, struct mbuf **mbp, char **bposp) { struct mbuf *mb = *mbp; char *bpos = *bposp; u_int32_t *tl; if (before_ret) { tl = nfsm_build(u_int32_t *, NFSX_UNSIGNED); *tl = nfsrv_nfs_false; } else { tl = nfsm_build(u_int32_t *, 7 * NFSX_UNSIGNED); *tl++ = nfsrv_nfs_true; txdr_hyper(before_vap->va_size, tl); tl += 2; txdr_nfsv3time(&(before_vap->va_mtime), tl); tl += 2; txdr_nfsv3time(&(before_vap->va_ctime), tl); } *bposp = bpos; *mbp = mb; nfsm_srvpostopattr(nfsd, after_ret, after_vap, mbp, bposp); } void nfsm_srvpostopattr(struct nfsrv_descript *nfsd, int after_ret, struct vattr *after_vap, struct mbuf **mbp, char **bposp) { struct mbuf *mb = *mbp; char *bpos = *bposp; u_int32_t *tl; struct nfs_fattr *fp; if (after_ret) { tl = nfsm_build(u_int32_t *, NFSX_UNSIGNED); *tl = nfsrv_nfs_false; } else { tl = nfsm_build(u_int32_t *, NFSX_UNSIGNED + NFSX_V3FATTR); *tl++ = nfsrv_nfs_true; fp = (struct nfs_fattr *)tl; nfsm_srvfattr(nfsd, after_vap, fp); } *mbp = mb; *bposp = bpos; } void nfsm_srvfattr(struct nfsrv_descript *nfsd, struct vattr *vap, struct nfs_fattr *fp) { fp->fa_nlink = txdr_unsigned(vap->va_nlink); fp->fa_uid = txdr_unsigned(vap->va_uid); fp->fa_gid = txdr_unsigned(vap->va_gid); if (nfsd->nd_flag & ND_NFSV3) { fp->fa_type = vtonfsv3_type(vap->va_type); fp->fa_mode = vtonfsv3_mode(vap->va_mode); txdr_hyper(vap->va_size, &fp->fa3_size); txdr_hyper(vap->va_bytes, &fp->fa3_used); fp->fa3_rdev.specdata1 = txdr_unsigned(major(vap->va_rdev)); fp->fa3_rdev.specdata2 = txdr_unsigned(minor(vap->va_rdev)); fp->fa3_fsid.nfsuquad[0] = 0; fp->fa3_fsid.nfsuquad[1] = txdr_unsigned(vap->va_fsid); fp->fa3_fileid.nfsuquad[0] = 0; fp->fa3_fileid.nfsuquad[1] = txdr_unsigned(vap->va_fileid); txdr_nfsv3time(&vap->va_atime, &fp->fa3_atime); txdr_nfsv3time(&vap->va_mtime, &fp->fa3_mtime); txdr_nfsv3time(&vap->va_ctime, &fp->fa3_ctime); } else { fp->fa_type = vtonfsv2_type(vap->va_type); fp->fa_mode = vtonfsv2_mode(vap->va_type, vap->va_mode); fp->fa2_size = txdr_unsigned(vap->va_size); fp->fa2_blocksize = txdr_unsigned(vap->va_blocksize); if (vap->va_type == VFIFO) fp->fa2_rdev = 0xffffffff; else fp->fa2_rdev = txdr_unsigned(vap->va_rdev); fp->fa2_blocks = txdr_unsigned(vap->va_bytes / NFS_FABLKSIZE); fp->fa2_fsid = txdr_unsigned(vap->va_fsid); fp->fa2_fileid = txdr_unsigned(vap->va_fileid); txdr_nfsv2time(&vap->va_atime, &fp->fa2_atime); txdr_nfsv2time(&vap->va_mtime, &fp->fa2_mtime); txdr_nfsv2time(&vap->va_ctime, &fp->fa2_ctime); } } /* * nfsrv_fhtovp() - convert a fh to a vnode ptr (optionally locked) * - look up fsid in mount list (if not found ret error) * - get vp and export rights by calling VFS_FHTOVP() * - if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon */ int nfsrv_fhtovp(fhandle_t *fhp, int flags, struct vnode **vpp, struct nfsrv_descript *nfsd, struct nfssvc_sock *slp, struct sockaddr *nam, int *rdonlyp) { struct mount *mp; int i; struct ucred *cred, *credanon; int error, exflags; #ifdef MNT_EXNORESPORT /* XXX needs mountd and /etc/exports help yet */ struct sockaddr_int *saddr; #endif int credflavor; int numsecflavors, *secflavors; int authsys; int v3 = nfsd->nd_flag & ND_NFSV3; int mountreq; *vpp = NULL; if (nfs_ispublicfh(fhp)) { if (!nfs_pub.np_valid) return (ESTALE); fhp = &nfs_pub.np_handle; } mp = vfs_busyfs(&fhp->fh_fsid); if (!mp) return (ESTALE); error = VFS_CHECKEXP(mp, nam, &exflags, &credanon, &numsecflavors, &secflavors); if (error) { vfs_unbusy(mp); goto out; } if (numsecflavors == 0) { /* * This can happen if the system is running with an * old mountd that doesn't pass in a secflavor list. */ numsecflavors = 1; authsys = AUTH_SYS; secflavors = &authsys; } credflavor = nfsd->nd_credflavor; for (i = 0; i < numsecflavors; i++) { if (secflavors[i] == credflavor) break; } if (i == numsecflavors) { /* * RFC 2623 section 2.3.2 - allow certain procedures * used at NFS client mount time even if they have * weak authentication. */ mountreq = FALSE; if (v3) { if (nfsd->nd_procnum == NFSPROC_FSINFO || nfsd->nd_procnum == NFSPROC_GETATTR) mountreq = TRUE; } else { if (nfsd->nd_procnum == NFSPROC_FSSTAT || nfsd->nd_procnum == NFSPROC_GETATTR) mountreq = TRUE; } if (!mountreq) { error = NFSERR_AUTHERR | AUTH_TOOWEAK; vfs_unbusy(mp); goto out; } } error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, vpp); if (error) { /* Make sure the server replies ESTALE to the client. */ error = ESTALE; vfs_unbusy(mp); goto out; } #ifdef MNT_EXNORESPORT if (!(exflags & (MNT_EXNORESPORT|MNT_EXPUBLIC))) { saddr = (struct sockaddr_in *)nam; if ((saddr->sin_family == AF_INET || saddr->sin_family == AF_INET6) && /* same code for INET and INET6: sin*_port at same offet */ ntohs(saddr->sin_port) >= IPPORT_RESERVED) { vput(*vpp); *vpp = NULL; error = NFSERR_AUTHERR | AUTH_TOOWEAK; vfs_unbusy(mp); goto out; } } #endif /* * Check/setup credentials. */ cred = nfsd->nd_cr; if (cred->cr_uid == 0 || (exflags & MNT_EXPORTANON)) { cred->cr_uid = credanon->cr_uid; crsetgroups(cred, credanon->cr_ngroups, credanon->cr_groups); } if (exflags & MNT_EXRDONLY) *rdonlyp = 1; else *rdonlyp = 0; if (!(flags & NFSRV_FLAG_BUSY)) vfs_unbusy(mp); out: if (credanon != NULL) crfree(credanon); return (error); } /* * WebNFS: check if a filehandle is a public filehandle. For v3, this * means a length of 0, for v2 it means all zeroes. nfsm_srvmtofh has * transformed this to all zeroes in both cases, so check for it. */ int nfs_ispublicfh(fhandle_t *fhp) { char *cp = (char *)fhp; int i; NFSD_LOCK_DONTCARE(); for (i = 0; i < NFSX_V3FH; i++) if (*cp++ != 0) return (FALSE); return (TRUE); } /* * Map errnos to NFS error numbers. For Version 3 also filter out error * numbers not specified for the associated procedure. */ int nfsrv_errmap(struct nfsrv_descript *nd, int err) { const short *defaulterrp, *errp; int e; if (nd->nd_flag & ND_NFSV3) { if (nd->nd_procnum <= NFSPROC_COMMIT) { errp = defaulterrp = nfsrv_v3errmap[nd->nd_procnum]; while (*++errp) { if (*errp == err) return (err); else if (*errp > err) break; } return ((int)*defaulterrp); } else return (err & 0xffff); } e = 0; if (err <= ELAST) e = nfsrv_v2errmap[err - 1]; if (e != 0) return (e); return (NFSERR_IO); } /* * Sort the group list in increasing numerical order. * (Insertion sort by Chris Torek, who was grossed out by the bubble sort * that used to be here.) */ void nfsrvw_sort(gid_t *list, int num) { int i, j; gid_t v; /* Insertion sort. */ for (i = 1; i < num; i++) { v = list[i]; /* find correct slot for value v, moving others up */ for (j = i; --j >= 0 && v < list[j];) list[j + 1] = list[j]; list[j + 1] = v; } } /* * Helper functions for macros. */ void nfsm_srvfhtom_xx(fhandle_t *f, int v3, struct mbuf **mb, caddr_t *bpos) { u_int32_t *tl; if (v3) { tl = nfsm_build_xx(NFSX_UNSIGNED + NFSX_V3FH, mb, bpos); *tl++ = txdr_unsigned(NFSX_V3FH); bcopy(f, tl, NFSX_V3FH); } else { tl = nfsm_build_xx(NFSX_V2FH, mb, bpos); bcopy(f, tl, NFSX_V2FH); } } void nfsm_srvpostop_fh_xx(fhandle_t *f, struct mbuf **mb, caddr_t *bpos) { u_int32_t *tl; tl = nfsm_build_xx(2 * NFSX_UNSIGNED + NFSX_V3FH, mb, bpos); *tl++ = nfsrv_nfs_true; *tl++ = txdr_unsigned(NFSX_V3FH); bcopy(f, tl, NFSX_V3FH); } int nfsm_srvstrsiz_xx(int *s, int m, struct mbuf **md, caddr_t *dpos) { u_int32_t *tl; tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; *s = fxdr_unsigned(int32_t, *tl); if (*s > m || *s <= 0) return EBADRPC; return 0; } int nfsm_srvnamesiz_xx(int *s, int m, struct mbuf **md, caddr_t *dpos) { u_int32_t *tl; NFSD_LOCK_DONTCARE(); tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; *s = fxdr_unsigned(int32_t, *tl); if (*s > m) return NFSERR_NAMETOL; if (*s <= 0) return EBADRPC; return 0; } int nfsm_srvnamesiz0_xx(int *s, int m, struct mbuf **md, caddr_t *dpos) { u_int32_t *tl; tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; *s = fxdr_unsigned(int32_t, *tl); if (*s > m) return NFSERR_NAMETOL; if (*s < 0) return EBADRPC; return 0; } void nfsm_clget_xx(u_int32_t **tl, struct mbuf *mb, struct mbuf **mp, char **bp, char **be, caddr_t bpos) { struct mbuf *nmp; NFSD_UNLOCK_ASSERT(); if (*bp >= *be) { if (*mp == mb) (*mp)->m_len += *bp - bpos; MGET(nmp, M_WAITOK, MT_DATA); MCLGET(nmp, M_WAITOK); nmp->m_len = NFSMSIZ(nmp); (*mp)->m_next = nmp; *mp = nmp; *bp = mtod(*mp, caddr_t); *be = *bp + (*mp)->m_len; } *tl = (u_int32_t *)*bp; } int nfsm_srvmtofh_xx(fhandle_t *f, int v3, struct mbuf **md, caddr_t *dpos) { u_int32_t *tl; int fhlen; if (v3) { tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; fhlen = fxdr_unsigned(int, *tl); if (fhlen != 0 && fhlen != NFSX_V3FH) return EBADRPC; } else { fhlen = NFSX_V2FH; } if (fhlen != 0) { tl = nfsm_dissect_xx_nonblock(fhlen, md, dpos); if (tl == NULL) return EBADRPC; bcopy((caddr_t)tl, (caddr_t)(f), fhlen); } else { bzero((caddr_t)(f), NFSX_V3FH); } return 0; } int nfsm_srvsattr_xx(struct vattr *a, struct mbuf **md, caddr_t *dpos) { u_int32_t *tl; int toclient = 0; tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; if (*tl == nfsrv_nfs_true) { tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; (a)->va_mode = nfstov_mode(*tl); } tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; if (*tl == nfsrv_nfs_true) { tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; (a)->va_uid = fxdr_unsigned(uid_t, *tl); } tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; if (*tl == nfsrv_nfs_true) { tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; (a)->va_gid = fxdr_unsigned(gid_t, *tl); } tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; if (*tl == nfsrv_nfs_true) { tl = nfsm_dissect_xx_nonblock(2 * NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; (a)->va_size = fxdr_hyper(tl); } tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; switch (fxdr_unsigned(int, *tl)) { case NFSV3SATTRTIME_TOCLIENT: tl = nfsm_dissect_xx_nonblock(2 * NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; fxdr_nfsv3time(tl, &(a)->va_atime); toclient = 1; break; case NFSV3SATTRTIME_TOSERVER: vfs_timestamp(&a->va_atime); a->va_vaflags |= VA_UTIMES_NULL; break; } tl = nfsm_dissect_xx_nonblock(NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; switch (fxdr_unsigned(int, *tl)) { case NFSV3SATTRTIME_TOCLIENT: tl = nfsm_dissect_xx_nonblock(2 * NFSX_UNSIGNED, md, dpos); if (tl == NULL) return EBADRPC; fxdr_nfsv3time(tl, &(a)->va_mtime); a->va_vaflags &= ~VA_UTIMES_NULL; break; case NFSV3SATTRTIME_TOSERVER: vfs_timestamp(&a->va_mtime); if (toclient == 0) a->va_vaflags |= VA_UTIMES_NULL; break; } return 0; }
dplbsd/soc2013
head/sys/nfsserver/nfs_srvsubs.c
C
bsd-2-clause
31,853
from django import template from django.template.defaultfilters import stringfilter register = template.Library() STATUS_COLORS = { 'default': 'blue', 'queued': 'blue', 'undetermined': 'blue', 'infected': 'red', 'uninfected': 'green', 'deposited': 'blue', 'rejected': 'red', 'accepted': 'green', 'valid': 'green', 'invalid': 'red', 'undefined': 'blue' } BOX_COLORS = { 'blue': 'primary', 'red': 'danger', 'green': 'success', 'grey': 'default' } @register.filter @stringfilter def status_color(status): """ This method will return grey for a unkown status. """ return STATUS_COLORS.get(status, 'grey') @register.filter def box_color(status): """ This method will return grey for a unkown status. """ return BOX_COLORS.get(STATUS_COLORS.get(status, 'grey'), 'default') @register.filter def status_sps(status): """ This method will return valid, invalid or undefined for a given result of models.PackageMember.sps_validation_status(). status: Tuple(None, {}) status: Tuple(True, {'is_valid': True, 'sps_errors': [], 'dtd_errors': []}) status: Tuple(False, {'is_valid': True, 'sps_errors': [], 'dtd_errors': []}) """ if status[0] is True: return 'valid' if status[0] is False: return 'invalid' return 'undefined' @register.filter def widget_scielops_colors_weight(xmls): """ This method will return a color for the SciELO PS widget. The color will be matched according to the error level of any of the members of the package. status: Dict with xml's returned by models.Package.xmls(). """ if len(xmls['invalid']) > 0: return STATUS_COLORS['invalid'] if len(xmls['undefined']) > 0: return STATUS_COLORS['undefined'] if len(xmls['valid']) == 0: return STATUS_COLORS['undefined'] return STATUS_COLORS['valid']
gustavofonseca/penne-core
frontdesk/templatetags/frontdesk.py
Python
bsd-2-clause
1,931
template <> class TypeInfoOf<OptName>: public TypeInfo { static constexpr UUID uuid() { return UUID(); } public: TypeInfoOf() : TypeInfo("OptName", uuid(), false, false, false, sbTokenEq, 0) {} static const TypeInfoOf<OptName>* const instance() { return &RawType<OptName>::rawType; } static Type type() { return Type(instance()); } atom_t getTypeAtom(VM vm) const { return OptName::getTypeAtom(vm); } inline void printReprToStream(VM vm, RichNode self, std::ostream& out, int depth, int width) const; inline GlobalNode* globalize(VM vm, RichNode from) const; inline void gCollect(GC gc, RichNode from, StableNode& to) const; inline void gCollect(GC gc, RichNode from, UnstableNode& to) const; inline void sClone(SC sc, RichNode from, StableNode& to) const; inline void sClone(SC sc, RichNode from, UnstableNode& to) const; }; template <> class TypedRichNode<OptName>: public BaseTypedRichNode { public: explicit TypedRichNode(RichNode self) : BaseTypedRichNode(self) {} inline class mozart::Space * home(); inline bool isLiteral(VM vm); inline bool lookupFeature(VM vm, class mozart::RichNode feature, nullable<class mozart::UnstableNode &> value); inline bool lookupFeature(VM vm, nativeint feature, nullable<class mozart::UnstableNode &> value); inline bool isRecord(VM vm); inline bool isTuple(VM vm); inline class mozart::UnstableNode label(VM vm); inline size_t width(VM vm); inline class mozart::UnstableNode arityList(VM vm); inline class mozart::UnstableNode clone(VM vm); inline class mozart::UnstableNode waitOr(VM vm); inline bool testRecord(VM vm, class mozart::RichNode arity); inline bool testTuple(VM vm, class mozart::RichNode label, size_t width); inline bool testLabel(VM vm, class mozart::RichNode label); inline void makeFeature(VM vm); inline bool isName(VM vm); inline class mozart::GlobalNode * globalize(VM vm); inline void printReprToStream(VM vm, std::ostream & out, int depth, int width); };
mozart/mozart2
vm/vm/main/cached/OptName-implem-decl-after.hh
C++
bsd-2-clause
2,105
;Testname=test; Arguments=-O0 -fbin -opinsr16.bin; Files=stdout stderr pinsr16.bin bits 16 pinsrw mm0,eax,0 pinsrw mm1,si,0 pinsrw mm2,[bx],0 pinsrw mm3,word [bx],0 pinsrb xmm0,eax,0 pinsrb xmm1,sil,0 ; pinsrb xmm1,bh,0 pinsrb xmm2,[bx],0 pinsrb xmm3,byte [bx],0 pinsrw xmm0,eax,0 pinsrw xmm1,si,0 pinsrw xmm2,[bx],0 pinsrw xmm3,word [bx],0 pinsrd xmm0,eax,0 pinsrd xmm1,esi,0 pinsrd xmm2,[bx],0 pinsrd xmm3,dword [bx],0 vpinsrb xmm0,eax,0 vpinsrb xmm1,bl,0 vpinsrb xmm2,[bx],0 vpinsrb xmm3,byte [bx],0 vpinsrw xmm0,eax,0 vpinsrw xmm1,si,0 vpinsrw xmm2,[bx],0 vpinsrw xmm3,word [bx],0 vpinsrd xmm0,eax,0 vpinsrd xmm1,esi,0 vpinsrd xmm2,[bx],0 vpinsrd xmm3,dword [bx],0 vpinsrb xmm4,xmm0,eax,0 vpinsrb xmm5,xmm1,bl,0 vpinsrb xmm6,xmm2,[bx],0 vpinsrb xmm7,xmm3,byte [bx],0 vpinsrw xmm4,xmm0,eax,0 vpinsrw xmm5,xmm1,si,0 vpinsrw xmm6,xmm2,[bx],0 vpinsrw xmm7,xmm3,word [bx],0 vpinsrd xmm4,xmm0,eax,0 vpinsrd xmm5,xmm1,esi,0 vpinsrd xmm6,xmm2,[bx],0 vpinsrd xmm7,xmm3,dword [bx],0
coapp-packages/nasm
test/pinsr16.asm
Assembly
bsd-2-clause
1,081
class Strace < Formula desc "Diagnostic, instructional, and debugging tool for the Linux kernel" homepage "https://strace.io/" url "https://github.com/strace/strace/releases/download/v5.15/strace-5.15.tar.xz" sha256 "ebcac22f297335294dc654425cbc3ce013343bece6da2699e3aec86aee8d72dc" license "LGPL-2.1-or-later" bottle do sha256 cellar: :any_skip_relocation, x86_64_linux: "d532a2deca6676dd22013f05791a0f8bc3c0d50b913f9523173ac7e33f4b7761" end head do url "https://github.com/strace/strace.git" depends_on "autoconf" => :build depends_on "automake" => :build end depends_on :linux depends_on "linux-headers@4.4" def install system "./bootstrap" if build.head? system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}", "--enable-mpers=no" # FIX: configure: error: Cannot enable m32 personality support system "make", "install" end test do out = `"strace" "true" 2>&1` # strace the true command, redirect stderr to output assert_match "execve(", out assert_match "+++ exited with 0 +++", out end end
sjackman/homebrew-core
Formula/strace.rb
Ruby
bsd-2-clause
1,141
#include "RotLib.h" #include "Exception.h" using namespace std; RotLib::RotLib(PRECISION p, STORAGE s, int b, bool ph) : lib_p(p), lib_s(s), basis(b), phase(ph) { int N = p -> base; if (N != 2 && N != 10) { cout << "non base-2 or base-10 target precision." << endl; exit(1); } } RotLib::RotLib(const char* file) { load(file); } ostream& operator<<(ostream& out, const RotLib& L) { out << "===== Rotation library info =====" << endl; out << " - Basis = " << L.basis << endl; out << " - Precision: " << std::scientific << pow(L.lib_p->base, -L.lib_p->digits) << endl; out << " - Max Storage: " << L.lib_s -> size << L.lib_s -> unit << endl; out << " - Number of sequences: " << L.seqs.size() << endl; out << "=================================" << endl; return out; } int RotLib::estimate_storage(double thres, int Na) { int K10 = -log10(thres); int T = 10 * K10 + 3; // estimated T-count for each angle int bytes = Na * (2.5 * T + 200) / 8; char s_unit[5]; strcpy(s_unit, lib_s->unit); for (int i = 0; s_unit[i] != '\0'; i++) { s_unit[i] = toupper(s_unit[i]); } string str_unit(s_unit); string units[5] = {"B", "KB", "MB", "GB", "TB"}; int i = 0; int mult = 1; while (i < 5 && str_unit.compare(units[i]) != 0) { mult *= 1024; i++; } if (i == 5) { cout << "Unrecgonized storage unit." << endl; exit(1); } else if (lib_s->size * mult < bytes) { cout << "Need more storage space to achieve precision. "; cout << "Estimates: " << bytes << " Bytes." << endl; exit(1); } return bytes; } void RotLib::generate() { int N = lib_p -> base; int K = lib_p -> digits; int B = basis; // determine digits in basis int J = K; double thres = pow(N,-K); if (N > B) { while (thres < pow(B,-J)) { J++; } } else if (N < B) { while (J > 0 && thres > pow(B,-J+1)) { J--; } } int Na = (B-1) * J + 1; // number of angles to generate // Estimate storage and verify if too much int bytes = estimate_storage(thres, Na); int Ka = K; // Precision for each angle string p_flag; stringstream fss; if (N == 2) { // generate all base-2 angles, up to K of them Ka = Ka + 3; // Each seq has ~10x higher precision fss << "-b " << Ka; } else if (N == 10) { // generate all base-10 angles, up to 9K of them Ka = Ka + 1; // Each seq has ~10x higher precision fss << "-d " << Ka; // Each seq has ~10x higher precision } // Set global phase flag if (phase) { fss << " -p"; } p_flag = fss.str(); // Invoke gridsynth for rotation sequences // Modify me if gridsynth not found string gridsynthpath = "../../Rotations/gridsynth/gridsynth"; ifstream ifile(gridsynthpath.c_str()); if (!ifile) { cout << "Rotation decomposer not found!"; cout << " Check src/RotLib.cpp for gridsynthpath." << endl; exit(1); } double denom = 1.0; // First always add Pi to the library. stringstream argss; argss << "./" << gridsynthpath << " "; argss << "pi" << " " << p_flag; const char *args = argss.str().c_str(); int l = 0; int s = 0; charBits *bit_buff = new charBits(); // new code vector if (!bit_buff) { cout << "charBits buffer error!" << endl; exit(1); } load_gridsynth(args, bit_buff, &l, &s); cout << "\tSequence: " << l << " chars, Code: " << s << " bits.\n" << endl; Code *word_ptr = (*bit_buff).flush_code(); if (!word_ptr) { cout << "charBits buffer error!" << endl; delete bit_buff; exit(1); } else { seqs.push_back(RotLib::seq(l, s, 1, 0, *word_ptr)); // clean up code vector delete bit_buff; } // Add more angles to library if necessary for (int k = 1; k < J + 1; k++) { denom /= B; for (int c = 1; c < B; c++) { stringstream ckss; ckss << "./" << gridsynthpath << " "; ckss << c << "*pi*" << setprecision(15)<< fixed << denom << " " << p_flag; const char *ckstr = ckss.str().c_str(); int ckl = 0; int cks = 0; charBits *ckbit_buff = new charBits(); // new code vector if (!ckbit_buff) { cout << "charBits buffer error!" << endl; delete ckbit_buff; exit(1); } load_gridsynth(ckstr, ckbit_buff, &ckl, &cks); cout <<"\tSequence: "<< ckl <<" chars, Code: "<< cks <<" bits.\n"<< endl; Code *ckword_ptr = (*ckbit_buff).flush_code(); if (!ckword_ptr) { cout << "charBits buffer error!" << endl; delete ckbit_buff; exit(1); } else { seqs.push_back(RotLib::seq(ckl, cks, c, k, *ckword_ptr)); } // clean up buffer delete ckbit_buff; } } } int RotLib::encode(string gates, int l, charBits *data) { const Codemap *et = &encode_table; // for encoding if (phase) { // no W gate et = &encode_table2; } int code_size = 4; int g = 0; while (g < l) { stringstream gss; gss << gates[g]; string gate_str = gss.str(); if (gate_str == "H" && g < l - 1) { stringstream htss; htss << gates[g] << gates[g + 1]; if (htss.str() == "HT") { gate_str = htss.str(); g++; } } string huff = (*et).at(gate_str); int num_bits = huff.length(); data -> charBits::write_bits(huff, num_bits); code_size += num_bits; g++; } return code_size; } string RotLib::decode(charBits &data, int l) { string all_bits; stringstream ress; data.charBits::read_bits(&all_bits); int len = all_bits.size(); if (phase) { // no W gate int i = 0; while (i < len) { if (all_bits[i] == '0') { // 0 : HT ress << "HT"; i++; } else if (i + 1 < len && all_bits[i+1] == '0') { // 10 : S ress << "S"; i += 2; } else if (i + 2 < len && all_bits[i+2] == '1') { // 111 : X ress << "X"; i += 3; } else if (i + 3 < len && all_bits[i+3] == '0') { // 1100 : H ress << "H"; i += 4; } else if (i + 3 < len && all_bits[i+3] == '1') { // 1101 : T ress << "T"; i += 4; } else { cout << "Something went wrong while decoding." << endl; exit(1); } } } else { // with W gate int i = 0; while (i < len) { if (all_bits[i] == '0') { // 0 : HT ress << "HT"; i++; } else if (i + 1 < len && all_bits[i+1] == '0') { // 10 : S ress << "S"; i += 2; } else if (i + 2 < len && all_bits[i+2] == '1') { // 111 : W ress << "W"; i += 3; } else if (i + 3 < len && all_bits[i+3] == '0') { // 1100 : X ress << "X"; i += 4; } else if (i + 4 < len && all_bits[i+4] == '0') { // 11010 : H ress << "H"; i += 5; } else if (i + 4 < len && all_bits[i+4] == '1') { // 11011 : T ress << "T"; i += 5; } else { cout << "Something went wrong while decoding." << endl; exit(1); } } } return ress.str(); } void RotLib::load_gridsynth(const char *args, charBits *data, int *l, int *s) { cout << "Calling: " << args << endl; string res = exec(args); cout << "\t" << res; int ll = res.length() - 1; // excluding '\n' at the end int ss; if (!data) { cout << "charBits buffer error!" << endl; exit(1); } else { ss = encode(res, ll, data); } if (!l || !s) { cout << "l,s reference error!" << endl; exit(1); } else { *l = ll; *s = ss; } return; } int RotLib::load(const char *file) { char header[27]; char check[] = "Gridsynth Rotation Library"; char msg[128]; ifstream infile; infile.open(file, ios::in | ios::binary); if (!infile) { sprintf(msg, "unable to open file '%s' for reading", file); cout << msg << endl; exit(1); } // Check Header infile.read((char *)header, sizeof(check)); if (strncmp(header, check, 27*sizeof(char))) { sprintf(msg, "'%s' does not look like a Rotation Library.", file); cout << msg << endl; exit(1); } // Structural stuff infile.read((char *)&basis, sizeof(basis)); infile.read((char *)&phase, sizeof(phase)); infile.read((char *)&lib_p, sizeof(lib_p)); infile.read((char *)&lib_s, sizeof(lib_s)); // Content of sequences int total; infile.read((char *)&total, sizeof(int)); for (int si = 0; si < total; si++) { int ls; int ss; int cs; int ks; Code words; infile.read((char *)&ls, sizeof(int)); infile.read((char *)&ss, sizeof(int)); infile.read((char *)&cs, sizeof(int)); infile.read((char *)&ks, sizeof(int)); int code_bytes; infile.read((char *)&code_bytes, sizeof(int)); unsigned char tmp; for (int ci = 0; ci < code_bytes; ci++) { infile.read((char *)&tmp, sizeof(unsigned char)); words.push_back(tmp); } seqs.push_back(RotLib::seq(ls, ss, cs, ks, words)); } infile.close(); return 1; } void RotLib::save(const char *file) { char header[] = "Gridsynth Rotation Library"; char msg[128]; ofstream outfile; outfile.open(file, ios::out | ios::binary); if (!outfile) { sprintf(msg, "unable to open file '%s' for writing", file); cout << msg << endl; exit(1); } // Header outfile.write(header, sizeof(header)); // Structural stuff outfile.write((char *)&basis, sizeof(basis)); outfile.write((char *)&phase, sizeof(phase)); outfile.write((char *)&lib_p, sizeof(lib_p)); outfile.write((char *)&lib_s, sizeof(lib_s)); // Content of sequences int total = seqs.size(); outfile.write((char *)&total, sizeof(int)); vector<seq>::iterator si = seqs.begin(); while (si != seqs.end()) { outfile.write((char *)&(*si).l, sizeof(int)); outfile.write((char *)&(*si).s, sizeof(int)); outfile.write((char *)&(*si).c, sizeof(int)); outfile.write((char *)&(*si).k, sizeof(int)); int code_bytes = (*si).word.size(); outfile.write((char *)&code_bytes, sizeof(int)); for (Code::iterator ci = (*si).word.begin(); ci != (*si).word.end(); ci++) { outfile.write((char *)&(*ci), sizeof(unsigned char)); } si++; } outfile.close(); } double RotLib::range_zero_two(double radian) { // assuming radian does not have pi factor while (radian < 0) { radian += 2; } while (radian >= 2) { radian -= 2; } return radian; } bool RotLib::epsilon_close(double a, double b, double epsilon) { double big = (a > b)? a : b; double small = (a <= b)? a : b; return (big - small < epsilon); // strictly close } void RotLib::seq_combine(const vector<int> &indices, Rz *out) { // assuming indices are unique and check if seq is clean if (!out || out -> length != 0) { cout << "Invalid seq destination (NULL or non-empty)." << endl; exit(0); } // append sequences from left to right stringstream gss; vector<int>::const_iterator ii; for (ii = indices.begin(); ii != indices.end(); ii++) { const seq seqi = seqs.at(*ii); out -> length += seqi.l; charBits *bits = new charBits(seqi.word); gss << decode(*bits, seqi.l); // clean up bits delete bits; } out -> gates = gss.str(); } void RotLib::concatenate(Rz *output, double radian, const char *factor) { double pi = 3.1415926535897; char pi_str[] = "pi"; char no_str[] = ""; char input[10]; strcpy(input, factor); for (int i = 0; input[i] != '\0'; i++) { input[i] = tolower(input[i]); } double r_angle; bool radian_pi = strcmp(input, pi_str) == 0; if (strcmp(input, no_str) == 0) { radian /= pi; radian_pi = true; } if (radian_pi) { // angle: radian*pi radian = range_zero_two(radian); r_angle = radian; vector<int> indices; int J = seqs.size() / (basis - 1); int c_array[J + 1]; // basis representation of radian // c_array[i] stores c_i for (int i = 0; i < J + 1; i++) c_array[i] = 0; // integer part if (radian >= 1.0) { c_array[0] = 1; radian -= 1.0; } int j = 1; double bj = 1.0 / basis; // basis^(-j) double epsilon = pow(lib_p -> base, -(lib_p -> digits)); while (!epsilon_close(radian, 0, epsilon) && j < J + 1) { while (radian - bj >= 0) { radian -= bj; c_array[j] += 1; } bj /= (double)basis; j++; } if (c_array[0] == 1) indices.push_back(0); for (int k = 1; k < J + 1; k++) { int c = c_array[k]; if (c > 0) { int id = (basis - 1) * (k - 1) + c; if (id >= seqs.size()) { cout << "seqs out of bound: " << id << " out of " << seqs.size() << endl; exit(1); } indices.push_back(id); } } // Now combine the selected sequences stringstream angless; angless << r_angle << "*pi"; output -> theta = angless.str(); output -> p = lib_p; seq_combine(indices, output); } else { cout << "non pi-factor angles are not yet supported!" << endl; exit(1); } }
ajavadia/ScaffCC
scripts/gen_rotations/src/RotLib.cpp
C++
bsd-2-clause
12,194
/* * Copyright (c) 2012, NTT Multimedia Communications Laboratories, Inc. and Koushik Sen * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Author: Koushik Sen (ksen@cs.berkeley.edu) */ package janala.logger.inst; public class L2D extends Instruction { public L2D(int iid, int mid) { super(iid, mid); } public void visit(IVisitor visitor) { visitor.visitL2D(this); } @Override public String toString() { return "L2D iid="+iid+" mid="+mid; } }
handysama/janala2-csit6910
src/janala/logger/inst/L2D.java
Java
bsd-2-clause
1,784
/* $FreeBSD: soc2013/dpl/head/contrib/ipfilter/ipsend/.OLD/ip_compat.h 145562 2005-04-25 18:20:15Z darrenr $ */ /* * (C)opyright 1995 by Darren Reed. * * This code may be freely distributed as long as it retains this notice * and is not changed in any way. The author accepts no responsibility * for the use of this software. I hate legaleese, don't you ? * * @(#)ip_compat.h 1.2 12/7/95 */ /* * These #ifdef's are here mainly for linux, but who knows, they may * not be in other places or maybe one day linux will grow up and some * of these will turn up there too. */ #ifndef ICMP_UNREACH # define ICMP_UNREACH ICMP_DEST_UNREACH #endif #ifndef ICMP_SOURCEQUENCH # define ICMP_SOURCEQUENCH ICMP_SOURCE_QUENCH #endif #ifndef ICMP_TIMXCEED # define ICMP_TIMXCEED ICMP_TIME_EXCEEDED #endif #ifndef ICMP_PARAMPROB # define ICMP_PARAMPROB ICMP_PARAMETERPROB #endif #ifndef IPVERSION # define IPVERSION 4 #endif #ifndef IPOPT_MINOFF # define IPOPT_MINOFF 4 #endif #ifndef IPOPT_COPIED # define IPOPT_COPIED(x) ((x)&0x80) #endif #ifndef IPOPT_EOL # define IPOPT_EOL 0 #endif #ifndef IPOPT_NOP # define IPOPT_NOP 1 #endif #ifndef IP_MF # define IP_MF ((u_short)0x2000) #endif #ifndef ETHERTYPE_IP # define ETHERTYPE_IP ((u_short)0x0800) #endif #ifndef TH_FIN # define TH_FIN 0x01 #endif #ifndef TH_SYN # define TH_SYN 0x02 #endif #ifndef TH_RST # define TH_RST 0x04 #endif #ifndef TH_PUSH # define TH_PUSH 0x08 #endif #ifndef TH_ACK # define TH_ACK 0x10 #endif #ifndef TH_URG # define TH_URG 0x20 #endif #ifndef IPOPT_EOL # define IPOPT_EOL 0 #endif #ifndef IPOPT_NOP # define IPOPT_NOP 1 #endif #ifndef IPOPT_RR # define IPOPT_RR 7 #endif #ifndef IPOPT_TS # define IPOPT_TS 68 #endif #ifndef IPOPT_SECURITY # define IPOPT_SECURITY 130 #endif #ifndef IPOPT_LSRR # define IPOPT_LSRR 131 #endif #ifndef IPOPT_SATID # define IPOPT_SATID 136 #endif #ifndef IPOPT_SSRR # define IPOPT_SSRR 137 #endif #ifndef IPOPT_SECUR_UNCLASS # define IPOPT_SECUR_UNCLASS ((u_short)0x0000) #endif #ifndef IPOPT_SECUR_CONFID # define IPOPT_SECUR_CONFID ((u_short)0xf135) #endif #ifndef IPOPT_SECUR_EFTO # define IPOPT_SECUR_EFTO ((u_short)0x789a) #endif #ifndef IPOPT_SECUR_MMMM # define IPOPT_SECUR_MMMM ((u_short)0xbc4d) #endif #ifndef IPOPT_SECUR_RESTR # define IPOPT_SECUR_RESTR ((u_short)0xaf13) #endif #ifndef IPOPT_SECUR_SECRET # define IPOPT_SECUR_SECRET ((u_short)0xd788) #endif #ifndef IPOPT_SECUR_TOPSECRET # define IPOPT_SECUR_TOPSECRET ((u_short)0x6bc5) #endif #ifdef linux # if LINUX < 0200 # define icmp icmphdr # define icmp_type type # define icmp_code code # endif /* * From /usr/include/netinet/ip_var.h * !%@#!$@# linux... */ struct ipovly { caddr_t ih_next, ih_prev; /* for protocol sequence q's */ u_char ih_x1; /* (unused) */ u_char ih_pr; /* protocol */ short ih_len; /* protocol length */ struct in_addr ih_src; /* source internet address */ struct in_addr ih_dst; /* destination internet address */ }; typedef struct { __u16 th_sport; __u16 th_dport; __u32 th_seq; __u32 th_ack; # if defined(__i386__) || defined(__MIPSEL__) || defined(__alpha__) ||\ defined(vax) __u8 th_res:4; __u8 th_off:4; #else __u8 th_off:4; __u8 th_res:4; #endif __u8 th_flags; __u16 th_win; __u16 th_sum; __u16 th_urp; } tcphdr_t; typedef struct { __u16 uh_sport; __u16 uh_dport; __s16 uh_ulen; __u16 uh_sum; } udphdr_t; typedef struct { # if defined(__i386__) || defined(__MIPSEL__) || defined(__alpha__) ||\ defined(vax) __u8 ip_hl:4; __u8 ip_v:4; # else __u8 ip_hl:4; __u8 ip_v:4; # endif __u8 ip_tos; __u16 ip_len; __u16 ip_id; __u16 ip_off; __u8 ip_ttl; __u8 ip_p; __u16 ip_sum; struct in_addr ip_src; struct in_addr ip_dst; } ip_t; typedef struct { __u8 ether_dhost[6]; __u8 ether_shost[6]; __u16 ether_type; } ether_header_t; typedef struct icmp { u_char icmp_type; /* type of message, see below */ u_char icmp_code; /* type sub code */ u_short icmp_cksum; /* ones complement cksum of struct */ union { u_char ih_pptr; /* ICMP_PARAMPROB */ struct in_addr ih_gwaddr; /* ICMP_REDIRECT */ struct ih_idseq { n_short icd_id; n_short icd_seq; } ih_idseq; int ih_void; } icmp_hun; #define icmp_pptr icmp_hun.ih_pptr #define icmp_gwaddr icmp_hun.ih_gwaddr #define icmp_id icmp_hun.ih_idseq.icd_id #define icmp_seq icmp_hun.ih_idseq.icd_seq #define icmp_void icmp_hun.ih_void union { struct id_ts { n_time its_otime; n_time its_rtime; n_time its_ttime; } id_ts; struct id_ip { ip_t idi_ip; /* options and then 64 bits of data */ } id_ip; u_long id_mask; char id_data[1]; } icmp_dun; #define icmp_otime icmp_dun.id_ts.its_otime #define icmp_rtime icmp_dun.id_ts.its_rtime #define icmp_ttime icmp_dun.id_ts.its_ttime #define icmp_ip icmp_dun.id_ip.idi_ip #define icmp_mask icmp_dun.id_mask #define icmp_data icmp_dun.id_data } icmphdr_t; # define bcopy(a,b,c) memmove(b,a,c) # define bcmp(a,b,c) memcmp(a,b,c) # define ifnet device #else typedef struct udphdr udphdr_t; typedef struct tcphdr tcphdr_t; typedef struct ip ip_t; typedef struct ether_header ether_header_t; #endif #if defined(__SVR4) || defined(__svr4__) # define bcopy(a,b,c) memmove(b,a,c) # define bcmp(a,b,c) memcmp(a,b,c) # define bzero(a,b) memset(a,0,b) #endif
dplbsd/zcaplib
head/contrib/ipfilter/ipsend/.OLD/ip_compat.h
C
bsd-2-clause
5,247
default_app_config = 'comet.apps.CometIndicatorConfig'
LegoStormtroopr/comet-indicator-registry
comet/__init__.py
Python
bsd-2-clause
54
// Copyright (C) 2018 Leo Balter. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.prototype.flatMap description: > array-like objects can be flattened (typedArrays) info: | Array.prototype.flatMap ( mapperFunction [ , thisArg ] ) 1. Let O be ? ToObject(this value). 2. Let sourceLen be ? ToLength(? Get(O, "length")). ... 5. Let A be ? ArraySpeciesCreate(O, 0). ... ArraySpeciesCreate ( originalArray, length ) 3. Let isArray be ? IsArray(originalArray). 4. If isArray is false, return ? ArrayCreate(length). 5. Let C be ? Get(originalArray, "constructor"). includes: [compareArray.js] features: [Array.prototype.flatMap, Int32Array] ---*/ function same(e) { return e; } var ta; var actual; ta = new Int32Array([1, 0, 42]); Object.defineProperty(ta, 'constructor', { get() { throw "it should not object the typedarray ctor"; } }); actual = [].flatMap.call(ta, same); assert.compareArray(actual, [1, 0, 42], 'compare returned array'); assert.sameValue(Object.getPrototypeOf(actual), Array.prototype, 'returned object is an array #1'); assert.sameValue(actual instanceof Int32Array, false, 'returned object is not an instance of Int32Array #1'); ta = new Int32Array(0); Object.defineProperty(ta, 'constructor', { get() { throw "it should not object the typedarray ctor"; } }); actual = [].flatMap.call(ta, same); assert.compareArray(actual, [], 'compare returned empty array'); assert.sameValue(Object.getPrototypeOf(actual), Array.prototype, 'returned object is an array #2'); assert.sameValue(actual instanceof Int32Array, false, 'returned object is not an instance of Int32Array #2');
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Array/prototype/flatMap/array-like-objects-typedarrays.js
JavaScript
bsd-2-clause
1,689
# Copyright 2012 Energid Technologies from energid_nlp import logic GENERATION_PROPOSITION = '$generate' class Error(Exception): pass class Generator: def __init__(self, kb): self.kb = kb def generate_prim(self, concept): if isinstance(concept, logic.Description): return self.generate_prim(concept.base) elif isinstance(concept, logic.Expr): return self.generate_prim(concept.op) else: result = '%s' % (concept,) return str(result) def generate(self, concept): if (isinstance(concept, str) or isinstance(concept, logic.Description) or isinstance(concept, logic.Expr)): template = self.kb.slot_value(concept, GENERATION_PROPOSITION) if template is None: return self.generate_prim(concept) else: return self.generate_template(concept, template.op) else: return self.generate_prim(concept) def generate_template(self, concept, template): result_string = '' start = 0 while start < len(template): slot_start = template.find('{', start) if slot_start == -1: # No more slot refs result_string = result_string + template[start:] break result_string = result_string + template[start:slot_start] slot_end = template.find('}', slot_start + 1) if slot_end == -1: raise Error("Generation template %r for %s has an unclosed '{'" % ( template, concept)) slot_name = template[slot_start + 1:slot_end] slot_value = self.kb.slot_value(concept, slot_name) if slot_value is not None: result_string = result_string + self.generate(slot_value) start = slot_end + 1 # Strip whitepace out of result, in case slots in template # couldn't be filled. return result_string.strip()
wiseman/energid_nlp
energid_nlp/generation.py
Python
bsd-2-clause
1,810
/* ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @file wdg_lld.h * @brief WDG Driver subsystem low level driver header. * * @addtogroup WDG * @{ */ #ifndef _WDG_LLD_H_ #define _WDG_LLD_H_ #if (HAL_USE_WDG == TRUE) || defined(__DOXYGEN__) /*===========================================================================*/ /* Driver constants. */ /*===========================================================================*/ /** * @name RLR register definitions * @{ */ #define STM32_IWDG_RL_MASK (0x00000FFF << 0) #define STM32_IWDG_RL(n) ((n) << 0) /** @} */ /** * @name PR register definitions * @{ */ #define STM32_IWDG_PR_MASK (7 << 0) #define STM32_IWDG_PR_4 0U #define STM32_IWDG_PR_8 1U #define STM32_IWDG_PR_16 2U #define STM32_IWDG_PR_32 3U #define STM32_IWDG_PR_64 4U #define STM32_IWDG_PR_128 5U #define STM32_IWDG_PR_256 6U /** @} */ /** * @name WINR register definitions * @{ */ #define STM32_IWDG_WIN_MASK (0x00000FFF << 0) #define STM32_IWDG_WIN(n) ((n) << 0) #define STM32_IWDG_WIN_DISABLED STM32_IWDG_WIN(0x00000FFF) /** @} */ /*===========================================================================*/ /* Driver pre-compile time settings. */ /*===========================================================================*/ /** * @name Configuration options * @{ */ /** * @brief IWDG driver enable switch. * @details If set to @p TRUE the support for IWDG is included. * @note The default is @p FALSE. */ #if !defined(STM32_WDG_USE_IWDG) || defined(__DOXYGEN__) #define STM32_WDG_USE_IWDG FALSE #endif /** @} */ /*===========================================================================*/ /* Derived constants and error checks. */ /*===========================================================================*/ #if STM32_WDG_USE_IWDG && !STM32_HAS_IWDG #error "IWDG not present in the selected device" #endif #if !STM32_WDG_USE_IWDG #error "WDG driver activated but no xWDG peripheral assigned" #endif #if !defined(STM32_LSI_ENABLED) #error "STM32_LSI_ENABLED not defined" #endif #if (STM32_WDG_USE_IWDG == TRUE) && (STM32_LSI_ENABLED == FALSE) #error "IWDG requires LSI clock" #endif /*===========================================================================*/ /* Driver data structures and types. */ /*===========================================================================*/ /** * @brief Type of a structure representing an WDG driver. */ typedef struct WDGDriver WDGDriver; /** * @brief Driver configuration structure. * @note It could be empty on some architectures. */ typedef struct { /** * @brief Configuration of the IWDG_PR register. * @details See the STM32 reference manual for details. */ uint32_t pr; /** * @brief Configuration of the IWDG_RLR register. * @details See the STM32 reference manual for details. */ uint32_t rlr; #if STM32_IWDG_IS_WINDOWED || defined(__DOXYGEN__) /** * @brief Configuration of the IWDG_WINR register. * @details See the STM32 reference manual for details. * @note This field is not present in F1, F2, F4, L1 sub-families. */ uint32_t winr; #endif } WDGConfig; /** * @brief Structure representing an WDG driver. */ struct WDGDriver { /** * @brief Driver state. */ wdgstate_t state; /** * @brief Current configuration data. */ const WDGConfig *config; /* End of the mandatory fields.*/ /** * @brief Pointer to the IWDG registers block. */ IWDG_TypeDef *wdg; }; /*===========================================================================*/ /* Driver macros. */ /*===========================================================================*/ /*===========================================================================*/ /* External declarations. */ /*===========================================================================*/ #if STM32_WDG_USE_IWDG && !defined(__DOXYGEN__) extern WDGDriver WDGD1; #endif #ifdef __cplusplus extern "C" { #endif void wdg_lld_init(void); void wdg_lld_start(WDGDriver *wdgp); void wdg_lld_stop(WDGDriver *wdgp); void wdg_lld_reset(WDGDriver *wdgp); #ifdef __cplusplus } #endif #endif /* HAL_USE_WDG == TRUE */ #endif /* _WDG_LLD_H_ */ /** @} */
nameless1379/rplidar_3d
embedded/os/hal/ports/STM32/LLD/xWDGv1/wdg_lld.h
C
bsd-2-clause
5,393
<?php namespace NicklasW\PkmGoApi\Authentication\Config; use NicklasW\PkmGoApi\Authentication\AccessToken; use NicklasW\PkmGoApi\Authentication\Factory\Factory; class Config { /** * @var string */ protected $user; /** * @var string */ protected $password; /** * @var string */ protected $authToken; /** * @var string */ protected $refreshToken; /** * @var string */ protected $oauthToken; /** * @var string */ protected $provider; /** * @return string */ public function getUser() { return $this->user; } /** * @param string $user */ public function setUser($user) { $this->user = $user; } /** * @return string */ public function getPassword() { return $this->password; } /** * @param string $password */ public function setPassword($password) { $this->password = $password; } /** * @return string */ public function getAuthToken() { return $this->authToken; } /** * @param string $authToken */ public function setAuthToken($authToken) { $this->authToken = $authToken; } /** * @return string */ public function getRefreshToken() { return $this->refreshToken; } /** * @param string $refreshToken */ public function setRefreshToken($refreshToken) { $this->refreshToken = $refreshToken; } /** * @return string */ public function getOauthToken() { return $this->oauthToken; } /** * @param string $oauthToken */ public function setOauthToken($oauthToken) { $this->oauthToken = $oauthToken; } /** * @return string */ public function getProvider() { return $this->provider; } /** * @param string $provider */ public function setProvider($provider) { $this->provider = $provider; } /** * @return boolean */ public function isGoogle() { return $this->provider === Factory::PROVIDER_GOOGLE; } /** * @return boolean */ public function isPTC() { return $this->provider === Factory::PROVIDER_PTC; } }
voxx/PokemonGoAPI-PHP
src/Authentication/Config/Config.php
PHP
bsd-2-clause
2,395
cask 'mullvadvpn' do version '2018.2' sha256 '9a3436e566cd7577e78cfe87a77b874ce631da1502dc09914e14ca49ad26642f' # github.com/mullvad/mullvadvpn-app was verified as official when first introduced to the cask url "https://github.com/mullvad/mullvadvpn-app/releases/download/#{version}/MullvadVPN-#{version}.pkg" appcast 'https://github.com/mullvad/mullvadvpn-app/releases.atom' name 'Mullvad' homepage 'https://mullvad.net/' conflicts_with cask: 'mullvad-vpn-beta' pkg "MullvadVPN-#{version}.pkg" uninstall pkgutil: 'net.mullvad.vpn', launchctl: 'net.mullvad.daemon' end
cliffcotino/homebrew-cask
Casks/mullvadvpn.rb
Ruby
bsd-2-clause
607
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: The valueOf method returns its "this" value es5id: 15.2.4.4_A1_T3 description: "\"this\" value is a string" ---*/ //CHECK#1 if (typeof Object.prototype.valueOf !== "function") { $ERROR('#1: valueOf method defined'); } var obj = new Object("greenfield"); //CHECK#2 if (typeof obj.valueOf !== "function") { $ERROR('#2: valueOf method accessed'); } //CHECK#3 if (obj.valueOf() !== "greenfield") { $ERROR('#3: The valueOf method returns its this value'); }
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Object/prototype/valueOf/S15.2.4.4_A1_T3.js
JavaScript
bsd-2-clause
608
#include <QDebug> #include <cdio/cdio.h> #include "CdromManager.h" #include "MetadataManager.h" #include "Player.h" #ifdef EMS_CDROM_RIPPER #include "CdromRipper.h" #endif #define INTERFACE "com.EnnaMediaServer.Cdrom" #define SIGNAL_NAME_INSERT "inserted" #define SIGNAL_NAME_REMOVE "removed" /* --------------------------------------------------------- * UTILS * --------------------------------------------------------- */ static inline int cddb_sum(int n) { int result = 0; while (n > 0) { result += n % 10; n /= 10; } return result; } void CdromManager::getAvailableCdroms(QVector<EMSCdrom> *cdromsOut) { cdromsOut->clear(); mutex.lock(); for (int i=0; i<cdroms.size(); i++) { cdromsOut->append(cdroms.at(i)); } mutex.unlock(); } bool CdromManager::getCdrom(QString device, EMSCdrom *cdrom) { bool found = false; mutex.lock(); for (int i=0; i<cdroms.size(); i++) { if (cdroms.at(i).device == device) { *cdrom = cdroms.at(i); found = true; break; } } mutex.unlock(); return found; } bool CdromManager::isRipInProgress() { #ifdef EMS_CDROM_RIPPER if (m_cdromRipper) return true; #endif return false; } void CdromManager::setRipAudioFormat(const QString &ripAudioFormat) { m_ripAudioFormat = ripAudioFormat; } /* --------------------------------------------------------- * INSERT/REMOVE HOOK * --------------------------------------------------------- */ void CdromManager::dbusMessageInsert(QString message) { EMSCdrom newCD; unsigned int sum = 0; /* Check the new CD is not already in the list */ if (getCdrom(message, &newCD)) { qCritical() << "CD already in the list of current CDROM."; return; } /* The given message only contain the device name */ newCD.device = message; qDebug() << "New CDROM inserted : " << newCD.device; /* Open the CD and get track data (number, duration, ...) */ CdIo_t *cdrom = cdio_open(newCD.device.toStdString().c_str(), DRIVER_UNKNOWN); if (!cdrom) { qCritical() << "Unable to open device " << newCD.device; return; } /* Check that the inserted cdrom is a CD-DA */ discmode_t mode = cdio_get_discmode(cdrom); if (mode != CDIO_DISC_MODE_CD_DA) { /* Ignore not valid CDROM */ qDebug() << "Inserted disk is not an audio CD " << QString("(%1)").arg(mode); return; } /* Get size of the disck */ track_t trackNumber = cdio_get_num_tracks(cdrom); if (trackNumber <= 1) { qCritical() << "Unable to read CDROM TOC"; } qDebug() << "Found " << QString("%1").arg(trackNumber) << " tracks in " << newCD.device; /* Retrieve each track data */ for (track_t i=1; i<=trackNumber; i++) { EMSTrack track; track.filename = newCD.device; track.type = TRACK_TYPE_CDROM; track.position = i; lsn_t lsnBegin = cdio_get_track_lsn(cdrom, i); lsn_t lsnEnd = cdio_get_track_last_lsn(cdrom, i); track.duration = (lsnEnd - lsnBegin + 1) / CDIO_CD_FRAMES_PER_SEC; /* One sector = 1/75s */ track.format = QString("cdda"); track.sample_rate = 44100; /* Set a default name waiting metadata */ track.name = QString("Track %1").arg(track.position); track.album.name = QString("Unknown album"); /* Add the new track in the list only if it is an audio track */ track_format_t format = cdio_get_track_format(cdrom, i); if (format == TRACK_FORMAT_AUDIO) { newCD.tracks.append(track); } /* For disc id computation */ lba_t lba = cdio_lsn_to_lba (lsnBegin); sum += cddb_sum(lba / CDIO_CD_FRAMES_PER_SEC); QPair<lsn_t, lsn_t> trackSectors(lsnBegin, lsnEnd); newCD.trackSectors[i] = trackSectors; } /* Compute the discid * Code copied from libcdio/example/discid.c */ unsigned start_sec = cdio_get_track_lba(cdrom, 1) / CDIO_CD_FRAMES_PER_SEC; unsigned int leadout = cdio_get_track_lba(cdrom, CDIO_CDROM_LEADOUT_TRACK); unsigned leadout_sec = leadout / CDIO_CD_FRAMES_PER_SEC; unsigned total = leadout_sec - start_sec; unsigned id = ((sum % 0xff) << 24 | total << 8 | trackNumber); newCD.disc_id = QString().sprintf("%08X %d", id, trackNumber); for (track_t i=1; i <=trackNumber; i++) { lba_t lba = cdio_get_track_lba(cdrom, i); newCD.disc_id += QString().sprintf(" %ld", (long) lba); } newCD.disc_id += QString().sprintf(" %u", leadout); cdio_destroy(cdrom); qDebug() << "Computed DISCID is " << newCD.disc_id; /* Add the new CDROM in the list and emit signal to warn listeners */ mutex.lock(); cdroms.append(newCD); mutex.unlock(); emit cdromInserted(newCD); /* Ask metadata to all plugins which can handle "discid" lookup */ QStringList capabilities; capabilities << "discid"; for(int i=0; i<newCD.tracks.size(); i++) { emit cdromTrackNeedUpdate(newCD.tracks.at(i), capabilities); } } void CdromManager::cdromTrackUpdated(EMSTrack track, bool complete) { bool found = false; unsigned cdromID = 0; if (track.type != TRACK_TYPE_CDROM) { return; } if (!complete) { return; } /* Retrieve the corresponding cdrom in the list of cdroms */ mutex.lock(); for (int i=0; i<cdroms.size(); i++) { if (cdroms.at(i).device == track.filename) { cdromID = i; found = true; break; } } if (found) { EMSCdrom cdrom = cdroms.at(cdromID); for(int i=0; i<cdrom.tracks.size(); i++) { /* Replace the new track */ if(cdrom.tracks.at(i).position == track.position) { cdrom.tracks.replace(i, track); break; } } cdroms[cdromID] = cdrom; } if (found) { emit cdromChanged(cdroms.at(cdromID)); } mutex.unlock(); } void CdromManager::dbusMessageRemove(QString message) { bool found = false; EMSCdrom cdrom; mutex.lock(); for (int i=0; i<cdroms.size(); i++) { if (cdroms.at(i).device == message) { cdrom = cdroms.at(i); cdroms.removeAt(i); found = true; break; } } mutex.unlock(); if (!found) { /* Ejected CDROM is not found */ return; } qDebug() << "CDROM ejected : " << cdrom.device; /* Remove played CDROM from the current playlist */ EMSPlaylist playlist = Player::instance()->getCurentPlaylist(); for (int i=0; i<playlist.tracks.size(); i++) { EMSTrack track = playlist.tracks.at(i); if (track.type == TRACK_TYPE_CDROM && track.filename == cdrom.device) { Player::instance()->removeTrack(track); } } emit cdromEjected(cdrom); } /* --------------------------------------------------------- * START/STOP CDROM MANAGER * --------------------------------------------------------- */ CdromManager* CdromManager::_instance = 0; CdromManager::CdromManager(QObject *parent) : QObject(parent), bus(QDBusConnection::systemBus()) { cdio_init(); qRegisterMetaType<EMSCdrom>("EMSCdrom"); connect(this, SIGNAL(cdromTrackNeedUpdate(EMSTrack,QStringList)), MetadataManager::instance(), SLOT(update(EMSTrack,QStringList)), Qt::DirectConnection); connect(MetadataManager::instance(), SIGNAL(updated(EMSTrack,bool)), this, SLOT(cdromTrackUpdated(EMSTrack,bool))); } CdromManager::~CdromManager() { #ifdef EMS_CDROM_RIPPER delete m_cdromRipper; #endif } bool CdromManager::startMonitor() { if (!bus.isConnected()) { qCritical() << "Could not connect to session bus ! No CDROM management."; return false; } else { bus.connect(QString(), QString(), INTERFACE , SIGNAL_NAME_INSERT, this, SLOT(dbusMessageInsert(QString))); bus.connect(QString(), QString(), INTERFACE , SIGNAL_NAME_REMOVE, this, SLOT(dbusMessageRemove(QString))); } /* In case of CDROM already present, trigger actions using udevadm * Note: EMS must be launched with root rights or be able to trigger action using udev. */ QProcess cmd; cmd.execute(QString("/bin/udevadm"), QString("trigger --action=change --sysname-match=sr[0-9]").split(' ')); return true; } void CdromManager::stopMonitor() { if (bus.isConnected()) { bus.disconnect(QString(), QString(), INTERFACE , SIGNAL_NAME_INSERT, this, SLOT(dbusMessageInsert(QString))); bus.disconnect(QString(), QString(), INTERFACE , SIGNAL_NAME_REMOVE, this, SLOT(dbusMessageRemove(QString))); } } void CdromManager::startRip() { #ifdef EMS_CDROM_RIPPER /* Get first available CDROM */ QVector<EMSCdrom> cdroms; getAvailableCdroms(&cdroms); /* Start the thread */ if ((cdroms.size() > 0) && (!isRipInProgress())) { EMSCdrom cdrom = cdroms.at(0); m_cdromRipper = new CdromRipper(this); connect(m_cdromRipper, &CdromRipper::resultReady, this, &CdromManager::handleCdromRipperResults); connect(m_cdromRipper, &CdromRipper::finished, m_cdromRipper, &QObject::deleteLater); connect(m_cdromRipper, &CdromRipper::ripProgressChanged, this, &CdromManager::ripProgress); m_cdromRipper->setCdrom(cdrom); m_cdromRipper->setAudioFormat(m_ripAudioFormat); m_cdromRipper->start(); } #endif } void CdromManager::ripProgress(EMSRipProgress ripProgress) { emit ripProgressChanged(ripProgress); } void CdromManager::handleCdromRipperResults(const QString &result ) { #ifdef EMS_CDROM_RIPPER if (m_cdromRipper) { qDebug() << "CdromManager handle cdrom ripper results: " << result; delete m_cdromRipper; m_cdromRipper = Q_NULLPTR; } #endif }
raoulh/Enna-Media-Server
src/ems/CdromManager.cpp
C++
bsd-2-clause
10,171
package com.wut.resources.file; import com.wut.datasources.CrudSource; import com.wut.datasources.aws.S3FileSource; import com.wut.model.Data; import com.wut.model.map.MessageData; import com.wut.model.scalar.BooleanData; import com.wut.model.scalar.IdData; import com.wut.model.scalar.StringData; import com.wut.model.stream.StreamData; import com.wut.pipeline.WutRequest; import com.wut.provider.file.DefaultFileProvider; import com.wut.provider.file.FileProvider; import com.wut.resources.common.CrudResource; import com.wut.resources.common.MissingParameterException; import com.wut.resources.common.ObsoleteCrudResource; import com.wut.support.Language; import com.wut.support.settings.SettingsManager; public class FileResource extends CrudResource { public FileResource() { super("queue", null); // TODO fix null here -- use a provider! } private static final long serialVersionUID = -1678486712182811729L; //private static FileProvider provider = new DefaultFileProvider(new S3FileSource()); @Override public String getName() { return "queue"; } @Override public Data read(WutRequest request) throws MissingParameterException { return null; } @Override public Data delete(WutRequest request) throws MissingParameterException { return null; } @Override public Data update(WutRequest request) throws MissingParameterException { return null; } }
rpalmite/webutilitykit
queue/src/main/java/com/wut/resources/file/FileResource.java
Java
bsd-2-clause
1,397
using System; using System.IO; namespace RestSharp.Portable.Content { /// <summary> /// A stream that encapsulates another and avoids calling the <see cref="IDisposable.Dispose"/> /// </summary> internal class NonDisposableStream : Stream { private readonly Stream _baseStream; /// <summary> /// Initializes a new instance of the <see cref="NonDisposableStream"/> class. /// </summary> /// <param name="baseStream">The underlying stream</param> public NonDisposableStream(Stream baseStream) { _baseStream = baseStream; } /// <inheritdoc/> public override bool CanRead => _baseStream.CanRead; /// <inheritdoc/> public override bool CanSeek => _baseStream.CanSeek; /// <inheritdoc/> public override bool CanWrite => _baseStream.CanWrite; /// <inheritdoc/> public override long Length => _baseStream.Length; /// <inheritdoc/> public override long Position { get { return _baseStream.Position; } set { _baseStream.Position = value; } } /// <inheritdoc/> public override void Flush() { _baseStream.Flush(); } /// <inheritdoc/> public override int Read(byte[] buffer, int offset, int count) { return _baseStream.Read(buffer, offset, count); } /// <inheritdoc/> public override long Seek(long offset, SeekOrigin origin) { return _baseStream.Seek(offset, origin); } /// <inheritdoc/> public override void SetLength(long value) { _baseStream.SetLength(value); } /// <inheritdoc/> public override void Write(byte[] buffer, int offset, int count) { _baseStream.Write(buffer, offset, count); } } }
gabornemeth/restsharp.portable
src/FubarCoder.RestSharp.Portable.Core/Content/NonDisposableStream.cs
C#
bsd-2-clause
1,941
"""Magic functions for running cells in various scripts.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import errno import os import sys import signal import time from subprocess import Popen, PIPE import atexit from IPython.core import magic_arguments from IPython.core.magic import ( Magics, magics_class, line_magic, cell_magic ) from IPython.lib.backgroundjobs import BackgroundJobManager from IPython.utils import py3compat from IPython.utils.process import arg_split from traitlets import List, Dict, default #----------------------------------------------------------------------------- # Magic implementation classes #----------------------------------------------------------------------------- def script_args(f): """single decorator for adding script args""" args = [ magic_arguments.argument( '--out', type=str, help="""The variable in which to store stdout from the script. If the script is backgrounded, this will be the stdout *pipe*, instead of the stderr text itself. """ ), magic_arguments.argument( '--err', type=str, help="""The variable in which to store stderr from the script. If the script is backgrounded, this will be the stderr *pipe*, instead of the stderr text itself. """ ), magic_arguments.argument( '--bg', action="store_true", help="""Whether to run the script in the background. If given, the only way to see the output of the command is with --out/err. """ ), magic_arguments.argument( '--proc', type=str, help="""The variable in which to store Popen instance. This is used only when --bg option is given. """ ), ] for arg in args: f = arg(f) return f @magics_class class ScriptMagics(Magics): """Magics for talking to scripts This defines a base `%%script` cell magic for running a cell with a program in a subprocess, and registers a few top-level magics that call %%script with common interpreters. """ script_magics = List( help="""Extra script cell magics to define This generates simple wrappers of `%%script foo` as `%%foo`. If you want to add script magics that aren't on your path, specify them in script_paths """, ).tag(config=True) @default('script_magics') def _script_magics_default(self): """default to a common list of programs""" defaults = [ 'sh', 'bash', 'perl', 'ruby', 'python', 'python2', 'python3', 'pypy', ] if os.name == 'nt': defaults.extend([ 'cmd', ]) return defaults script_paths = Dict( help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby' Only necessary for items in script_magics where the default path will not find the right interpreter. """ ).tag(config=True) def __init__(self, shell=None): super(ScriptMagics, self).__init__(shell=shell) self._generate_script_magics() self.job_manager = BackgroundJobManager() self.bg_processes = [] atexit.register(self.kill_bg_processes) def __del__(self): self.kill_bg_processes() def _generate_script_magics(self): cell_magics = self.magics['cell'] for name in self.script_magics: cell_magics[name] = self._make_script_magic(name) def _make_script_magic(self, name): """make a named magic, that calls %%script with a particular program""" # expand to explicit path if necessary: script = self.script_paths.get(name, name) @magic_arguments.magic_arguments() @script_args def named_script_magic(line, cell): # if line, add it as cl-flags if line: line = "%s %s" % (script, line) else: line = script return self.shebang(line, cell) # write a basic docstring: named_script_magic.__doc__ = \ """%%{name} script magic Run cells with {script} in a subprocess. This is a shortcut for `%%script {script}` """.format(**locals()) return named_script_magic @magic_arguments.magic_arguments() @script_args @cell_magic("script") def shebang(self, line, cell): """Run a cell via a shell command The `%%script` line is like the #! line of script, specifying a program (bash, perl, ruby, etc.) with which to run. The rest of the cell is run by that program. Examples -------- :: In [1]: %%script bash ...: for i in 1 2 3; do ...: echo $i ...: done 1 2 3 """ argv = arg_split(line, posix = not sys.platform.startswith('win')) args, cmd = self.shebang.parser.parse_known_args(argv) try: p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE) except OSError as e: if e.errno == errno.ENOENT: print("Couldn't find program: %r" % cmd[0]) return else: raise if not cell.endswith('\n'): cell += '\n' cell = cell.encode('utf8', 'replace') if args.bg: self.bg_processes.append(p) self._gc_bg_processes() if args.out: self.shell.user_ns[args.out] = p.stdout if args.err: self.shell.user_ns[args.err] = p.stderr self.job_manager.new(self._run_script, p, cell, daemon=True) if args.proc: self.shell.user_ns[args.proc] = p return try: out, err = p.communicate(cell) except KeyboardInterrupt: try: p.send_signal(signal.SIGINT) time.sleep(0.1) if p.poll() is not None: print("Process is interrupted.") return p.terminate() time.sleep(0.1) if p.poll() is not None: print("Process is terminated.") return p.kill() print("Process is killed.") except OSError: pass except Exception as e: print("Error while terminating subprocess (pid=%i): %s" \ % (p.pid, e)) return out = py3compat.bytes_to_str(out) err = py3compat.bytes_to_str(err) if args.out: self.shell.user_ns[args.out] = out else: sys.stdout.write(out) sys.stdout.flush() if args.err: self.shell.user_ns[args.err] = err else: sys.stderr.write(err) sys.stderr.flush() def _run_script(self, p, cell): """callback for running the script in the background""" p.stdin.write(cell) p.stdin.close() p.wait() @line_magic("killbgscripts") def killbgscripts(self, _nouse_=''): """Kill all BG processes started by %%script and its family.""" self.kill_bg_processes() print("All background processes were killed.") def kill_bg_processes(self): """Kill all BG processes which are still running.""" if not self.bg_processes: return for p in self.bg_processes: if p.poll() is None: try: p.send_signal(signal.SIGINT) except: pass time.sleep(0.1) self._gc_bg_processes() if not self.bg_processes: return for p in self.bg_processes: if p.poll() is None: try: p.terminate() except: pass time.sleep(0.1) self._gc_bg_processes() if not self.bg_processes: return for p in self.bg_processes: if p.poll() is None: try: p.kill() except: pass self._gc_bg_processes() def _gc_bg_processes(self): self.bg_processes = [p for p in self.bg_processes if p.poll() is None]
unnikrishnankgs/va
venv/lib/python3.5/site-packages/IPython/core/magics/script.py
Python
bsd-2-clause
8,835
package org.ontoware.semweb4j.lessons.lesson6; import org.ontoware.jrest.RestParams; import org.ontoware.jrest.RestServer; import org.ontoware.jrest.annotation.RestAddressByParameter; import org.ontoware.jrest.response.RestResponse; /* * implements a RESTful web server with an integer adding restlet */ public class Step1 { private static Step1 instance; //TODO why do we need "Exception" here? /* * initializing RestServer, registering Restlet for integer addition, starting RestServer * look at * http://localhost:8888/rest/__main * http://localhost:8888/rest/add?a=5&b=15 * after running this program. */ public static void main(String[] args) throws Exception { //TODO explain in web we use Jetty here (what is jetty? what is a restful web server?) //TODO understand & explain what this "webroot" is & what so setup elsewhere to get jRest working ... RestServer rs = new RestServer(8888, "./step1"); // default is RestServer rs = new RestServer(5555); // which stores content in "./web" // creating singleton instance: instance = new Step1(); //TODO explain the concept Restlet rs.registerRestlet("add", instance); // to unregister Restlet: rs.unregisterRestlet("step1"); rs.start(); // to stop the RestServer: rs.stop(); //TODO clear confusion about rs.run() & rs.start() } //TODO explain @annotations - list of annotations /* * HTTP GET handler */ public RestResponse get(@RestAddressByParameter("a") int a, @RestAddressByParameter("b") int b) { //TODO explain what a,b are //TODO explain RestResponse //TODO explain RestParams (it contains constants for mimetypes & keys - what are keys??) // setting response to a HTML String containing (a+b): String responseString = "<html><h2>" + (a + b)+"</h2>"; // setting MIME-type to text/HTML: String mimetype = RestParams.MIME_TEXT_HTML; // setting responsecode to 200 (HTTP OK): int responsecode = 200; // ( ',null,null' here means we don't use xslt or css here) RestResponse response = new RestResponse(responseString, mimetype, responsecode, null, null); return response; } }
semweb4j/semweb4j
org.semweb4j.tutorial/src/main/java/org/ontoware/semweb4j/lessons/lesson6/Step1.java
Java
bsd-2-clause
2,151
#include "catch.hpp" #include <osmium/builder/attr.hpp> #include <osmium/memory/buffer.hpp> #include <osmium/tags/matcher.hpp> #include <iterator> #include <string> #include <type_traits> #include <utility> static_assert(std::is_default_constructible<osmium::TagMatcher>::value, "TagMatcher should be default constructible"); static_assert(std::is_copy_constructible<osmium::TagMatcher>::value, "TagMatcher should be copy constructible"); static_assert(std::is_move_constructible<osmium::TagMatcher>::value, "TagMatcher should be move constructible"); static_assert(std::is_copy_assignable<osmium::TagMatcher>::value, "TagMatcher should be copyable"); static_assert(std::is_move_assignable<osmium::TagMatcher>::value, "TagMatcher should be moveable"); TEST_CASE("Tag matcher") { osmium::memory::Buffer buffer{10240}; const auto pos = osmium::builder::add_tag_list(buffer, osmium::builder::attr::_tags({ { "highway", "primary" }, { "name", "Main Street" }, { "source", "GPS" } })); const osmium::TagList& tag_list = buffer.get<osmium::TagList>(pos); SECTION("Matching nothing (default constructor)") { osmium::TagMatcher m{}; REQUIRE_FALSE(m(tag_list)); REQUIRE_FALSE(m(*tag_list.begin())); } SECTION("Matching nothing (bool)") { osmium::TagMatcher m{false}; REQUIRE_FALSE(m(tag_list)); REQUIRE_FALSE(m(*tag_list.begin())); } SECTION("Matching everything") { osmium::TagMatcher m{true}; REQUIRE(m(tag_list)); REQUIRE(m(*tag_list.begin())); REQUIRE(m(*std::next(tag_list.begin()))); REQUIRE(m(*std::next(std::next(tag_list.begin())))); } SECTION("Matching keys only") { osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"}}; REQUIRE(m(tag_list)); REQUIRE(m(*tag_list.begin())); REQUIRE_FALSE(m(*std::next(tag_list.begin()))); } SECTION("Matching keys only with shortcut const char*") { osmium::TagMatcher m{"highway"}; REQUIRE(m(tag_list)); REQUIRE(m(*tag_list.begin())); REQUIRE_FALSE(m(*std::next(tag_list.begin()))); } SECTION("Matching keys only with shortcut std::string") { std::string s{"highway"}; osmium::TagMatcher m{s}; REQUIRE(m(tag_list)); REQUIRE(m(*tag_list.begin())); REQUIRE_FALSE(m(*std::next(tag_list.begin()))); } SECTION("Matching key and value") { osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"}, osmium::StringMatcher::equal{"primary"}}; REQUIRE(m(tag_list)); REQUIRE(m(*tag_list.begin())); REQUIRE_FALSE(m(*std::next(tag_list.begin()))); } SECTION("Matching key and value with shortcut") { osmium::TagMatcher m{"highway", "primary", false}; REQUIRE(m(tag_list)); REQUIRE(m(*tag_list.begin())); REQUIRE_FALSE(m(*std::next(tag_list.begin()))); } SECTION("Matching key and value") { osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"}, osmium::StringMatcher::equal{"secondary"}}; REQUIRE_FALSE(m(tag_list)); } SECTION("Matching key and value inverted") { osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"}, osmium::StringMatcher::equal{"secondary"}, true}; REQUIRE(m(tag_list)); REQUIRE(m(*tag_list.begin())); REQUIRE_FALSE(m(*std::next(tag_list.begin()))); } SECTION("Matching key and value list") { osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"}, osmium::StringMatcher::list{{"primary", "secondary"}}}; REQUIRE(m(tag_list)); REQUIRE(m(*tag_list.begin())); REQUIRE_FALSE(m(*std::next(tag_list.begin()))); } } TEST_CASE("Copy and move tag matcher") { osmium::TagMatcher m1{"highway"}; osmium::TagMatcher c1{true}; osmium::TagMatcher c2{false}; auto m2 = m1; REQUIRE(m2("highway", "residential")); REQUIRE_FALSE(m2("name", "High Street")); c1 = m1; REQUIRE(c1("highway", "residential")); REQUIRE_FALSE(c1("name", "High Street")); auto m3 = std::move(m2); REQUIRE(m3("highway", "residential")); REQUIRE_FALSE(m3("name", "High Street")); c1 = std::move(c2); REQUIRE_FALSE(c1("highway", "residential")); REQUIRE_FALSE(c1("name", "High Street")); }
Project-OSRM/osrm-backend
third_party/libosmium/test/t/tags/test_tag_matcher.cpp
C++
bsd-2-clause
4,540
/////////////////////////////////////////////////////////////////////////////// // Name: tests/controls/itemcontainertest.h // Purpose: wxItemContainer unit test // Author: Steven Lamerton // Created: 2010-06-29 // Copyright: (c) 2010 Steven Lamerton /////////////////////////////////////////////////////////////////////////////// #ifndef _WX_TESTS_CONTROLS_ITEMCONTAINERTEST_H_ #define _WX_TESTS_CONTROLS_ITEMCONTAINERTEST_H_ class ItemContainerTestCase { public: ItemContainerTestCase() { } virtual ~ItemContainerTestCase() { } protected: // this function must be overridden by the derived classes to return the // text entry object we're testing, typically this is done by creating a // control implementing wxItemContainer interface in setUp() virtual method and // just returning it from here virtual wxItemContainer *GetContainer() const = 0; // and this one must be overridden to return the window which implements // wxItemContainer interface -- usually it will return the same pointer as // GetTestEntry(), just as a different type virtual wxWindow *GetContainerWindow() const = 0; // this should be inserted in the derived class CPPUNIT_TEST_SUITE // definition to run all wxItemContainer tests as part of it #define wxITEM_CONTAINER_TESTS() \ CPPUNIT_TEST( Append ); \ CPPUNIT_TEST( Insert ); \ CPPUNIT_TEST( Count ); \ CPPUNIT_TEST( ItemSelection ); \ CPPUNIT_TEST( FindString ); \ CPPUNIT_TEST( ClientData ); \ CPPUNIT_TEST( VoidData ); \ CPPUNIT_TEST( Set ); \ CPPUNIT_TEST( SetSelection ); \ CPPUNIT_TEST( SetString ); \ WXUISIM_TEST( SimSelect ); void Append(); void Insert(); void Count(); void ItemSelection(); void FindString(); void ClientData(); void VoidData(); void Set(); void SetSelection(); void SetString(); virtual void SimSelect(); private: wxDECLARE_NO_COPY_CLASS(ItemContainerTestCase); }; #endif // _WX_TESTS_CONTROLS_ITEMCONTAINERTEST_H_
adouble42/nemesis-current
wxWidgets-3.1.0/tests/controls/itemcontainertest.h
C
bsd-2-clause
2,093
cask "rhinoceros" do version "6.32.20340.21002" sha256 "60108e98e2354a063210b18d046378f96ba4fc0060c332c7524f86c350742750" url "https://files.mcneel.com/rhino/#{version.major}/mac/releases/rhino_#{version}.dmg", verified: "mcneel.com/" name "Rhinoceros" homepage "https://www.rhino3d.com/" livecheck do url "https://files.mcneel.com/rhino/#{version.major}/mac/updates/commercialUpdates.xml" strategy :sparkle, &:version end auto_updates true app "Rhinoceros.app" zap trash: [ "~/Library/Preferences/com.mcneel.rhinoceros.plist", "~/Library/Caches/com.mcneel.rhinoceros", "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.mcneel.rhinoceros.sfl*", ] end
kingthorin/homebrew-cask
Casks/rhinoceros.rb
Ruby
bsd-2-clause
768
package introspect import ( "encoding/xml" "strings" "github.com/godbus/dbus/v5" ) // Call calls org.freedesktop.Introspectable.Introspect on a remote object // and returns the introspection data. func Call(o dbus.BusObject) (*Node, error) { var xmldata string var node Node err := o.Call("org.freedesktop.DBus.Introspectable.Introspect", 0).Store(&xmldata) if err != nil { return nil, err } err = xml.NewDecoder(strings.NewReader(xmldata)).Decode(&node) if err != nil { return nil, err } if node.Name == "" { node.Name = string(o.Path()) } return &node, nil }
godbus/dbus
introspect/call.go
GO
bsd-2-clause
585
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use kartik\date\DatePicker; use yii\web\JsExpression; use yii\widgets\Pjax; use app\models\Maestros; //use kartik\select2\Select2; /* @var $this yii\web\View */ /* @var $nuevo app\models\TblPersonaSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <!--<form class="contact_form" action="#" id="contact_form" runat="server">--> <div id="form1" > <?php $form = ActiveForm::begin(['options' => ['class' => '', ]]); ?> <div> <h3><strong> Mi Proyecto | </strong><span style=" font-size: medium">Datos Generales</span></h3> </div> <div class="col-xs-12 col-sm-7 col-md-12" id="form2" > <div class="form-group field-proyecto-titulo required"> <input type="hidden" value="<?= $proyecto->id?>" id="proyecto-id" name="Proyecto[id]" /> <label for="proyecto-titulo">Título del Proyecto:</label> <input class="form-control" type="text" value="<?= $proyecto->titulo?>" placeholder="Nombre del Proyecto" id="proyecto-titulo" name="Proyecto[titulo]" required/> <!-- required--> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-vigencia required"> <label for="proyecto-vigencia">Vigencia (En Meses):</label> <input class="form-control entero" type="text" id="proyecto-vigencia" value="<?= $proyecto->vigencia?>" placeholder="Vigencia del Proyecto en Meses" name="Proyecto[vigencia]" required/> <!-- required--> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-id_tipo_proyecto required"> <label for="proyecto-id_tipo_proyecto">Invetigación:</label> <select class="form-control" id="proyecto-id_tipo_proyecto" name="Proyecto[id_tipo_proyecto]" > <option value="0">--Seleccione--</option> <?php foreach($tipoInv as $tipoInvs) { ?> <option value="<?= $tipoInvs->id; ?>" <?=($tipoInvs->id == $proyecto->id_tipo_proyecto)?'selected':'' ?> > <?= $tipoInvs->descripcion ?></option>; <?php } ?> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > </div> <div class="clearfix"></div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-id_direccion_linea required"> <label for="proyecto-id_direccion_linea">Dirección en Linea:</label> <select class="form-control" id="proyecto-id_direccion_linea" name="Proyecto[id_direccion_linea]" > <option value="0">--Seleccione--</option> <?php $tipoDireccion = Maestros::find() ->where('id_padre = 21 and estado = 1') ->orderBy('orden') ->all(); foreach($tipoDireccion as $tipoDireccion2) { ?> <option value="<?= $tipoDireccion2->id; ?>" <?=($tipoDireccion2->id == $proyecto->id_direccion_linea)?'selected':'' ?> required> <?= $tipoDireccion2->descripcion ?></option>; <?php } ?> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-id_unidad_ejecutora required"> <label for="proyecto-id_unidad_ejecutora">Unidad Ejecutora:</label> <select class="form-control" id="proyecto-id_unidad_ejecutora" name="Proyecto[id_unidad_ejecutora]" > <option value="0">--Seleccione--</option> <?php $tipoUnidadEj = Maestros::find() ->where('id_padre = 25 and estado = 1') ->orderBy('orden') ->all(); foreach($tipoUnidadEj as $tipoUnidadEj2) { ?> <option value="<?= $tipoUnidadEj2->id; ?>" <?=($tipoUnidadEj2->id == $proyecto->id_unidad_ejecutora)?'selected':'' ?> required> <?= $tipoUnidadEj2->descripcion ?></option>; <?php } ?> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-id_dependencia_inia required"> <label for="proyecto-id_dependencia_inia">Dependencia del INIA :</label> <select class="form-control" name="Proyecto[id_dependencia_inia]" id="proyecto-id_dependencia_inia" > <option value="0">--Seleccione--</option> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-departamento required"> <label for="proyecto-departamento">Departamento:</label> <select class="form-control" onchange="provincia(1)" id="proyecto-departamento" name="Proyecto[departamento][]" > <option value="0">--Departamento--</option> <?php foreach($departamentos as $departamentos2) { ?> <option value="<?= $departamentos2->department_id; ?>" <?=($departamentos2->department_id == substr($proyecto->ubigeo,0,2))?'selected':'' ?> > <?= $departamentos2->department ?></option> <?php } ?> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-provincia required"> <label for="proyecto-provincia">Provincia:</label> <select class="form-control" onchange="distrito(1)" id="proyecto-provincia" name="Proyecto[provincia]" > <option value="0">--Provincia--</option> <?php if ($proyecto->ubigeo) { foreach($provincias as $provincias2) { echo '<option value="'.$provincias2->province_id.'" '.($provincias2->province_id == substr($proyecto->ubigeo,0,4) ? 'selected="selected"' : '' ).'> '.$provincias2->province .'</option>'; } } ?> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-distrito required"> <label for="proyecto-distrito">Distrito:</label> <select class="form-control" id="proyecto-distrito" name="Proyecto[distrito]" > <option value="0">--Distrito--</option> <?php if ($proyecto->ubigeo) { foreach($distritos as $distritos2) { echo '<option value="'.$distritos2->district_id.'" '.($distritos2->district_id == $proyecto->ubigeo ? 'selected="selected"' : '' ).'> '.$distritos2->district .'</option>'; } } ?> </select> </div> </div> <div class="clearfix"></div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-id_programa required"> <label for="proyecto-id_programa">Programa:</label> <select class="form-control" id="proyecto-distrito" name="Proyecto[id_programa]" > <option value="0">--Programa--</option> <?php if ($proyecto->ubigeo) { foreach($programa as $programa2) { echo '<option value="'.$programa2->id.'" '.($programa2->id == $proyecto->id_programa ? 'selected="selected"' : '' ).'> '.$programa2->descripcion .'</option>'; } } ?> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-id_cultivo required"> <label for="proyecto-id_cultivo">Cultivo o Crianza:</label> <select class="form-control" id="proyecto-id_cultivo" name="Proyecto[id_cultivo]" > <option value="0">--Seleccione--</option> <?php $maestro = Maestros::find() ->where('id_padre = 1 and estado = 1') ->orderBy('orden') ->all(); foreach($maestro as $maestros) { ?> <option value="<?= $maestros->id; ?>" <?=($maestros->id == $proyecto->id_cultivo)?'selected':'' ?> > <?= $maestros->descripcion ?></option>; <?php } ?> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-4" > <div class="form-group field-proyecto-id_especie required"> <label for="proyecto-id_especie">Especie:</label> <select class="form-control" id="proyecto-id_especie" name="Proyecto[id_especie]" > <option value="0">--Seleccione--</option> <?php $especie = Maestros::find() ->where('id_padre = 45 and estado = 1') ->orderBy('orden') ->all(); foreach($especie as $especie2) { ?> <option value="<?= $especie2->id; ?>" <?=($especie2->id == $proyecto->id_especie)?'selected':'' ?> > <?= $especie2->descripcion ?></option>; <?php } ?> </select> </div> </div> <!--<div class="clearfix"><h4>Dependencia del INIA que Ejecutara el Proyecto</h4></div> <div class="clearfix"><h4>Nombres y Apellidos del Responsable Técnico del Proyecto</h4></div> <div class="col-xs-12 col-sm-7 col-md-12" > <div class="form-group field-proyecto-nombres required"> <label for="proyecto-nombres">Nombres:</label> <input class="form-control" type="text" value="<?= $responsable->nombres?>" placeholder="Nombres" id="proyecto-nombres" name="Proyecto[nombres]" required/> </div> </div> <div class="col-xs-12 col-sm-7 col-md-12" > <div class="form-group field-proyecto-apellidos required"> <label for="proyecto-apellidos">Apellidos:</label> <input class="form-control" type="text" value="<?= $responsable->apellidos?>" placeholder="Apellidos" id="proyecto-apellidos" name="Proyecto[apellidos]" required/> </div> </div> <div class="col-xs-12 col-sm-7 col-md-6" > <div class="form-group field-proyecto-telefono required"> <label for="proyecto-telefono">Teléfono Fijo:</label> <input class="form-control" type="text" value="<?= $responsable->telefono?>" placeholder="Teléfono Fijo" id="proyecto-telefono" name="Proyecto[telefono]" required/> </div> </div> <div class="col-xs-12 col-sm-7 col-md-6" > <div class="form-group field-proyecto-celular required"> <label for="proyecto-celular">Celular:</label> <input class="form-control" type="text" value="<?= $responsable->celular?>" placeholder="Celular" id="proyecto-celular" name="Proyecto[celular]" required/> </div> </div> <div class="col-xs-12 col-sm-7 col-md-12" > <div class="form-group field-proyecto-correo required"> <label for="proyecto-correo">Correo Electrónico:</label> <input class="form-control" type="text" value="<?= $responsable->correo?>" placeholder="Correo Electrónico" id="proyecto-correo" name="Proyecto[correo]" required/> <span class="form_hint">Formato correcto: "nombre@dominio.com"</span> </div> </div> <div class="clearfix"></div> <div class="clearfix"><h4>Lista de Nombres y Colaboradores Técnicos del Proyecto y Función Técnica</h4></div>--> <div class="col-xs-12 col-sm-7 col-md-12" > <div class="form-group field-proyecto-id_areatematica required"> <label for="proyecto-id_areatematica">Área temática:</label> <select class="form-control" id="proyecto-id_areatematica" name="Proyecto[id_areatematica]" > <option value="0">--Seleccione--</option> <?php $accionTrans = Maestros::find() ->where('id_padre = 10 and estado = 1') ->orderBy('orden') ->all(); foreach($accionTrans as $accionTransv) { ?> <option value="<?= $accionTransv->id; ?>" <?=($accionTransv->id == $proyecto->id_areatematica)?'selected':'' ?> > <?= $accionTransv->descripcion ?></option>; <?php } ?> </select> </div> </div> <div class="col-xs-12 col-sm-7 col-md-12" > <?= \app\widgets\colaboradores\ColaboradoresWidget::widget(['id'=>$proyecto->id]); ?> </div> <div class="clearfix"></div> <br/> <br/> <!-- <div class="clearfix"><h4>Alianza Estratégica establecidas para el Proyecto</h4></div> <div class="col-xs-12 col-sm-7 col-md-12" > <?php // \app\widgets\instituciones\InstitucionesWidget::widget(['proyecto_id'=>$proyecto->id]); ?> </div> <div class="clearfix"></div> <div class="clearfix"><h4>Resumen Ejecutivo del Proyecto</h4></div> <div class="col-xs-12 col-sm-7 col-md-12" > <div class="form-group field-proyecto-resumen_ejecutivo required"> <label for="proyecto-resumen_ejecutivo">Descripción:</label> <textarea class="form-control" type="text" placeholder="..." rows="10" id="proyecto-resumen_ejecutivo" name="Proyecto[resumen_ejecutivo]" required><?= $proyecto->resumen_ejecutivo?></textarea> </div> </div> <div class="clearfix"></div> <div class="clearfix"><h4>Relevancia del Proyecto y Referencias a Resultados Obtenidos en INIA u otras Instituciones</h4></div> <div class="col-xs-12 col-sm-7 col-md-12" > <div class="form-group field-proyecto-relevancia required"> <label for="proyecto-relevancia">Descripción:</label> <textarea class="form-control" type="text" placeholder="..." rows="10" id="proyecto-relevancia" name="Proyecto[relevancia]" required><?= $proyecto->relevancia?></textarea> </div> </div>--> <div class="col-xs-12 col-sm-7 col-md-12" > <button type="submit" id="btnproyecto" class="btn btn-primary pull-right">Guardar</button> </div> <?php ActiveForm::end(); ?> </div> <?php $urlproyectoExiste= Yii::$app->getUrlManager()->createUrl('proyecto/existeproyecto'); $urlresponsable= Yii::$app->getUrlManager()->createUrl('responsable/guardar'); $urlDependencia= Yii::$app->getUrlManager()->createUrl('maestros/dependencia'); $obtenerprovincia = Yii::$app->getUrlManager()->createUrl('proyecto/obtenerprovincia'); $obtenerdistrito = Yii::$app->getUrlManager()->createUrl('proyecto/obtenerdistrito'); ?> <script type="text/javascript"> $(document).ready(function(){ alert("asd"); //$('#form2').find('input, textarea, button, select').attr('disabled','disabled'); $("#proyecto-titulo").disabled = true; var inicialdependencia = <?= $proyecto-> id_dependencia_inia;?>; if (inicialdependencia != '') { var dependencia = $("#proyecto-id_dependencia_inia"); var unidad = $("#proyecto-id_unidad_ejecutora"); if(unidad.val() != '0') { $.ajax({ url: '<?= $urlDependencia ?>', type: 'GET', async: true, data: {unidadejecutora:unidad.val()}, success: function(data){ dependencia.find('option').remove(); dependencia.append(data); $("#proyecto-id_dependencia_inia option[value="+inicialdependencia+"]").attr('selected','selected'); dependencia.prop('disabled', false); } }); } } else { $("#proyecto-id_dependencia_inia").prop('disabled', true); } $("#proyecto-id_unidad_ejecutora").change(function(){ var dependencia = $("#proyecto-id_dependencia_inia"); var unidad = $(this); if($(this).val() != '0') { $.ajax({ url: '<?= $urlDependencia ?>', type: 'GET', async: true, data: {unidadejecutora:unidad.val()}, success: function(data){ dependencia.find('option').remove(); dependencia.append(data); dependencia.prop('disabled', false); } }); } else { dependencia.find('option').remove(); dependencia.append('<option value="0">--Seleccione--</option>'); dependencia.prop('disabled', true); } }); }); function provincia(valor) { var departamento = $('#proyecto-departamento'); var provincia = $('#proyecto-provincia'); var distrito = $('#proyecto-distrito'); if(departamento.val() != '0') { $.ajax({ url: '<?= $obtenerprovincia ?>', type: 'GET', async: true, data: {id:departamento.val()}, success: function(data){ provincia.find('option').remove(); provincia.append(data); provincia.prop('disabled', false); distrito.find('option').remove(); distrito.append('<option value="0">--Seleccione--</option>'); distrito.prop('disabled', true); } }); } else { provincia.find('option').remove(); provincia.append('<option value="0">--Seleccione--</option>'); provincia.prop('disabled', true); distrito.find('option').remove(); distrito.append('<option value="0">--Seleccione--</option>'); distrito.prop('disabled', true); } } function distrito(identificador) { var provincia = $('#proyecto-provincia'); var distrito = $('#proyecto-distrito'); if(provincia.val() != '0') { $.ajax({ url: '<?= $obtenerdistrito ?>', type: 'GET', async: true, data: {id:provincia.val()}, success: function(data){ distrito.find('option').remove(); distrito.append(data); distrito.prop('disabled', false); } }); } else { distrito.find('option').remove(); distrito.append('<option value="0">--Seleccione--</option>'); distrito.prop('disabled', true); } } $("#btnproyecto").click(function( ) { var error=''; if($.trim($('#proyecto-titulo').val())=='') { error=error+'Ingrese Nombre del Proyecto<br>'; $('#proyecto-titulo').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-vigencia').val())=='') { error=error+'Ingrese la Vigencia del Proyecto<br>'; $('#proyecto-vigencia').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-id_tipo_proyecto').val())=='0') { error=error+'Seleccione el Tipo de Investigación<br>'; $('#proyecto-id_tipo_proyecto').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-departamento').val())=='0' || $.trim($('#proyecto-provincia').val())=='0' || $.trim($('#proyecto-distrito').val())=='0') { error=error+'Seleccione Ubigeo<br>'; $('#proyecto-departamento').addClass('has-error'); $('#proyecto-provincia').addClass('has-error'); $('#proyecto-distrito').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-id_direccion_linea').val())=='0') { error=error+'Seleccione la Dirección en Linea<br>'; $('#proyecto-id_direccion_linea').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-id_unidad_ejecutora').val())=='0') { error=error+'Seleccione La Unidad Ejecutora<br>'; $('#proyecto-id_unidad_ejecutora').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-id_dependencia_inia').val())=='0') { error=error+'Seleccione la Dependencia INIA<br>'; $('#proyecto-id_dependencia_inia').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-id_programa').val())=='0') { error=error+'Selecciones el Programa<br>'; $('#proyecto-id_programa').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-id_cultivo').val())=='0') { error=error+'Seleccione el Cultivo o Crianza<br>'; $('#proyecto-id_cultivo').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-id_especie').val())=='0') { error=error+'Seleccione la Especie<br>'; $('#proyecto-id_especie').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-id_areatematica').val())=='0') { error=error+'Selecciones la ÁREA Temática<br>'; $('#proyecto-id_areatematica').addClass('has-error'); //alert('hola'); } /* var colaborador=$('input[name=\'Proyecto[nombresc][]\']').length; for (var i=0; i<colaborador; i++) { if(($('#proyecto-nombresc_'+i).val()=='') || ($('#proyecto-apellidosc_'+i).val()=='') || ($('#proyecto-funcionesc_'+i).val()=='')) { error=error+'Complete todos los Campos del Colaborador #'+(i+1)+' <br>'; // $('.field-proyecto-descripciones_'+i).addClass('has-error'); } }*/ /*if($.trim($('#proyecto-resumen_ejecutivo').val())=='') { error=error+'Ingrese el Resumen Ejecutivo<br>'; $('#proyecto-resumen_ejecutivo').addClass('has-error'); //alert('hola'); } if($.trim($('#proyecto-relevancia').val())=='') { error=error+'Ingrese La Relevancia del Proyecto<br>'; $('#proyecto-relevancia').addClass('has-error'); //alert('hola'); }*/ if(error!='') { $.notify({ message: error },{ type: 'danger', offset: 20, spacing: 10, z_index: 1031, placement: { from: 'top', align: 'right' }, }); return false; } /* var id = $('#proyecto-id').val(); var titulo = $('#proyecto-id').val(); var direccion_linea = $('#proyecto-direccion_linea').val(); var estacion_exp = $('#proyecto-estacion_exp').val(); var sub_estacion_exp = $('#proyecto-sub_estacion_exp').val(); var nombres = $('#responsable-nombres').val(); var apellidos = $('#responsable-apellidos').val(); var telefono = $('#responsable-telefono').val(); var celular = $('#responsable-celular').val(); var correo = $('#responsable-correo').val();*/ /* var validarproyecto=$.ajax({ url: '<? $urlproyecto ?>', type: 'POST', async: false, data: {'Proyecto[id]':id,'Proyecto[titulo]':titulo,'Proyecto[direccion_linea]':direccion_linea,'Proyecto[estacion_exp]':estacion_exp,'Proyecto[sub_estacion_exp]':sub_estacion_exp}, success: function(data){ } }); */ return true; }); </script>
lhuapaya/pnia
views/-proyecto/datosgenerales.php
PHP
bsd-3-clause
27,697
#!/bin/bash _term() { echo "Caught TERM signal" kill -TERM "$SERVICE" kill -TERM "$KBFS" exit 0 } trap _term SIGTERM if [ -z "$KEYBASE_TEST_ROOT_CERT_PEM" ]; then export KEYBASE_TEST_ROOT_CERT_PEM="$(echo $KEYBASE_TEST_ROOT_CERT_PEM_B64 | base64 -d)"; fi if [ -z "$KBFS_METADATA_VERSION" ]; then export KBFS_METADATA_VERSION=4 fi echo "Using KBFS metadata version $KBFS_METADATA_VERSION" if [ -f kbfs_revision ]; then echo "Running KBFS Docker with KBFS revision $(cat kbfs_revision)" fi if [ -f client_revision ]; then echo "Client revision $(cat client_revision)" fi git config --global user.email "you@example.com" git config --global user.name "Your Name" # Journaling is turned off by default for all tests, since some tests # depend on sync semantics. journalFlag="-enable-journal=${KBFS_JOURNAL_ENABLE:-false}" keybase -debug service & SERVICE=$! KEYBASE_DEBUG=1 kbfsfuse -debug -disk-cache-mode=local "$journalFlag" -mdserver $MDSERVER_ADDR -bserver $BSERVER_ADDR -localuser= -md-version $KBFS_METADATA_VERSION -log-to-file /keybase & KBFS=$! wait "$SERVICE" wait "$KBFS"
keybase/kbfs
kbfsfuse/kbfsfuse.sh
Shell
bsd-3-clause
1,119
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Wed Mar 02 16:46:13 EST 2011 --> <TITLE> Uses of Class gov.nih.nci.cabig.caaers.web.rule.notification.EditReportDefinitionController </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class gov.nih.nci.cabig.caaers.web.rule.notification.EditReportDefinitionController"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../gov/nih/nci/cabig/caaers/web/rule/notification/EditReportDefinitionController.html" title="class in gov.nih.nci.cabig.caaers.web.rule.notification"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../../index.html?gov/nih/nci/cabig/caaers/web/rule/notification/class-use/EditReportDefinitionController.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="EditReportDefinitionController.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>gov.nih.nci.cabig.caaers.web.rule.notification.EditReportDefinitionController</B></H2> </CENTER> No usage of gov.nih.nci.cabig.caaers.web.rule.notification.EditReportDefinitionController <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../gov/nih/nci/cabig/caaers/web/rule/notification/EditReportDefinitionController.html" title="class in gov.nih.nci.cabig.caaers.web.rule.notification"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../../index.html?gov/nih/nci/cabig/caaers/web/rule/notification/class-use/EditReportDefinitionController.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="EditReportDefinitionController.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
CBIIT/caaers
caAERS/software/docs/gov/nih/nci/cabig/caaers/web/rule/notification/class-use/EditReportDefinitionController.html
HTML
bsd-3-clause
6,544
# flake8: NOQA from . import datasets from . import evaluations from . import extensions from . import models from . import utils
start-jsk/jsk_apc
demos/grasp_fusion/grasp_fusion_lib/contrib/grasp_fusion/__init__.py
Python
bsd-3-clause
131
/* * Check decoding of migrate_pages syscall. * * Copyright (c) 2016 Dmitry V. Levin <ldv@altlinux.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tests.h" #include <asm/unistd.h> #ifdef __NR_migrate_pages # include <stdio.h> # include <unistd.h> int main(void) { const long pid = (long) 0xfacefeedffffffff; long rc = syscall(__NR_migrate_pages, pid, 0, 0, 0); printf("migrate_pages(%d, 0, NULL, NULL) = %ld %s (%m)\n", (int) pid, rc, errno2name()); puts("+++ exited with 0 +++"); return 0; } #else SKIP_MAIN_UNDEFINED("__NR_migrate_pages") #endif
cuviper/strace
tests/migrate_pages.c
C
bsd-3-clause
1,969
/* * Copyright (c) 2009, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ package org.contikios.cooja.dialogs; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.regex.Matcher; import javax.swing.Action; import org.apache.log4j.Logger; import org.contikios.cooja.Cooja; import org.contikios.cooja.MoteType; import org.contikios.cooja.MoteType.MoteTypeCreationException; import org.contikios.cooja.contikimote.ContikiMoteType; /** * Contiki compiler library. * Uses notion of Contiki platforms to compile a Contiki firmware. * * @author Fredrik Osterlind */ public class CompileContiki { private static Logger logger = Logger.getLogger(CompileContiki.class); /** * Executes a Contiki compilation command. * * @param command Command * @param env (Optional) Environment. May be null. * @param outputFile Expected output. May be null. * @param directory Directory in which to execute command * @param onSuccess Action called if compilation succeeds * @param onFailure Action called if compilation fails * @param compilationOutput Is written both std and err process output * @param synchronous If true, method blocks until process completes * @return Sub-process if called asynchronously * @throws Exception If process returns error, or outputFile does not exist */ public static Process compile( final String command, final String[] env, final File outputFile, final File directory, final Action onSuccess, final Action onFailure, final MessageList compilationOutput, boolean synchronous) throws Exception { Pattern p = Pattern.compile("([^\\s\"']+|\"[^\"]*\"|'[^']*')"); Matcher m = p.matcher(command); ArrayList<String> commandList = new ArrayList<String>(); while(m.find()) { String arg = m.group(); if (arg.length() > 1 && (arg.charAt(0) == '"' || arg.charAt(0) == '\'')) { arg = arg.substring(1, arg.length() - 1); } commandList.add(arg); } return compile(commandList.toArray(new String[commandList.size()]), env, outputFile, directory, onSuccess, onFailure, compilationOutput, synchronous); } /** * Executes a Contiki compilation command. * * @param command Command * @param env (Optional) Environment. May be null. * @param outputFile Expected output. May be null. * @param directory Directory in which to execute command * @param onSuccess Action called if compilation succeeds * @param onFailure Action called if compilation fails * @param messageDialog Is written both std and err process output * @param synchronous If true, method blocks until process completes * @return Sub-process if called asynchronously * @throws Exception If process returns error, or outputFile does not exist */ public static Process compile( final String command[], final String[] env, final File outputFile, final File directory, final Action onSuccess, final Action onFailure, final MessageList compilationOutput, boolean synchronous) throws Exception { /* TODO Fix me */ final MessageList messageDialog; if (compilationOutput == null) { messageDialog = new MessageListUI(); } else { messageDialog = compilationOutput; } { String cmd = ""; for (String c: command) { cmd += c + " "; } logger.info("> " + cmd); messageDialog.addMessage("", MessageListUI.NORMAL); messageDialog.addMessage("> " + cmd, MessageListUI.NORMAL); } final Process compileProcess; try { compileProcess = Runtime.getRuntime().exec(command, env, directory); final BufferedReader processNormal = new BufferedReader( new InputStreamReader(compileProcess.getInputStream())); final BufferedReader processError = new BufferedReader( new InputStreamReader(compileProcess.getErrorStream())); if (outputFile != null) { if (outputFile.exists()) { outputFile.delete(); } if (outputFile.exists()) { messageDialog.addMessage("Error when deleting old " + outputFile.getName(), MessageList.ERROR); if (onFailure != null) { onFailure.actionPerformed(null); } throw new MoteTypeCreationException("Error when deleting old " + outputFile.getName()); } } Thread readInput = new Thread(new Runnable() { public void run() { try { String readLine; while ((readLine = processNormal.readLine()) != null) { if (messageDialog != null) { messageDialog.addMessage(readLine, MessageListUI.NORMAL); } } } catch (IOException e) { logger.warn("Error while reading from process"); } } }, "read input stream thread"); Thread readError = new Thread(new Runnable() { public void run() { try { String readLine; while ((readLine = processError.readLine()) != null) { if (messageDialog != null) { messageDialog.addMessage(readLine, MessageList.ERROR); } } } catch (IOException e) { logger.warn("Error while reading from process"); } } }, "read error stream thread"); final MoteTypeCreationException syncException = new MoteTypeCreationException(""); Thread handleCompilationResultThread = new Thread(new Runnable() { public void run() { /* Wait for compilation to end */ try { compileProcess.waitFor(); } catch (Exception e) { messageDialog.addMessage(e.getMessage(), MessageList.ERROR); syncException.setCompilationOutput(new MessageListUI()); syncException.fillInStackTrace(); return; } /* Check return value */ if (compileProcess.exitValue() != 0) { messageDialog.addMessage("Process returned error code " + compileProcess.exitValue(), MessageList.ERROR); if (onFailure != null) { onFailure.actionPerformed(null); } syncException.setCompilationOutput(new MessageListUI()); syncException.fillInStackTrace(); return; } if (outputFile == null) { /* No firmware to generate: OK */ if (onSuccess != null) { onSuccess.actionPerformed(null); } return; } if (!outputFile.exists()) { messageDialog.addMessage("No firmware file: " + outputFile, MessageList.ERROR); if (onFailure != null) { onFailure.actionPerformed(null); } syncException.setCompilationOutput(new MessageListUI()); syncException.fillInStackTrace(); return; } messageDialog.addMessage("", MessageListUI.NORMAL); messageDialog.addMessage("Compilation succeded", MessageListUI.NORMAL); if (onSuccess != null) { onSuccess.actionPerformed(null); } } }, "handle compilation results"); readInput.start(); readError.start(); handleCompilationResultThread.start(); if (synchronous) { try { handleCompilationResultThread.join(); } catch (Exception e) { /* Make sure process has exited */ compileProcess.destroy(); String msg = e.getMessage(); if (e instanceof InterruptedException) { msg = "Aborted by user"; } throw (MoteTypeCreationException) new MoteTypeCreationException( "Compilation error: " + msg).initCause(e); } /* Detect error manually */ if (syncException.hasCompilationOutput()) { throw (MoteTypeCreationException) new MoteTypeCreationException( "Bad return value").initCause(syncException); } } } catch (IOException ex) { if (onFailure != null) { onFailure.actionPerformed(null); } throw (MoteTypeCreationException) new MoteTypeCreationException( "Compilation error: " + ex.getMessage()).initCause(ex); } return compileProcess; } /** * Generate JNI enabled Contiki main source file. * Used by Contiki Mote Type. * * @param sourceFile Source file to generate * @param javaClass JNI Java class * @param sensors Contiki sensors * @param coreInterfaces Core interfaces * @throws Exception At error * * @see ContikiMoteType */ public static void generateSourceFile( File sourceFile, String javaClass, String[] sensors, String[] coreInterfaces ) throws Exception { if (sourceFile == null) { throw new Exception("No output source file defined"); } if (javaClass == null) { throw new Exception("No Java class defined"); } if (sensors == null) { throw new Exception("No Contiki sensors defined"); } if (coreInterfaces == null) { throw new Exception("No Contiki dependencies defined"); } /* SENSORS */ String sensorString = ""; String externSensorDefs = ""; for (String sensor : sensors) { if (!sensorString.equals("")) { sensorString += ", "; } sensorString += "&" + sensor; externSensorDefs += "extern const struct sensors_sensor " + sensor + ";\n"; } if (!sensorString.equals("")) { sensorString = "SENSORS(" + sensorString + ");"; } else { sensorString = "SENSORS(NULL);"; } /* CORE INTERFACES */ String interfaceString = ""; String externInterfaceDefs = ""; for (String coreInterface : coreInterfaces) { if (!interfaceString.equals("")) { interfaceString += ", "; } interfaceString += "&" + coreInterface; externInterfaceDefs += "SIM_INTERFACE_NAME(" + coreInterface + ");\n"; } if (!interfaceString.equals("")) { interfaceString = "SIM_INTERFACES(" + interfaceString + ");"; } else { interfaceString = "SIM_INTERFACES(NULL);"; } /* If directory does not exist, try creating it */ if (!sourceFile.getParentFile().exists()) { logger.info("Creating source file directory: " + sourceFile.getParentFile().getAbsolutePath()); sourceFile.getParentFile().mkdir(); } /* GENERATE SOURCE FILE */ BufferedReader templateReader = null; BufferedWriter sourceFileWriter = null; try { Reader reader; String mainTemplate = Cooja.getExternalToolsSetting("CONTIKI_MAIN_TEMPLATE_FILENAME"); if ((new File(mainTemplate)).exists()) { reader = new FileReader(mainTemplate); } else { /* Try JAR, or fail */ InputStream input = CompileContiki.class.getResourceAsStream('/' + mainTemplate); if (input == null) { throw new FileNotFoundException(mainTemplate + " not found"); } reader = new InputStreamReader(input); } templateReader = new BufferedReader(reader); sourceFileWriter = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(sourceFile))); // Replace special fields in template String line; while ((line = templateReader.readLine()) != null) { line = line.replaceFirst("\\[SENSOR_DEFINITIONS\\]", externSensorDefs); line = line.replaceFirst("\\[SENSOR_ARRAY\\]", sensorString); line = line.replaceFirst("\\[INTERFACE_DEFINITIONS\\]", externInterfaceDefs); line = line.replaceFirst("\\[INTERFACE_ARRAY\\]", interfaceString); line = line.replaceFirst("\\[CLASS_NAME\\]", javaClass); sourceFileWriter.write(line + "\n"); } sourceFileWriter.close(); templateReader.close(); } catch (Exception e) { try { if (templateReader != null) { templateReader.close(); } if (sourceFileWriter != null) { sourceFileWriter.close(); } } catch (Exception e2) { } // Forward exception throw e; } if (!sourceFile.exists()) { throw new Exception("Output source file does not exist: " + sourceFile.getAbsolutePath()); } logger.info("Generated Contiki main source: " + sourceFile.getName()); } /** * Generate compiler environment using external tools settings. * Used by Contiki Mote Type. * * @param identifier Mote type identifier, "mtype123" * @param contikiApp Contiki application source, "hello-world.c" * @param mapFile Output map file, "mtype123.map" * @param libFile Output JNI library, "mtype123.cooja" * @param archiveFile Output archive, "mtype123.a" * @param javaClass Java JNI library class, "Lib4" * @return Compilation environment * @throws Exception At errors */ public static String[][] createCompilationEnvironment( String identifier, File contikiApp, File mapFile, File libFile, File archiveFile, String javaClass) throws Exception { if (identifier == null) { throw new Exception("No identifier specified"); } if (contikiApp == null) { throw new Exception("No Contiki application specified"); } if (mapFile == null) { throw new Exception("No map file specified"); } if (libFile == null) { throw new Exception("No library output specified"); } if (archiveFile == null) { throw new Exception("No archive file specified"); } if (javaClass == null) { throw new Exception("No Java library class name specified"); } boolean includeSymbols = false; /* TODO */ /* Fetch configuration from external tools */ String link1 = Cooja.getExternalToolsSetting("LINK_COMMAND_1", ""); String link2 = Cooja.getExternalToolsSetting("LINK_COMMAND_2", ""); String ar1 = Cooja.getExternalToolsSetting("AR_COMMAND_1", ""); String ar2 = Cooja.getExternalToolsSetting("AR_COMMAND_2", ""); String ccFlags = Cooja.getExternalToolsSetting("COMPILER_ARGS", ""); /* Replace MAPFILE variable */ link1 = link1.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName()); link2 = link2.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName()); ar1 = ar1.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName()); ar2 = ar2.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName()); ccFlags = ccFlags.replace("$(MAPFILE)", "obj_cooja/" + mapFile.getName()); /* Replace LIBFILE variable */ link1 = link1.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName()); link2 = link2.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName()); ar1 = ar1.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName()); ar2 = ar2.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName()); ccFlags = ccFlags.replace("$(LIBFILE)", "obj_cooja/" + libFile.getName()); /* Replace ARFILE variable */ link1 = link1.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName()); link2 = link2.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName()); ar1 = ar1.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName()); ar2 = ar2.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName()); ccFlags = ccFlags.replace("$(ARFILE)", "obj_cooja/" + archiveFile.getName()); /* Replace JAVA_HOME variable */ String javaHome = System.getenv().get("JAVA_HOME"); if (javaHome == null) { javaHome = ""; } link1 = link1.replace("$(JAVA_HOME)", javaHome); link2 = link2.replace("$(JAVA_HOME)", javaHome); ar1 = ar1.replace("$(JAVA_HOME)", javaHome); ar2 = ar2.replace("$(JAVA_HOME)", javaHome); ccFlags = ccFlags.replace("$(JAVA_HOME)", javaHome); /* Strip away contiki application .c extension */ String contikiAppNoExtension = contikiApp.getName().substring(0, contikiApp.getName().length()-2); /* Create environment */ ArrayList<String[]> env = new ArrayList<String[]>(); env.add(new String[] { "LIBNAME", identifier }); env.add(new String[] { "CLASSNAME", javaClass }); env.add(new String[] { "CONTIKI_APP", contikiAppNoExtension }); env.add(new String[] { "COOJA_SOURCEDIRS", "" }); env.add(new String[] { "COOJA_SOURCEFILES", "" }); env.add(new String[] { "CC", Cooja.getExternalToolsSetting("PATH_C_COMPILER") }); env.add(new String[] { "OBJCOPY", Cooja.getExternalToolsSetting("PATH_OBJCOPY") }); env.add(new String[] { "EXTRA_CC_ARGS", ccFlags }); env.add(new String[] { "LD", Cooja.getExternalToolsSetting("PATH_LINKER") }); env.add(new String[] { "LINK_COMMAND_1", link1 }); env.add(new String[] { "LINK_COMMAND_2", link2 }); env.add(new String[] { "AR", Cooja.getExternalToolsSetting("PATH_AR") }); env.add(new String[] { "AR_COMMAND_1", ar1 }); env.add(new String[] { "AR_COMMAND_2", ar2 }); env.add(new String[] { "SYMBOLS", includeSymbols?"1":"" }); env.add(new String[] { "PATH", System.getenv("PATH") }); return env.toArray(new String[0][0]); } public static void redefineCOOJASources(MoteType moteType, String[][] env) { if (moteType == null || env == null) { return; } /* Check whether cooja projects include additional sources */ String[] coojaSources = moteType.getConfig().getStringArrayValue(ContikiMoteType.class, "C_SOURCES"); if (coojaSources == null) { return; } String sources = ""; String dirs = ""; for (String s: coojaSources) { if (s.trim().isEmpty()) { continue; } File p = moteType.getConfig().getUserProjectDefining(ContikiMoteType.class, "C_SOURCES", s); if (p == null) { logger.warn("Project defining C_SOURCES$" + s + " not found"); continue; } /* Redefine sources. TODO Move to createCompilationEnvironment. */ sources += s + " "; dirs += p.getPath() + " "; /* XXX Cygwin specific directory style */ if (dirs.contains("C:\\")) { dirs += p.getPath().replace("C:\\", "/cygdrive/c/") + " "; } } if (!sources.trim().isEmpty()) { for (int i=0; i < env.length; i++) { if (env[i][0].equals("COOJA_SOURCEFILES")) { env[i][1] = sources; break; } } } if (!dirs.trim().isEmpty()) { for (int i=0; i < env.length; i++) { if (env[i][0].equals("COOJA_SOURCEDIRS")) { env[i][1] = dirs.replace("\\", "/"); break; } } } } }
miarcompanies/sdn-wise-contiki
contiki/tools/cooja/java/org/contikios/cooja/dialogs/CompileContiki.java
Java
bsd-3-clause
20,398
/******************************************************************************* * Copyright (C) 2015 Brocade Communications Systems, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * https://github.com/brocade/vTM-eclipse/LICENSE * This software is distributed "AS IS". * * Contributors: * Brocade Communications Systems - Main Implementation ******************************************************************************/ package com.zeus.eclipsePlugin.project.operations; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.ui.WorkbenchException; import org.eclipse.ui.actions.WorkspaceModifyOperation; import com.zeus.eclipsePlugin.ZLang; import com.zeus.eclipsePlugin.model.ModelException; import com.zeus.eclipsePlugin.model.ZXTM; import com.zeus.eclipsePlugin.swt.EmptyMonitor; /** * Operation that creates a new empty rule. */ public class NewRuleOp extends WorkspaceModifyOperation { private ZXTM zxtm; private String name; /** * Setup the new rule operation with the specified destination ZXTM and rule * name. * @param zxtm The ZXTM to add the rule to. * @param name The name of the new rule. */ public NewRuleOp( ZXTM zxtm, String name ) { this.zxtm = zxtm; this.name = name; } /** * Creates the new rule on the ZXTM. */ /* Override */ protected void execute( IProgressMonitor monitor ) throws CoreException, InvocationTargetException, InterruptedException { if( monitor == null ) monitor = new EmptyMonitor(); monitor.beginTask( ZLang.bind( ZLang.ZL_AddingNewRuleTo, zxtm ), 1 ); monitor.subTask( "" ); try { zxtm.addRule( name ); } catch( ModelException e ) { throw new WorkbenchException( e.getLocalizedMessage(), e ); } monitor.worked( 1 ); monitor.done(); } }
brocade/vTM-eclipse
plugin/src/com/zeus/eclipsePlugin/project/operations/NewRuleOp.java
Java
bsd-3-clause
2,149
<?php /** * TOP API: taobao.tmc.messages.produce request * * @author auto create * @since 1.0, 2016.01.29 */ class TmcMessagesProduceRequest { /** * tmc消息列表, 最多50条,元素结构与taobao.tmc.message.produce一致,用json表示的消息列表。例如:[{"content": "{\"tid\":1234554321,\"status\":\"X_LOGISTICS_PRINTED\",\"action_time\":\"2014-08-08 18:24:00\",\"seller_nick\": \"向阳aa\",\"operator\":\"小张\"}","topic": "taobao_jds_TradeTrace"},{"content": "{\"tid\":1234554321,\"status\":\"X_LOGISTICS_PRINTED\",\"action_time\":\"2014-08-08 18:24:00\",\"seller_nick\": \"向阳aa\",\"operator\":\"小张\"}","topic": "taobao_jds_TradeTrace"}] **/ private $messages; private $apiParas = array(); public function setMessages($messages) { $this->messages = $messages; $this->apiParas["messages"] = $messages; } public function getMessages() { return $this->messages; } public function getApiMethodName() { return "taobao.tmc.messages.produce"; } public function getApiParas() { return $this->apiParas; } public function check() { } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
jasonzhangxian/scanner
common/components/topsdk/top/request/TmcMessagesProduceRequest.php
PHP
bsd-3-clause
1,222
package com.oracle.xmlns.apps.crmcommon.activities.activitiesservice._transient.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.oracle.xmlns.apps.crmcommon.activities.activitiesservice.TransientAppointment; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="result" type="{http://xmlns.oracle.com/apps/crmCommon/activities/activitiesService/}TransientAppointment"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "result" }) @XmlRootElement(name = "mergeAppointmentAsyncResponse") public class MergeAppointmentAsyncResponse { @XmlElement(required = true) protected TransientAppointment result; /** * Gets the value of the result property. * * @return * possible object is * {@link TransientAppointment } * */ public TransientAppointment getResult() { return result; } /** * Sets the value of the result property. * * @param value * allowed object is * {@link TransientAppointment } * */ public void setResult(TransientAppointment value) { this.result = value; } }
dushmis/Oracle-Cloud
PaaS_SaaS_Accelerator_RESTFulFacade/FusionProxy_ActivityAppointmentService/src/com/oracle/xmlns/apps/crmcommon/activities/activitiesservice/_transient/types/MergeAppointmentAsyncResponse.java
Java
bsd-3-clause
1,815
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage App * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\GData\App; /** * Concrete class to use a file handle as an attachment within a MediaEntry. * * @uses \Zend\GData\App\IOException * @uses \Zend\Gdata\App\MediaData * @category Zend * @package Zend_Gdata * @subpackage App * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class MediaFileSource extends BaseMediaSource { /** * The filename which is represented * * @var string */ protected $_filename = null; /** * The content type for the file attached (example image/png) * * @var string */ protected $_contentType = null; /** * Create a new \Zend\Gdata\App\MediaFileSource object. * * @param string $filename The name of the file to read from. */ public function __construct($filename) { $this->setFilename($filename); } /** * Return the MIME multipart representation of this MediaEntry. * * @return string * @throws \Zend\GData\App\IOException */ public function encode() { if ($this->getFilename() !== null && is_readable($this->getFilename())) { // Retrieves the file, using the include path $fileHandle = fopen($this->getFilename(), 'r', true); $result = fread($fileHandle, filesize($this->getFilename())); if ($result === false) { throw new IOException("Error reading file - " . $this->getFilename() . '. Read failed.'); } fclose($fileHandle); return $result; } else { throw new IOException("Error reading file - " . $this->getFilename() . '. File is not readable.'); } } /** * Get the filename associated with this reader. * * @return string */ public function getFilename() { return $this->_filename; } /** * Set the filename which is to be read. * * @param string $value The desired file handle. * @return \Zend\GData\App\MediaFileSource Provides a fluent interface. */ public function setFilename($value) { $this->_filename = $value; return $this; } /** * The content type for the file attached (example image/png) * * @return string The content type */ public function getContentType() { return $this->_contentType; } /** * Set the content type for the file attached (example image/png) * * @param string $value The content type * @return \Zend\GData\App\MediaFileSource Provides a fluent interface */ public function setContentType($value) { $this->_contentType = $value; return $this; } /** * Alias for getFilename(). * * @return string */ public function __toString() { return $this->getFilename(); } }
magicobject/zf2
library/Zend/GData/App/MediaFileSource.php
PHP
bsd-3-clause
3,784
'use strict'; const test = require('tape'), routes = require('../lib/app/routes.js'); test('Routes tests', t => { t.plan(2); t.test('should use room from params for route redir', st => { st.plan(4); const query = { room: 'random' }, redir = routes.findRedirect(query), url = 'https://gitter.im/' + query.room; st.ok(redir.room, 'route has a room'); st.ok(redir.org, 'route has an org'); st.ok(redir.url, 'route has a url'); st.equal(redir.url, url, 'route url is correct'); st.end(); }); t.test('should find DM room go URI', st => { st.plan(3); const query = { room: 'bothelp' }, redir = routes.findRedirect(query), url = 'https://gitter.im/' + query.room; st.ok(redir.room, 'route has a room'); st.ok(redir.url, 'route has a url'); st.equal(redir.url, url, 'route url is correct'); st.end(); }); });
dhcodes/camperbot
test/routes.spec.js
JavaScript
bsd-3-clause
915
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=0;"> <meta name="apple-mobile-web-app-capable" content="yes"> <title>Tableviews 1</title> <link rel="stylesheet" href="chui/chui.css"> <script src="chui/chocolatechip.js" type="text/javascript"></script> <script src="chui/chui.js" type="text/javascript"></script> <script type="text/javascript"> $.ready(function() { }); </script> </head> <body> <app> <view id="main" ui-background-style="striped" ui-navigation-status="current"> <navbar> <h1>Tableview</h1> </navbar> <subview ui-associations="withNavBar"> <scrollpanel> <tableview> <tablecell> <celltitle>People</celltitle> </tablecell> <tablecell> <celltitle>Places</celltitle> </tablecell> <tablecell> <celltitle>Things</celltitle> </tablecell> <tablecell> <celltitle>Animals</celltitle> </tablecell> <tablecell> <celltitle>Food</celltitle> </tablecell> <tablefooter> A quick summary about all of the items in this list. </tablefooter> </tableview> </scrollpanel> </subview> </view> </app> </body> </html>
rbiggs/chocolatechip-ui.com
downloads/examples/tableview-with-tablefooter.html
HTML
bsd-3-clause
1,318
<?php /** * PHPFrame/Mapper/SQLPersistenceFactory.php * * PHP version 5 * * @category PHPFrame * @package Mapper * @author Lupo Montero <lupo@e-noise.com> * @copyright 2010 The PHPFrame Group * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @link http://github.com/PHPFrame/PHPFrame */ /** * SQL Persistence Factory Class * * @category PHPFrame * @package Mapper * @author Lupo Montero <lupo@e-noise.com> * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @link http://github.com/PHPFrame/PHPFrame * @since 1.0 */ class PHPFrame_SQLPersistenceFactory extends PHPFrame_PersistenceFactory { private $_db; /** * Constructor * * @param string $target_class The target class for this factory. * @param string $table_name The table name the target class is * mapped to. * @param PHPFrame_Database $db Reference to the databse object. * @param string $type_column [Optional] Name of column storing * the subtype if any. When storing * subtypes in the same table the * subtype class name needs to be * stored in a column in order to * instantiate the correct objects * when retrievin data from storage. * * @return void * @since 1.0 */ public function __construct( $target_class, $table_name, PHPFrame_Database $db, $type_column=null ) { parent::__construct($target_class, $table_name, $type_column); $this->_db = $db; } /** * Get object assembler * * @return PHPFrame_PersistentObjectAssembler * @since 1.0 */ public function getAssembler() { return new PHPFrame_SQLPersistentObjectAssembler($this); } /** * Create a new IdObject to work with the target class * * @return PHPFrame_IdObject * @since 1.0 */ public function getIdObject() { $options = array("select"=>"*", "from"=>$this->getTableName()); //TODO: This line has been added to void using the PHPFrame_MySQLIdObject // as it is breaking code in existing PHPFrame based apps. return new PHPFrame_SQLIdObject($options); if ($this->getDB()->isMySQL()){ return new PHPFrame_MySQLIdObject($options); } else { return new PHPFrame_SQLIdObject($options); } } /** * Get reference to database object. * * @return PHPFrame_Database * @since 1.0 */ public function getDB() { return $this->_db; } }
PHPFrame/PHPFrame
src/PHPFrame/Mapper/SQLPersistenceFactory.php
PHP
bsd-3-clause
2,946
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace common\filters; use yii\base\Component; use yii\base\Action; use yii\web\User; use yii\web\Request; use yii\web\Controller; /** * This class represents an access rule defined by the [[AccessControl]] action filter * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class AccessRule extends Component { /** * @var boolean whether this is an 'allow' rule or 'deny' rule. */ public $allow; /** * @var array list of action IDs that this rule applies to. The comparison is case-sensitive. * If not set or empty, it means this rule applies to all actions. */ public $actions; /** * @var array list of controller IDs that this rule applies to. The comparison is case-sensitive. * If not set or empty, it means this rule applies to all controllers. */ public $controllers; /** * @var array list of roles that this rule applies to. Two special roles are recognized, and * they are checked via [[User::isGuest]]: * * - `?`: matches a guest user (not authenticated yet) * - `@`: matches an authenticated user * * Using other role names requires RBAC (Role-Based Access Control), and * [[User::can()]] will be called. * * If this property is not set or empty, it means this rule applies to all roles. */ public $roles; /** * @var array list of user IP addresses that this rule applies to. An IP address * can contain the wildcard `*` at the end so that it matches IP addresses with the same prefix. * For example, '192.168.*' matches all IP addresses in the segment '192.168.'. * If not set or empty, it means this rule applies to all IP addresses. * @see Request::userIP */ public $ips; /** * @var array list of request methods (e.g. `GET`, `POST`) that this rule applies to. * The request methods must be specified in uppercase. * If not set or empty, it means this rule applies to all request methods. * @see \yii\web\Request::method */ public $verbs; /** * @var callable a callback that will be called to determine if the rule should be applied. * The signature of the callback should be as follows: * * ~~~ * function ($rule, $action) * ~~~ * * where `$rule` is this rule, and `$action` is the current [[Action|action]] object. * The callback should return a boolean value indicating whether this rule should be applied. */ public $matchCallback; /** * @var callable a callback that will be called if this rule determines the access to * the current action should be denied. If not set, the behavior will be determined by * [[AccessControl]]. * * The signature of the callback should be as follows: * * ~~~ * function ($rule, $action) * ~~~ * * where `$rule` is this rule, and `$action` is the current [[Action|action]] object. */ public $denyCallback; /** * Checks whether the Web user is allowed to perform the specified action. * @param Action $action the action to be performed * @param User $user the user object * @param Request $request * @return boolean|null true if the user is allowed, false if the user is denied, null if the rule does not apply to the user */ public function allows($action, $user, $request) { if ($this->matchAction($action) && $this->matchRole($user) && $this->matchIP($request->getUserIP()) && $this->matchVerb($request->getMethod()) && $this->matchController($action->controller) && $this->matchCustom($action) ) { return $this->allow ? true : false; } else { return null; } } /** * @param Action $action the action * @return boolean whether the rule applies to the action */ protected function matchAction($action) { return empty($this->actions) || in_array($action->id, $this->actions, true); } /** * @param Controller $controller the controller * @return boolean whether the rule applies to the controller */ protected function matchController($controller) { return empty($this->controllers) || in_array($controller->uniqueId, $this->controllers, true); } /** * @param User $user the user object * @return boolean whether the rule applies to the role */ protected function matchRole($user) { if (empty($this->roles)) { return true; } foreach ($this->roles as $role) { if ($role === '?') { if ($user->getIsGuest()) { return true; } } elseif ($role === '@') { if (!$user->getIsGuest()) { return true; } } elseif ($user->can($role)) { return true; } } return false; } /** * @param string $ip the IP address * @return boolean whether the rule applies to the IP address */ protected function matchIP($ip) { if (empty($this->ips)) { return true; } foreach ($this->ips as $rule) { if ($rule === '*' || $rule === $ip || (($pos = strpos($rule, '*')) !== false && !strncmp($ip, $rule, $pos))) { return true; } } return false; } /** * @param string $verb the request method * @return boolean whether the rule applies to the request */ protected function matchVerb($verb) { return empty($this->verbs) || in_array($verb, $this->verbs, true); } /** * @param Action $action the action to be performed * @return boolean whether the rule should be applied */ protected function matchCustom($action) { return empty($this->matchCallback) || call_user_func($this->matchCallback, $this, $action); } }
rajanishtimes/basicyii
common/filters/AccessRule.php
PHP
bsd-3-clause
6,212
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe UserAcknowledgementsHelper do #Delete this example and add some real ones or delete this file it "should be included in the object returned by #helper" do included_modules = (class << helper; self; end).send :included_modules included_modules.should include(UserAcknowledgementsHelper) end end
camelpunch/simply_agile
spec/helpers/user_acknowledgements_helper_spec.rb
Ruby
bsd-3-clause
391
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__char_environment_ofstream_16.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-16.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: environment Read input from an environment variable * GoodSource: Use a fixed file name * Sink: ofstream * BadSink : Open the file named in data using ofstream::open() * Flow Variant: 16 Control flow: while(1) * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH "c:\\temp\\" #else #include <wchar.h> #define BASEPATH "/tmp/" #endif #define ENV_VARIABLE "ADD" #ifdef _WIN32 #define GETENV getenv #else #define GETENV getenv #endif #include <fstream> using namespace std; namespace CWE23_Relative_Path_Traversal__char_environment_ofstream_16 { #ifndef OMITBAD void bad() { char * data; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; while(1) { { /* Append input from an environment variable to data */ size_t dataLen = strlen(data); char * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ strncat(data+dataLen, environment, FILENAME_MAX-dataLen-1); } } break; } { ofstream outputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ outputFile.open((char *)data); outputFile.close(); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */ static void goodG2B() { char * data; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; while(1) { /* FIX: Use a fixed file name */ strcat(data, "file.txt"); break; } { ofstream outputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ outputFile.open((char *)data); outputFile.close(); } } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE23_Relative_Path_Traversal__char_environment_ofstream_16; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE23_Relative_Path_Traversal/s02/CWE23_Relative_Path_Traversal__char_environment_ofstream_16.cpp
C++
bsd-3-clause
3,250
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--Rendered using the Haskell Html Library v0.2--> <HTML ><HEAD ><TITLE >Graphics.UI.SDL</TITLE ><LINK HREF = "haddock.css" REL = "stylesheet" TYPE = "text/css" ></HEAD ><BODY ><TABLE CLASS = "vanilla" CELLSPACING = "0" CELLPADDING = "0" ><TR ><TD CLASS = "topbar" ><TABLE CLASS = "vanilla" CELLSPACING = "0" CELLPADDING = "0" ><TR ><TD ><IMG SRC = "haskell_icon.gif" WIDTH = "16" HEIGHT = "16" ALT = " " ></TD ><TD CLASS = "title" >SDL-0.4.0</TD ><TD CLASS = "topbut" ><A HREF = "index.html" >Contents</A ></TD ><TD CLASS = "topbut" ><A HREF = "doc-index.html" >Index</A ></TD ></TR ></TABLE ></TD ></TR ><TR ><TD CLASS = "modulebar" ><TABLE CLASS = "vanilla" CELLSPACING = "0" CELLPADDING = "0" ><TR ><TD ><FONT SIZE = "6" >Graphics.UI.SDL</FONT ></TD ><TD ALIGN = "right" ><TABLE CLASS = "narrow" CELLSPACING = "0" CELLPADDING = "0" ><TR ><TD CLASS = "infohead" >Portability</TD ><TD CLASS = "infoval" > portablex</TD ></TR ><TR ><TD CLASS = "infohead" >Stability</TD ><TD CLASS = "infoval" > provisional</TD ></TR ><TR ><TD CLASS = "infohead" >Maintainer</TD ><TD CLASS = "infoval" > lemmih@gmail.com</TD ></TR ></TABLE ></TD ></TR ></TABLE ></TD ></TR ><TR ><TD CLASS = "s15" ></TD ></TR ><TR ><TD ><TABLE CLASS = "vanilla" CELLSPACING = "0" CELLPADDING = "0" ></TABLE ></TD ></TR ><TR ><TD CLASS = "s15" ></TD ></TR ><TR ><TD CLASS = "section1" >Description</TD ></TR ><TR ><TD CLASS = "doc" ></TD ></TR ><TR ><TD CLASS = "s15" ></TD ></TR ><TR ><TD CLASS = "section1" >Synopsis</TD ></TR ><TR ><TD CLASS = "s15" ></TD ></TR ><TR ><TD CLASS = "body" ><TABLE CLASS = "vanilla" CELLSPACING = "0" CELLPADDING = "0" ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.General.html" >Graphics.UI.SDL.General</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Rect.html" >Graphics.UI.SDL.Rect</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Time.html" >Graphics.UI.SDL.Time</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Types.html" >Graphics.UI.SDL.Types</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Video.html" >Graphics.UI.SDL.Video</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.WindowManagement.html" >Graphics.UI.SDL.WindowManagement</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Audio.html" >Graphics.UI.SDL.Audio</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Color.html" >Graphics.UI.SDL.Color</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Keysym.html" >Graphics.UI.SDL.Keysym</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Events.html" >Graphics.UI.SDL.Events</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.RWOps.html" >Graphics.UI.SDL.RWOps</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Version.html" >Graphics.UI.SDL.Version</A ></TD ></TR ><TR ><TD CLASS = "s8" ></TD ></TR ><TR ><TD CLASS = "decl" >module <A HREF = "Graphics.UI.SDL.Joystick.html" >Graphics.UI.SDL.Joystick</A ></TD ></TR ></TABLE ></TD ></TR ><TR ><TD CLASS = "s15" ></TD ></TR ><TR ><TD CLASS = "s15" ></TD ></TR ><TR ><TD CLASS = "botbar" >Produced by <A HREF = "http://www.haskell.org/haddock/" >Haddock</A > version 0.6</TD ></TR ></TABLE ></BODY ></HTML >
vincenthz/hs-sdl
doc/Graphics.UI.SDL.html
HTML
bsd-3-clause
4,975