text
stringlengths
2
99k
meta
dict
package com.beust.kobalt.internal import com.beust.kobalt.KobaltException import com.beust.kobalt.api.* import com.beust.kobalt.misc.kobaltLog import java.io.ByteArrayInputStream import java.io.InputStream import javax.xml.bind.JAXBContext import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlRootElement // // Operations related to the parsing of kobalt-plugin.xml: XML parsing, PluginInfo, etc... // /** * If a plug-in didn't specify a factory, we use our own injector to instantiate all its components. */ class GuiceFactory : IFactory { override fun <T> instanceOf(c: Class<T>) : T = Kobalt.INJECTOR.getInstance(c) } ///// // XML parsing // // The following classes are used by JAXB to parse the kobalt-plugin.xml file. /** * The root element of kobalt-plugin.xml */ @XmlRootElement(name = "kobalt-plugin") class KobaltPluginXml { @XmlElement @JvmField var name: String? = null @XmlElement(name = "plugin-actors") @JvmField var pluginActors : ClassNameXml? = null @XmlElement(name = "factory-class-name") @JvmField var factoryClassName: String? = null } class ContributorXml { @XmlElement @JvmField val name: String? = null } class ClassNameXml { @XmlElement(name = "class-name") @JvmField var className: List<String> = arrayListOf() } /** * The fields in this interface have tests. */ interface IPluginInfo { val testJvmFlagContributors : List<ITestJvmFlagContributor> val testJvmFlagInterceptors : List<ITestJvmFlagInterceptor> } open class BasePluginInfo : IPluginInfo { override val testJvmFlagContributors = arrayListOf<ITestJvmFlagContributor>() override val testJvmFlagInterceptors = arrayListOf<ITestJvmFlagInterceptor>() } /** * Turn a KobaltPluginXml (the raw content of kobalt-plugin.xml mapped to POJO's) into a PluginInfo object, which * contains all the contributors instantiated and other information that Kobalt can actually use. Kobalt code that * needs to access plug-in info can then just inject a PluginInfo object. */ class PluginInfo(val xml: KobaltPluginXml, val pluginClassLoader: ClassLoader?, val classLoader: ClassLoader?) : BasePluginInfo() { val plugins = arrayListOf<IPlugin>() val projectContributors = arrayListOf<IProjectContributor>() val classpathContributors = arrayListOf<IClasspathContributor>() val templateContributors = arrayListOf<ITemplateContributor>() val repoContributors = arrayListOf<IRepoContributor>() val compilerFlagContributors = arrayListOf<ICompilerFlagContributor>() val compilerInterceptors = arrayListOf<ICompilerInterceptor>() val sourceDirectoriesInterceptors = arrayListOf<ISourceDirectoryInterceptor>() val buildDirectoryInterceptors = arrayListOf<IBuildDirectoryInterceptor>() // val runnerContributors = arrayListOf<IRunnerContributor>() val testRunnerContributors = arrayListOf<ITestRunnerContributor>() val classpathInterceptors = arrayListOf<IClasspathInterceptor>() val compilerContributors = arrayListOf<ICompilerContributor>() val docContributors = arrayListOf<IDocContributor>() val sourceDirContributors = arrayListOf<ISourceDirectoryContributor>() val testSourceDirContributors = arrayListOf<ITestSourceDirectoryContributor>() val buildConfigFieldContributors = arrayListOf<IBuildConfigFieldContributor>() val taskContributors = arrayListOf<ITaskContributor>() val assemblyContributors = arrayListOf<IAssemblyContributor>() val incrementalAssemblyContributors = arrayListOf<IIncrementalAssemblyContributor>() val incrementalTaskContributors = arrayListOf<IIncrementalTaskContributor>() // Not documented yet val buildConfigContributors = arrayListOf<IBuildConfigContributor>() val mavenIdInterceptors = arrayListOf<IMavenIdInterceptor>() val jvmFlagContributors = arrayListOf<IJvmFlagContributor>() val localMavenRepoPathInterceptors = arrayListOf<ILocalMavenRepoPathInterceptor>() val buildListeners = arrayListOf<IBuildListener>() val buildReportContributors = arrayListOf<IBuildReportContributor>() val docFlagContributors = arrayListOf<IDocFlagContributor>() // Note: intentionally repeating them here even though they are defined by our base class so // that this class always contains the full list of contributors and interceptors override val testJvmFlagContributors = arrayListOf<ITestJvmFlagContributor>() override val testJvmFlagInterceptors = arrayListOf<ITestJvmFlagInterceptor>() companion object { /** * Where plug-ins define their plug-in actors. */ val PLUGIN_XML = "META-INF/kobalt-plugin.xml" /** * Kobalt's core XML file needs to be different from kobalt-plugin.xml because classloaders * can put a plug-in's jar file in front of Kobalt's, which means we'll read * that one instead of the core one. */ val PLUGIN_CORE_XML = "META-INF/kobalt-core-plugin.xml" /** * Read Kobalt's own kobalt-plugin.xml. */ fun readKobaltPluginXml(): PluginInfo { // Note: use forward slash here since we're looking up this file in a .jar file val url = Kobalt::class.java.classLoader.getResource(PLUGIN_CORE_XML) kobaltLog(2, "URL for core kobalt-plugin.xml: $url") if (url != null) { return readPluginXml(url.openConnection().inputStream) } else { throw AssertionError("Couldn't find $PLUGIN_XML") } } /** * Read a general kobalt-plugin.xml. */ fun readPluginXml(ins: InputStream, pluginClassLoader: ClassLoader? = null, classLoader: ClassLoader? = null): PluginInfo { val jaxbContext = JAXBContext.newInstance(KobaltPluginXml::class.java) val kobaltPlugin: KobaltPluginXml = jaxbContext.createUnmarshaller().unmarshal(ins) as KobaltPluginXml kobaltLog(2, "Parsed plugin XML file, found: " + kobaltPlugin.name) val result = try { PluginInfo(kobaltPlugin, pluginClassLoader, classLoader) } catch(ex: Exception) { throw KobaltException("Couldn't create PluginInfo: " + ex.message, ex) } return result } fun readPluginXml(s: String, pluginClassLoader: ClassLoader?, scriptClassLoader: ClassLoader? = null) = readPluginXml(ByteArrayInputStream(s.toByteArray(Charsets.UTF_8)), pluginClassLoader, scriptClassLoader) } init { val factory = if (xml.factoryClassName != null) { Class.forName(xml.factoryClassName).newInstance() as IFactory } else { GuiceFactory() } fun forName(className: String) : Class<*> { fun loadClass(className: String, classLoader: ClassLoader?) : Class<*>? { try { return classLoader?.loadClass(className) } catch(ex: ClassNotFoundException) { return null } } val result = loadClass(className, classLoader) ?: loadClass(className, pluginClassLoader) ?: Class.forName(className) return result } // // Populate pluginInfo with what was found in Kobalt's own kobalt-plugin.xml // @Suppress("UNCHECKED_CAST") xml.pluginActors?.className?.forEach { with(factory.instanceOf(forName(it))) { // Note: can't use "when" here since the same instance can implement multiple interfaces if (this is IBuildConfigFieldContributor) buildConfigFieldContributors.add(this) if (this is IBuildDirectoryInterceptor) buildDirectoryInterceptors.add(this) if (this is IClasspathContributor) classpathContributors.add(this) if (this is IClasspathInterceptor) classpathInterceptors.add(this) if (this is ICompilerContributor) compilerContributors.add(this) if (this is ICompilerFlagContributor) compilerFlagContributors.add(this) if (this is ICompilerInterceptor) compilerInterceptors.add(this) if (this is IDocContributor) docContributors.add(this) if (this is ITemplateContributor) templateContributors.add(this) if (this is IPlugin) plugins.add(this) if (this is IProjectContributor) projectContributors.add(this) if (this is IRepoContributor) repoContributors.add(this) // if (this is IRunnerContributor) runnerContributors.add(this) if (this is ISourceDirectoryContributor) sourceDirContributors.add(this) if (this is ISourceDirectoryInterceptor) sourceDirectoriesInterceptors.add(this) if (this is ITaskContributor) taskContributors.add(this) if (this is ITestRunnerContributor) testRunnerContributors.add(this) if (this is IMavenIdInterceptor) mavenIdInterceptors.add(this) if (this is ITestSourceDirectoryContributor) testSourceDirContributors.add(this) if (this is IBuildConfigContributor) buildConfigContributors.add(this) if (this is IAssemblyContributor) assemblyContributors.add(this) if (this is IIncrementalAssemblyContributor) incrementalAssemblyContributors.add(this) if (this is IIncrementalTaskContributor) incrementalTaskContributors.add(this) // Not documented yet if (this is ITestJvmFlagContributor) testJvmFlagContributors.add(this) if (this is ITestJvmFlagInterceptor) testJvmFlagInterceptors.add(this) if (this is IJvmFlagContributor) jvmFlagContributors.add(this) if (this is ILocalMavenRepoPathInterceptor) localMavenRepoPathInterceptors.add(this) if (this is IBuildListener) buildListeners.add(this) if (this is IBuildReportContributor) buildReportContributors.add(this) if (this is IDocFlagContributor) docFlagContributors.add(this) } } } fun cleanUp() { listOf(projectContributors, classpathContributors, templateContributors, repoContributors, compilerFlagContributors, compilerInterceptors, sourceDirectoriesInterceptors, buildDirectoryInterceptors, /* runnerContributors, */ testRunnerContributors, classpathInterceptors, compilerContributors, docContributors, sourceDirContributors, testSourceDirContributors, buildConfigFieldContributors, taskContributors, incrementalTaskContributors, assemblyContributors, incrementalAssemblyContributors, testJvmFlagInterceptors, jvmFlagContributors, localMavenRepoPathInterceptors, buildListeners, buildReportContributors, docFlagContributors ).forEach { it.forEach(IPluginActor::cleanUpActors) } } /** * Add the content of @param[pluginInfo] to this pluginInfo. */ fun addPluginInfo(pluginInfo: PluginInfo) { kobaltLog(2, "Found new plug-in, adding it to pluginInfo: $pluginInfo") plugins.addAll(pluginInfo.plugins) classpathContributors.addAll(pluginInfo.classpathContributors) projectContributors.addAll(pluginInfo.projectContributors) templateContributors.addAll(pluginInfo.templateContributors) repoContributors.addAll(pluginInfo.repoContributors) compilerFlagContributors.addAll(pluginInfo.compilerFlagContributors) compilerInterceptors.addAll(pluginInfo.compilerInterceptors) sourceDirectoriesInterceptors.addAll(pluginInfo.sourceDirectoriesInterceptors) buildDirectoryInterceptors.addAll(pluginInfo.buildDirectoryInterceptors) // runnerContributors.addAll(pluginInfo.runnerContributors) testRunnerContributors.addAll(pluginInfo.testRunnerContributors) classpathInterceptors.addAll(pluginInfo.classpathInterceptors) compilerContributors.addAll(pluginInfo.compilerContributors) docContributors.addAll(pluginInfo.docContributors) sourceDirContributors.addAll(pluginInfo.sourceDirContributors) buildConfigFieldContributors.addAll(pluginInfo.buildConfigFieldContributors) taskContributors.addAll(pluginInfo.taskContributors) incrementalTaskContributors.addAll(pluginInfo.incrementalTaskContributors) testSourceDirContributors.addAll(pluginInfo.testSourceDirContributors) mavenIdInterceptors.addAll(pluginInfo.mavenIdInterceptors) buildConfigContributors.addAll(pluginInfo.buildConfigContributors) assemblyContributors.addAll(pluginInfo.assemblyContributors) incrementalAssemblyContributors.addAll(pluginInfo.incrementalAssemblyContributors) testJvmFlagContributors.addAll(pluginInfo.testJvmFlagContributors) testJvmFlagInterceptors.addAll(pluginInfo.testJvmFlagInterceptors) jvmFlagContributors.addAll(pluginInfo.jvmFlagContributors) localMavenRepoPathInterceptors.addAll(pluginInfo.localMavenRepoPathInterceptors) buildListeners.addAll(pluginInfo.buildListeners) buildReportContributors.addAll(pluginInfo.buildReportContributors) docFlagContributors.addAll(pluginInfo.docFlagContributors) } }
{ "pile_set_name": "Github" }
import { logger } from './'; const hookMessageSuffix = 'hook called (from mixin)'; export const lifecycleHooks = { // Computeds computed: { componentName() { return `${this.$options.name} component`; }, }, // LifeCycle Hooks created() { logger.info(`${this.componentName} created ${hookMessageSuffix}`); logger.info('component data', this.$data); }, mounted() { logger.info(`${this.componentName} mounted ${hookMessageSuffix}`); }, updated() { logger.info(`${this.componentName} updated ${hookMessageSuffix}`); }, destroyed() { logger.info(`${this.componentName} destroyed ${hookMessageSuffix}`); }, }; export const heroWatchers = { // Watchers watch: { selectedHero: { immediate: true, deep: true, handler(newValue, oldValue) { logger.info('old values', oldValue); logger.info('new values', newValue); }, }, }, };
{ "pile_set_name": "Github" }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Management.Automation; using Microsoft.Azure.Management.DataMigration.Models; using PSModels = Microsoft.Azure.Commands.DataMigration.Models; namespace Microsoft.Azure.Commands.DataMigration.Cmdlets { public class ConnectToTargetMongoDbTaskCmdlet : TaskCmdlet<PSModels.MongoDbConnectionInfo> { public ConnectToTargetMongoDbTaskCmdlet(InvocationInfo myInvocation) : base(myInvocation) { } public override void CustomInit() { this.SimpleParam(TargetConnection, typeof(PSModels.MongoDbConnectionInfo), "MongoDb Connection Detail ", true); this.SimpleParam(TargetCred, typeof(PSCredential), "Credential Detail", false); } public override ProjectTaskProperties ProcessTaskCmdlet() { var properties = new ConnectToMongoDbTaskProperties(); if (MyInvocation.BoundParameters.ContainsKey(TargetConnection)) { var conn = MyInvocation.BoundParameters[TargetConnection] as PSModels.MongoDbConnectionInfo; if (MyInvocation.BoundParameters.ContainsKey(TargetCred)) { PSCredential cred = (PSCredential)MyInvocation.BoundParameters[TargetCred]; conn.UserName = cred.UserName; conn.Password = Decrypt(cred.Password); conn.ConstructConnectionString(); } properties.Input = new MongoDbConnectionInfo { ConnectionString = conn.ConnectionString }; } return properties; } } }
{ "pile_set_name": "Github" }
/* Package validation provides methods for validating parameter value using reflection. */ package validation // Copyright 2017 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. import ( "fmt" "reflect" "regexp" "strings" ) // Constraint stores constraint name, target field name // Rule and chain validations. type Constraint struct { // Target field name for validation. Target string // Constraint name e.g. minLength, MaxLength, Pattern, etc. Name string // Rule for constraint e.g. greater than 10, less than 5 etc. Rule interface{} // Chain Validations for struct type Chain []Constraint } // Validation stores parameter-wise validation. type Validation struct { TargetValue interface{} Constraints []Constraint } // Constraint list const ( Empty = "Empty" Null = "Null" ReadOnly = "ReadOnly" Pattern = "Pattern" MaxLength = "MaxLength" MinLength = "MinLength" MaxItems = "MaxItems" MinItems = "MinItems" MultipleOf = "MultipleOf" UniqueItems = "UniqueItems" InclusiveMaximum = "InclusiveMaximum" ExclusiveMaximum = "ExclusiveMaximum" ExclusiveMinimum = "ExclusiveMinimum" InclusiveMinimum = "InclusiveMinimum" ) // Validate method validates constraints on parameter // passed in validation array. func Validate(m []Validation) error { for _, item := range m { v := reflect.ValueOf(item.TargetValue) for _, constraint := range item.Constraints { var err error switch v.Kind() { case reflect.Ptr: err = validatePtr(v, constraint) case reflect.String: err = validateString(v, constraint) case reflect.Struct: err = validateStruct(v, constraint) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: err = validateInt(v, constraint) case reflect.Float32, reflect.Float64: err = validateFloat(v, constraint) case reflect.Array, reflect.Slice, reflect.Map: err = validateArrayMap(v, constraint) default: err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) } if err != nil { return err } } } return nil } func validateStruct(x reflect.Value, v Constraint, name ...string) error { //Get field name from target name which is in format a.b.c s := strings.Split(v.Target, ".") f := x.FieldByName(s[len(s)-1]) if isZero(f) { return createError(x, v, fmt.Sprintf("field %q doesn't exist", v.Target)) } return Validate([]Validation{ { TargetValue: getInterfaceValue(f), Constraints: []Constraint{v}, }, }) } func validatePtr(x reflect.Value, v Constraint) error { if v.Name == ReadOnly { if !x.IsNil() { return createError(x.Elem(), v, "readonly parameter; must send as nil or empty in request") } return nil } if x.IsNil() { return checkNil(x, v) } if v.Chain != nil { return Validate([]Validation{ { TargetValue: getInterfaceValue(x.Elem()), Constraints: v.Chain, }, }) } return nil } func validateInt(x reflect.Value, v Constraint) error { i := x.Int() r, ok := toInt64(v.Rule) if !ok { return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) } switch v.Name { case MultipleOf: if i%r != 0 { return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r)) } case ExclusiveMinimum: if i <= r { return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) } case ExclusiveMaximum: if i >= r { return createError(x, v, fmt.Sprintf("value must be less than %v", r)) } case InclusiveMinimum: if i < r { return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) } case InclusiveMaximum: if i > r { return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) } default: return createError(x, v, fmt.Sprintf("constraint %v is not applicable for type integer", v.Name)) } return nil } func validateFloat(x reflect.Value, v Constraint) error { f := x.Float() r, ok := v.Rule.(float64) if !ok { return createError(x, v, fmt.Sprintf("rule must be float value for %v constraint; got: %v", v.Name, v.Rule)) } switch v.Name { case ExclusiveMinimum: if f <= r { return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) } case ExclusiveMaximum: if f >= r { return createError(x, v, fmt.Sprintf("value must be less than %v", r)) } case InclusiveMinimum: if f < r { return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) } case InclusiveMaximum: if f > r { return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) } default: return createError(x, v, fmt.Sprintf("constraint %s is not applicable for type float", v.Name)) } return nil } func validateString(x reflect.Value, v Constraint) error { s := x.String() switch v.Name { case Empty: if len(s) == 0 { return checkEmpty(x, v) } case Pattern: reg, err := regexp.Compile(v.Rule.(string)) if err != nil { return createError(x, v, err.Error()) } if !reg.MatchString(s) { return createError(x, v, fmt.Sprintf("value doesn't match pattern %v", v.Rule)) } case MaxLength: if _, ok := v.Rule.(int); !ok { return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) } if len(s) > v.Rule.(int) { return createError(x, v, fmt.Sprintf("value length must be less than or equal to %v", v.Rule)) } case MinLength: if _, ok := v.Rule.(int); !ok { return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) } if len(s) < v.Rule.(int) { return createError(x, v, fmt.Sprintf("value length must be greater than or equal to %v", v.Rule)) } case ReadOnly: if len(s) > 0 { return createError(reflect.ValueOf(s), v, "readonly parameter; must send as nil or empty in request") } default: return createError(x, v, fmt.Sprintf("constraint %s is not applicable to string type", v.Name)) } if v.Chain != nil { return Validate([]Validation{ { TargetValue: getInterfaceValue(x), Constraints: v.Chain, }, }) } return nil } func validateArrayMap(x reflect.Value, v Constraint) error { switch v.Name { case Null: if x.IsNil() { return checkNil(x, v) } case Empty: if x.IsNil() || x.Len() == 0 { return checkEmpty(x, v) } case MaxItems: if _, ok := v.Rule.(int); !ok { return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.Name, v.Rule)) } if x.Len() > v.Rule.(int) { return createError(x, v, fmt.Sprintf("maximum item limit is %v; got: %v", v.Rule, x.Len())) } case MinItems: if _, ok := v.Rule.(int); !ok { return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.Name, v.Rule)) } if x.Len() < v.Rule.(int) { return createError(x, v, fmt.Sprintf("minimum item limit is %v; got: %v", v.Rule, x.Len())) } case UniqueItems: if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { if !checkForUniqueInArray(x) { return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.Target, x)) } } else if x.Kind() == reflect.Map { if !checkForUniqueInMap(x) { return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.Target, x)) } } else { return createError(x, v, fmt.Sprintf("type must be array, slice or map for constraint %v; got: %v", v.Name, x.Kind())) } case ReadOnly: if x.Len() != 0 { return createError(x, v, "readonly parameter; must send as nil or empty in request") } case Pattern: reg, err := regexp.Compile(v.Rule.(string)) if err != nil { return createError(x, v, err.Error()) } keys := x.MapKeys() for _, k := range keys { if !reg.MatchString(k.String()) { return createError(k, v, fmt.Sprintf("map key doesn't match pattern %v", v.Rule)) } } default: return createError(x, v, fmt.Sprintf("constraint %v is not applicable to array, slice and map type", v.Name)) } if v.Chain != nil { return Validate([]Validation{ { TargetValue: getInterfaceValue(x), Constraints: v.Chain, }, }) } return nil } func checkNil(x reflect.Value, v Constraint) error { if _, ok := v.Rule.(bool); !ok { return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) } if v.Rule.(bool) { return createError(x, v, "value can not be null; required parameter") } return nil } func checkEmpty(x reflect.Value, v Constraint) error { if _, ok := v.Rule.(bool); !ok { return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) } if v.Rule.(bool) { return createError(x, v, "value can not be null or empty; required parameter") } return nil } func checkForUniqueInArray(x reflect.Value) bool { if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { return false } arrOfInterface := make([]interface{}, x.Len()) for i := 0; i < x.Len(); i++ { arrOfInterface[i] = x.Index(i).Interface() } m := make(map[interface{}]bool) for _, val := range arrOfInterface { if m[val] { return false } m[val] = true } return true } func checkForUniqueInMap(x reflect.Value) bool { if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { return false } mapOfInterface := make(map[interface{}]interface{}, x.Len()) keys := x.MapKeys() for _, k := range keys { mapOfInterface[k.Interface()] = x.MapIndex(k).Interface() } m := make(map[interface{}]bool) for _, val := range mapOfInterface { if m[val] { return false } m[val] = true } return true } func getInterfaceValue(x reflect.Value) interface{} { if x.Kind() == reflect.Invalid { return nil } return x.Interface() } func isZero(x interface{}) bool { return x == reflect.Zero(reflect.TypeOf(x)).Interface() } func createError(x reflect.Value, v Constraint, err string) error { return fmt.Errorf("autorest/validation: validation failed: parameter=%s constraint=%s value=%#v details: %s", v.Target, v.Name, getInterfaceValue(x), err) } func toInt64(v interface{}) (int64, bool) { if i64, ok := v.(int64); ok { return i64, true } // older generators emit max constants as int, so if int64 fails fall back to int if i32, ok := v.(int); ok { return int64(i32), true } return 0, false }
{ "pile_set_name": "Github" }
//##1 try catch stack status final throws class IntExcep(~valu int) extends Exception{ override equals(o Object) boolean{return true;} } cnt = 0; fincnt = 0; catchCall = 0; def callCatch1() { catchCall++ } def mycall(fail boolean) int { if(fail){ throw new Exception("") } return ++cnt; } def callOnFinal1(){ fincnt+=1 } @com.concurnas.lang.Uninterruptible def da2(fail boolean, f2 boolean) int{ try{ return mycall(fail)//should be popped } finally{ //callOnFinal1()//return 8 throw new IntExcep(80) } } def runner(a boolean, b boolean) int{ try{ return da2(a,b) } catch(e IntExcep){ return e.valu } } def doings() String{ return "" + [ runner(true, true), runner(false, true), runner(true, false), runner(false, false), cnt, fincnt, catchCall]; } ~~~~~ //##2 try catch stack status final throws class IntExcep(~valu int) extends Exception{ override equals(o Object) boolean{return true;} } cnt = 0; fincnt = 0; catchCall = 0; def callCatch1() { catchCall++ } def mycall(fail boolean) int { if(fail){ throw new Exception("") } return ++cnt; } def callOnFinal1(){ fincnt+=1 } @com.concurnas.lang.Uninterruptible def da2(fail boolean, f2 boolean) int{ try{ mycall(fail)//should be popped } finally{ //callOnFinal1()//return 8 throw new IntExcep(80) } } def runner(a boolean, b boolean) int{ try{ return da2(a,b) } catch(e IntExcep){ return e.valu } } def doings() String{ return "" + [ runner(true, true), runner(false, true), runner(true, false), runner(false, false), cnt, fincnt, catchCall]; } ~~~~~ //##3 try catch stack status final throws applies to catch also class IntExcep(~valu int) extends Exception{ override equals(o Object) boolean{return true;} } cnt = 0; fincnt = 0; catchCall = 0; def callCatch1() { catchCall++ } def mycall(fail boolean) int { if(fail){ throw new Exception("") } return ++cnt; } def callOnFinal1(){ fincnt+=1 } @com.concurnas.lang.Uninterruptible def da2(fail boolean, f2 boolean) int{ try{ mycall(fail)//popped } catch(e Throwable){ callCatch1(); //popped } finally{ callOnFinal1()//return 8 throw new IntExcep(80) } } def runner(a boolean, b boolean) int{ try{ return da2(a,b) } catch(e IntExcep){ return e.valu } } def doings() String{ return "" + [ runner(true, true), runner(false, true), runner(true, false), runner(false, false), cnt, fincnt, catchCall]; } ~~~~~ //##4 vararg generics from java.util import ArrayList, List def asList<T>(ts T...) { result List<T> = ArrayList<T>() for (t in ts) { result.add(t) } result } def doings() { "" + asList<Integer>([Integer(1) 2 3 4 5]) } ~~~~~ //##5 vararg generics type inference infer type from java.util import ArrayList, List def asList<T>(ts T...) { result List<T> = ArrayList<T>() for (t in ts) { result.add(t) } result } def doings() { "" + asList([Integer(1) Integer(2) Integer(3) Integer(4) Integer(5)]) } ~~~~~ //##6 vararg simple needs boxing from java.util import ArrayList, List def asList(ts Integer...) { result List<int> = ArrayList<int>() for (t in ts) { result.add(t) } result } def doings() { "" + asList(1, 2, 3, 4, 5) } ~~~~~ //##7 vararg simple no boxing from java.util import ArrayList, List def asList(ts Integer...) { result List<Integer> = ArrayList<Integer>() for (t in ts) { result.add(t) } result } def doings() { "" + asList(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5)) } ~~~~~ //##8. when quailifying generic types used to not include source generic array level count def asList<T>(a T[]) => a def doings(){ xx = asList<int[]>([12 13 ; 12])//used to think this was int[] instead of int[2] "" + xx } ~~~~~ //##9. qualify generic varag with 1:1 non vararg mathc def asList<T>(a T[]) => a def doings(){ xx = asList(['hi', 'there']) "" +xx } ~~~~~ //##10. qualify generic vararg with boxed param def asList<T>(a T[]) => a h = new Integer(12) def doings(){ xx = asList([h, h]) "" + xx } ~~~~~ //##11. qualify generic vararg with unboxed param from java.util import Arrays, List, HashSet def doings(){ xx = Arrays.asList(1,2,3) "" + xx } ~~~~~ //##12. qualify generic vararg with boxed param def asList<T>(a T...) => a h = new Integer(1) def doings(){ xx = asList(h,h,h) "" + xx } ~~~~~ //##13. qualify generic vararg with boxed param box up def asList<T>(a T...) => a def doings(){ xx = asList(1,2,3) "" + xx } ~~~~~ //##14. qualify generic implicit vararg with boxed param box up def asList<T>(a T[]) => a def doings(){ xx = asList(1,2,3) "" + xx } ~~~~~ //##15. qualify generic implicit vararg with free vars boxing from java.util import ArrayList, List def asList<T>(ts T...) { result List<T> = ArrayList<T>() for (t in ts) { result.add(t) } result } def doings() { xx = asList(1,2,3,4,5) ""+xx } ~~~~~ //##16. qualify generic implicit vararg with free vars already boxed from java.util import ArrayList, List def asList<T>(ts T...) { result List<T> = ArrayList<T>() for (t in ts) { result.add(t) } result } def doings() { "" + asList(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5)) } ~~~~~ //##17. qualify generic implicit vararg with free vars already boxed generic declared from java.util import ArrayList, List def asList<T>(ts T...) { result List<T> = ArrayList<T>() for (t in ts) { result.add(t) } result } def doings() { "" + asList<Integer>([Integer(1) 2 3 4 5]) } ~~~~~ //##18. generic vararg more from java.util import ArrayList, List def asList<T>(ts T...) { result List<T> = ArrayList<T>() for (t in ts) { result.add(t) } result } def doings() { "" + asList(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5)) } ~~~~~ //##19. generic vararg more 2 from java.util import ArrayList, List def asList<T>(ts T...) { result List<T> = ArrayList<T>() for (t in ts) { result.add(t) } result } def doings() { "" + asList<int>(1, 2, 3, 4, 5) } ~~~~~ //##20. generic vararg more 3 from java.util import ArrayList, List def asList<T>(ts T...) { result List<T> = ArrayList<T>() for (t in ts) { result.add(t) } result } def doings() { "" + asList(1, 2, 3, 4, 5) } ~~~~~ //##21. cast elements to char not int def thing(a char...){ "" + a} def doings(){ g1 = thing(77,87) "" + g1 } ~~~~~ //##22. double check this works vararg is null def something(a String, b int...) => a + b def doings() => something('ok')//vararg is null ~~~~~ //##23. static methods were being missing from the origonal class - now we redirect from com.concurnas.lang.precompiled import ClassWithStaticClinit def doings(){ meths = ClassWithStaticClinit.class.getMethods() res = 'isFiberNotNull' in for(m in meths){ m.name} "" + res } ~~~~~ //##24. Fiber used to be uncreatable and now on reflection we find fiberized version if approperiate from com.concurnas.lang.precompiled import ClassWithStaticClinit def doings(){ meths = ClassWithStaticClinit.class.getMethods() res = for(m in meths){ if('getTheCurrentFiber' in m.name) { m } } //next line didnt used to work as Fibers cannot be created one = ClassWithStaticClinit.class.getMethod('getTheCurrentFiber') "" + [res, one] } ~~~~~ //##25. reflect to remove fiber parameter from method from com.concurnas.lang.precompiled import ClassWithStaticClinit def doings(){ one = ClassWithStaticClinit.class.getMethod('getTheCurrentFiber') //list args, hide the fiber //stuff = one.invoke(null, com.concurnas.bootstrap.runtime.cps.Fiber.getCurrentFiber()) "" + [one.getParameterTypes(), one.getParameterCount()] } ~~~~~ //##26. reflect to splice in fiber to invokation from com.concurnas.lang.precompiled import ClassWithStaticClinit def doings(){ one = ClassWithStaticClinit.class.getMethod('getTheCurrentFiber') stuff = one.invoke(null) <> null "" + stuff } ~~~~~ //##27. tricky problem with reflection and enums and fibers want := 2 j='bananana' inited = 0 enum MYE(a int){ OP(2), NO(1) init{ f = "wellhellothere" inited++ } init{ inited++ } } def doings() { x = inited a=MYE.OP l='lovely' v = MYE.values() k=MYE.class.getMethod("values").invoke(null) c=MYE.valueOf('NO') "" + [x, k, c, inited, want] } ~~~~~ //##28. method does not exist exception thrown correctly from com.concurnas.lang.precompiled import ClassWithStaticClinit def doings(){ res = try{ ClassWithStaticClinit.class.getMethod('doesntexist') }catch(e){""+e} "" + res } ~~~~~ //##29. bug concerning local arrays class GenParaInOut<X>(public ~x X[]){//gets stored as Object[] - but if its an array we need to explicitly convert this into a localarray[int:] override hashCode() => 69 override equals(a Object) => true override toString() => "has: " + x } la = [100: 200:] gp = new GenParaInOut(la)//turned out to be a problem with subtyping of generic types and refs def doings(){ got = gp.x got2 = gp\.x//type was also not correctly extracted here "" + [got, got2] } ~~~~~ //##30. can use js style setter when no getter defined class Complex(real double, imag double){ public myMap = {"-" -> 1} def put(a String, b int) { myMap[a] = b; } } c2 = Complex(2,2) def doings(){ c2.one = 101 "" + c2.myMap } ~~~~~ //##31.a broken before now ok calls := 0 def doingsx() { trans{calls++} } mtay = [1,2,3,4,5,6,7,8,9,10] def doings(){ a=0 while(a++< 1000){ parfor(b in mtay){//used to attempt to return something when nothing expected doingsx() } } await(calls; calls == 10000) "" + calls } ~~~~~ //##31.b broken before now ok calls := 0 def doingsx() { trans{calls++} } mtay = [1,2,3,4,5,6,7,8,9,10] def doings(){ a=0 sync{ while(a++< 1000){ parfor(b in mtay){ doingsx() } } } "" + calls } ~~~~~ //##31.c broken before now ok calls := 0 def doingsx() { trans{calls++} } mtay = [1,2,3,4,5,6,7,8,9,10] def doings(){ a=0 while(a++< 1000){ parforsync(b in mtay){ doingsx() } } "" + calls } ~~~~~ //##32. ensure function invokation locks ref origa = 12: origb = 12: def doingsa() { origa: } def doingsb() Integer: { origb: } def doings(){ a=doingsa() b=doingsb()//neither return refs natively "" + [a:&<>origa:, b:&<>origb:] } ~~~~~ //##33. used to incorrectly call generic version class MyClass<X>{ public var x X? public var y = "no set" this(x X){ this.x = x } this(a int[]){ this.x = null this.y="set" } override toString() => "" + [x,y] //respects fact that x is not bound at this point so points to Object //thus returned as an object array //above is ambigious } def doings() { mc2 = new MyClass([1,2]) "" + mc2 } ~~~~~ //##34. object is supertype of primatives def doings(){ an Object = 69 "" + an } ~~~~~ //##35. didnt used to work class MyClass(a int, b int){ override equals(a Object) => false override hashCode() => 1 override toString() => getClass().getSimpleName() + " " + [a,b] } clnam = MyClass.class.name class MyProvider{ def \new(className String, args Object...){ match(className){ //case('MyClass' and args.length == 2){ new MyClass(args[0] as int, args[1] as int) } case(clnam){ new MyClass(args[0] as int, args[1] as int) } else{ null } } } } def doings(){ mp = MyProvider() "" + mp.new MyClass(1,2) } ~~~~~ //##36. funcref arg being arrayref on non array def myfunct(b int, a int) => a+ 100 + b from com.concurnas.lang.precompiled.ListMaker import intList, intMatrix myAr1 = intList(1, 2) def doings(){ res = myfunct&(? int, myAr1.get(0)) res2 = myfunct&(? int, myAr1[0]) "" + [res(1), res2(1)] } ~~~~~ //##37. labels here were a problme, now they are ok erin = [true true false] def doings() { res1 = not y for y in (x for x in erin) res2 = for( y in (for( x in erin) {x})) { not y } "" + [res1 , res2] } ~~~~~ //##38. lists vs arrays myar = [1 2 3] myar2d = [1 2 3 ; 1 2 3] mylist = [1, 2, 3, 4] mylist2d = [[1, 2, 3], [1, 2, 3]] def doings(){ a1 = "" + myar + "\n" a2 = "" + myar2d + "\n" a3 = "" + mylist + "\n" a4 = "" + mylist2d "" + a1 + a2 + a3 +a4 } ~~~~~ //##39 broken before now ok array version calls := 0 def doingsx() { trans{calls++} } mtay = [1 2 3 4 5 6 7 8 9 10] def doings(){ a=0 while(a++< 1000){ parfor(b in mtay){//used to attempt to return something when nothing expected doingsx() } } await(calls; calls == 10000) "" + calls } ~~~~~ //##40 tidy up on array decl f double[]? = null def doings(){ bug1 = [ 23.34 666.78 ; null ] bug2 = [23.34 666.78 ; [1.] ] bug3 = [23.34 666.78 ; [] ] "" + [bug1, bug2, bug3] } ~~~~~ //##41 tidy up on array decl - like above def doings(){ bug1 = [ 23.34 666.78 ; null ]//should be 2d arry with null row bug2 = [23.34 666.78 ; [1.] ] bug3 = [23.34 666.78 ; [] ] bug4 = [null null] bug5 = [23.34 666.78 ; [null] ] bug6 = [23.34 666.78 ; [null null] ] "" + [bug1, bug2, bug3, bug4, bug5, bug6] } ~~~~~ //##42. problem with generic upper bounds for list iterator variables valu int: = 0 def dosomework(a int) { trans{ valu += a } } def doings() { sync{ //prevsouly the local vars declared within for loops were not being captured //TODO: any more like this? - check... for( b in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]){ dosomework(b)! } for(h =1; h <== 15; h++){ dosomework(h)! } h2 =1 for(; h2 <== 15; h2++){ dosomework(h2)! } } await(valu ; 360 == valu) "" + valu// (valu == 360) } ~~~~~ //##43. problem as above def doings(){ parfor(a in [1,2,3,4,5]){ g=a } "ok" } ~~~~~ //##44. list with no items def String join(delim String, items Object...){ ""+delim.join('hi', 'there') } def doings(){ e1 = [1] e2 = a[1] e3 = [,]//empty list e3 add "hi" "" + [e1, e2, e3] } ~~~~~ //##45. default value for array creation bug advanced class MyClass(a int){ override toString() => 'MyClass {a}' } h1 = new MyClass[3](new MyClass(6)) def doings(){ "" + h1 } ~~~~~ //##46. default value for array creation bug simple h1 = new int[2](9) def doings(){ "" + h1 } ~~~~~ //##47. default value for array creation bug v advanved from java.util import ArrayList h1 = new ArrayList<int[]>[4](new ArrayList<int[]>(0)) def doings(){ "" + h1 } ~~~~~ //##48. default value for array creation bug v advanved ciool from java.util import ArrayList h1 = new ArrayList<int[]>[4](new ArrayList<int[]>(0)) def doings(){ h1^add( [66] ) shoulderr = h1^get(0) "" + shoulderr } ~~~~~ //##49. bug on type resolution def fib(n int) => 1 if (n <== 1) else (fib(n - 1) + fib(n - 2)) //used to be unable to infir the return type of the above as genmore generic was not fitering nulls and resolving them to Object (nasty!) def doings(){ "" + (fib 4) } ~~~~~ //##50. looks cool import java.math.BigDecimal def doings(){ "" + (BigDecimal(12) ** 1989) } ~~~~~ //##51. globalization of static final fields from com.concurnas.lang.precompiled import HoldingAStaticVar from com.concurnas.lang.precompiled import HoldingAStaticVarWithNonFinal def doings(){//we used to not inialize final static fileds correctly a = [HoldingAStaticVar.CL_INVALID_VALUE, HoldingAStaticVar getInvalidValue] b = [HoldingAStaticVarWithNonFinal.CL_INVALID_VALUE, HoldingAStaticVarWithNonFinal getInvalidValue] "" + [a,b] } ~~~~~ //##52. imported local generic from com.concurnas.lang.precompiled import LocalGenericMethods def doings(){ LocalGenericMethods<String>().alocalGeneric<int[]>([1 2], 'ok')//should be ok "ok" } ~~~~~ //##53. clean up stack on naught static call from com.concurnas.lang.precompiled import NoStaticCall def getIt() => NoStaticCall() def doings(){ what = getIt().theCall() getIt().thing = 'yaya' p=getIt().thing getIt().thing2 += 100 getIt().thing2++ ++getIt().thing2 "fine" + [what, p, getIt().thing2] } ~~~~~ //##54. incorrect inference of return type bugfix def xxx(wc bool:){//was err here {wc=true}! } def doings(){ wc bool: xxx(wc) "" + wc } ~~~~~ //##55. add bridge method for virtual call with differing return type signature abstract class AbsCls{ def getFella() { this } def myMethod(){ getFella() } } class Inst(a int) < AbsCls{ override getFella() { this } } def doings(){ mc = Inst(2) "" + mc.myMethod().\class.name //ensure childclass method is called } ~~~~~ //##56. add bridge method for copier abstract class AbsCls{ def myMethod(){ this@//dont call own copier } } class Inst(a int) < AbsCls def doings(){ mc = Inst(2) "" + mc.myMethod().\class.name //ensure childclass method is copied } ~~~~~ //##57. ensure invoke special called for super invocation as part of asyncref abstract class SupClass{ override hashCode() => 1 override equals(an Object) => false def leMethod(){ "sup": } } class ChildClass < SupClass{ override hashCode() => 1 override equals(an Object) => false override leMethod(){ super.leMethod()://bug was here } } def doings(){ cc = ChildClass() "" + cc.leMethod() } ~~~~~ //##58. nasty fiber bug concerning System calls inside try catch blocks from com.concurnas.lang.precompiled.HoldingAStaticVar import CL_INVALID_VALUE from org.jocl.CL import CL_COMPLETE def xxx(writeComplete bool:) void{ { java.util.concurrent.TimeUnit.SECONDS.sleep(1); writeComplete=true; }! } private abstract class SupClass{ override hashCode() => 1 override equals(an Object) => false protected def leMethod(){ toRet bool: xxx(toRet) toRet: } } private class ChildClass < SupClass{ override hashCode() => 1 override equals(an Object) => false override leMethod(){ super.leMethod(): } } def doings(){ //f=CL_INVALID_VALUE f2=CL_COMPLETE cc = ChildClass() "" + cc.leMethod() } ~~~~~ //##59. list comprehensions on arrays 1 def doings(){ xxx = a[1, 2, 3, 4, 5, 6] ff =xxx.length sdf = "hithere" res = x + 10 for x in xxx "" + res } ~~~~~ //##60. list comprehensions on arrays 2 def doings(){ xxx = a[1, 2, 3, 4, 5, 6] ff =xxx.length sdf = "hithere" res = [x + 10] for x in xxx "" + res } ~~~~~ //##61. parfor on array def doings(){ xxx = a[1, 2, 3, 4, 5, 6] sdf = "hithere" res = x + 10 parfor x in xxx "" + res[1]//its fine } ~~~~~ //##62. magic hack concerning static fibers and native code opencl specificially from org.jocl import Sizeof private val sizeof_boolean = Sizeof.cl_int def doings(){//magic hack here - concerning static, fibers and native code r = { true} ! "hi" + [sizeof_boolean, r] } ~~~~~ //##63. a short array def doings(){ ok short[] = [1s 2s 3s] "" + ok } ~~~~~ //##64. lets fix chars def doings(){ achar char = 'c' aString String = "X" normalString String = 'astring' anotherNormalString String = "astring" "" + [achar, aString, normalString, anotherNormalString] } ~~~~~ //##65. weird open class Parent(an int) class Child(an int) < Parent(an){ def uusing(){ an } } def doings(){ cm = Child(12) "" + cm.uusing() } ~~~~~ //##66. subclass of Ref has self copier def waitwaiter(cl int:gpus.GPURef){ await(cl) //await on subtype of Local is a problem } def doings(){ what = int:gpus.GPURef(null) {what = 800}!//ensure that the ref is not copied waitwaiter(what) "ok" } ~~~~~ //##67. problem where we were cleaning up the stack and pop off value from com.concurnas.lang.precompiled import ClassNeedingDeleteOnUnused delCall =0 class MyClassHavingDeleteSubclass{ def accessStaticVar() { ClassNeedingDeleteOnUnused.delCount++;; ++ClassNeedingDeleteOnUnused.delCount;; } } def doings(){ mc = MyClassHavingDeleteSubclass() mc.accessStaticVar() "" + ClassNeedingDeleteOnUnused.delCount } ~~~~~ //##68. problem where we were cleaning up the stack and pop off value - where value wanted from com.concurnas.lang.precompiled import ClassNeedingDeleteOnUnused delCall =0 class MyClassHavingDeleteSubclass{ def accessStaticVar() { a=ClassNeedingDeleteOnUnused.delCount++;;//we want the value on the stack b=++ClassNeedingDeleteOnUnused.delCount;; } } def doings(){ mc = MyClassHavingDeleteSubclass() mc.accessStaticVar() "" + ClassNeedingDeleteOnUnused.delCount } ~~~~~ //##69. implicit ref creation needs zero arg constructor class GPURef<X>(type Class<?>[], ~event int) < com.concurnas.runtime.ref.Local<X>(type){ public this(type Class<?>[]){ this(type, 0) } } class NoZeroARgOne<X>(type Class<?>[], ~event int) < com.concurnas.runtime.ref.Local<X>(type) def ok(a Object) Object:GPURef { null//no cannot do this } def fail(a Object) Object:NoZeroARgOne { null//no cannot do this } def doings(){ what1 = try{ok("fail"); 'ok'}catch(e){'fail' + e} what2 = try{fail("fail"); 'fail' }catch(e){e.getMessage()} "" + [what1, what2] } ~~~~~ //##70. double check this works def doings(){ "" + int.class } ~~~~~ //##71. fwd ref failure class MyClass{ thing ATHing[]? def getThing(){ if(null == thing){//fwd def not found, used to consider this to be a new value thing = new ATHing[2] } thing } } class ATHing def doings(){ mc = MyClass() "ok" } ~~~~~ //##72. ignore generic when testing to see if we can do an equals on a type class GenCls<X>{ def checker<Y>(compto GenCls<Y> ) => this &== compto } def doings(){ inst = GenCls<String>() "ok " + inst.checker<String>(inst) } ~~~~~ //##73. indirect abstract classes bug abstract class SimpleAbstractClass{ def getThing() String } abstract class Holder(-thing String) < SimpleAbstractClass//com.concurnas.lang.precompiled.SimpleAbstractClass class AlmostHolder(thingx String) < Holder(thingx){ } def doings(){ tt = AlmostHolder("hi") tt.thing } ~~~~~ //##74. define a stub function from com.concurnas.lang import GPUStubFunction @GPUStubFunction def get_work_dim() int def doings() => "ok" ~~~~~ //##75. private class mapping when there is a choice from com.concurnas.lang.precompiled.PrivateClassHeirarchy import ClType1, ClType2 from com.concurnas.lang.precompiled.PrivateClassHeirarchy import ClTypeB1, ClTypeB2 def doings(){ t1 = new ClType1() t2 = new ClType2() things1 = [t1 t2]//not MyAbstract since it's private outside the declaration //maps to ParentOne tb1 = ClTypeB1() tb2 = ClTypeB2() things2 = [tb1 tb2] //maps to Object r1 = "" + (x.getClass().simpleName for x in things1) r2 = "" + (x.getClass().simpleName for x in things2) "" + [ r1 r2] } ~~~~~ //##76. private class can be used like this def doings(){ xx Object = com.concurnas.lang.precompiled.PrivateClassHeirarchy.getInstance() "" + xx.getClass().getSimpleName() } ~~~~~ //##77. local class wrong package name format //##MODULE com.myorg.code2 from com.concurnas.lang import GPUKernelFunctionDependancy def afunc(){ class SrcAndDeps(source String, dependancies String[]?) inst = new SrcAndDeps("hi", null) "hi" } //##MODULE from com.myorg.code2 import afunc def doings(){ "ok" + afunc() } ~~~~~ //##78. bug when defining default map lambda //##MODULE com.myorg.code from java.util import Map def myThing(srctoNode Map<String, int>){ nodeCounter = { default -> def (a int) { 0 } } for(node in srctoNode.values()){ nodeCounter[node]++ } nodeCounter } //##MODULE from com.myorg.code import myThing def doings(){ mmap = {"hi" -> 1 , "there" -> 2 ,"mane" -> 1} "ok " + myThing(mmap)[1] } ~~~~~ //##79. wrong assign type being used on array default values def id(a float[2]) => a def doings(){ a = [1.f 3; 4.f 5] ret=id(a) value = 79 conventional = float[2, 2](0) //bug "" + [ret, conventional, value] } ~~~~~ //##80. fix generics on generic types upper bounded when multi chooice def doings(){ xxx1 = [int.class float.class String.class] xxx2 Class<?>[] = [int.class bool.class] kk = [xxx1, xxx2] 'ok' + kk//ok } ~~~~~ //##81. fix generics above use case private def typeEqual(a Class<?>, b Class<?>){ def unbox(type Class<?>) Class<?> { wtf = match(type){ case(Boolean.class) => boolean.class case(Byte.class) => byte.class case(Character.class) => char.class case(Double.class) => double.class case(Float.class) => float.class case(Integer.class) => int.class case(Long.class) => long.class case(Short.class) => short.class else => type } wtf } unbox(a) == unbox(b) } def doings(){ 'ok' + [typeEqual(int.class, bool.class), typeEqual(int.class, Integer.class)] } ~~~~~ //##82. bug with type convertion for primative type comparison operators public def comp1(a long, b int) { return a > b; } public def comp2(a double, b long) { return a > b; } public def comp3(a int, b long) { return a > b;//LCMP not IF_ICMPLE } public def comp4(a int, b int) { return a > b; } //if either is long then use correct one def doings(){ a = 40 b = Long(4261620736) "{b as int} " + [comp1(a, b as int), comp2(a, b), comp3(a, b), comp4(a, b as int)] } ~~~~~ //##83. bug concerning setting of wanted on stack or not on ast override for funcinvoke which is really a constructor def doings(){ try{ Integer(99) 'ok' }catch(e){ e.message } } ~~~~~ //##84. was a bug with accessability class StatHolder{ package this(timestamp String){ } package this(error int){ } override toString() String => "hi" } class ProfilingInfo{ @com.concurnas.lang.Uninterruptible def statExtractor(a int) StatHolder { if(a <> 1){ StatHolder("hi") }else{ StatHolder(0) } } } def doings(){ mc = ProfilingInfo().statExtractor(1) 'ok'+ mc } ~~~~~ //##85. incorrectly filling in missing value for thing of array type def myThing(a String, b int[], c int[]? = null, d String...){ } def doings(){ myThing("hi", [1 2]) "ok" } ~~~~~ //##86. null to ref with no zero arg constructor cannot do class GPURef<X>(type Class<?>[], ~event int) < com.concurnas.runtime.ref.Local<X>(type){ } def ok<Typex>(a Typex) Typex: { null } def fail<Typex>(a Typex) Typex:GPURef { null//no cannot do this } def doings(){ ok("hi") msg = try{ fail("hi"); 'fail' }catch(e) { e getMessage } "fine " + msg } ~~~~~ //##87. del npe an Object? = null def rem(){ anx = an del anx//check its not null before del to avoid npe } def doings(){ rem() "ok" } ~~~~~ //##88. bridge method genneration open class AbstracParent<T>{//abstract class def getT(a T) T//abastract } class ImpClass < AbstracParent<Integer>{ def getT(an Integer) Integer{//requires a bridge method else moan about missing definition an } } def doings(){ im AbstracParent<Integer> = ImpClass() "" + im.getT(12)//call goes via bridge method } ~~~~~ //##89. assertion string incorrectly processed def thing(a int, b int){ assert a < b "{a} should be less than {b}" "fail" } def doings(){ try{ thing(10, 3) }catch(e){ e getMessage } } ~~~~~ //##90. this ref on prefix op def myFunc(a int, v1 int){ xxx = class(a int, v1 int){ override hashCode() => 1 override equals(an Object) => false def nexter(){ ret = v1 v1 += v1 if a==1 else -v1//was being double visited this ref on second arg cuausing stack frame inconsistancy ret } } xxx(a, v1) } def doings(){ "cool" + [myFunc(1, 44).nexter()] } ~~~~~ //##91. error on null type tagging def ttt() => true myPiggie1 = [null null] if ttt() else [null null] myPiggie2 Object?[] = [null null] if ttt() else [null null] myPiggie3 Integer?[] = [null null] if ttt() else {f=9; [null null]}//was failing to set on else block def doings() String{ return ""+ [myPiggie1, myPiggie2, myPiggie3] } ~~~~~ //##92. problem with label alocation on if else and try catch engine = null def doings(){ xx={ if(null == engine){ 'engine is null' }else{ 'TURDS' } }! xx.get() } ~~~~~ //##93. neg in things decc2 = [-10 1 2 3 4 5] flaotz = [-10. 1 2 3 4 5] flaotz2 = [-10.f 1 2 3 4 5] def doings(){ res1 = -10 in decc2//- was being captured as part of expr res2 = -10. in flaotz res3 = -10.f in flaotz2 "ok: " + [res1, res2, res3] } ~~~~~ //##94. neg for ints in exprlists def int thing(a int){ this + a } def doings(){ x = 10 thing (-1)//only way we can do this "" + x } ~~~~~ //##95. add getter setter if parent class has field accessable open class Sup(protected field int) class Child(val -field int) < Sup(field) def doings(){ c = Child(23) "" + c.field } ~~~~~ //##96. imply generics of argument returning local generic when used in callsite class Maker<T>{ def doer(a T) => a } def getMaker<XXX>() => new Maker<XXX>() class MakerTaker<MyT>(a MyT){ def take(mm Object) => false//mm.doer(a) } def doings(){ mt = MakerTaker<Integer>(12) res = mt.take(getMaker())//can ignore here "" + res } ~~~~~ //##97. imply generics of argument returning local generic when used in callsite v2 class Maker<T>{ def doer(a T){ a } } def getMaker<XXX>() => new Maker<XXX>() class MakerTaker<MyT>(a MyT){ def take(mm Maker<MyT>) MyT => mm.doer(a) } def doings(){ mt = MakerTaker<Integer>(12) res = mt.take(getMaker())//this needs its generic argument qualified "" + res } ~~~~~ //##98. bug fixed relating to generics class GenParaInOut<X>(public ~x X[]){//gets stored as Object[] - but if its an array we need to explicitly convert this into a localarray[int:] override hashCode() => 69 override equals(a Object) => true override toString() => "has: " + x } la = [100, 200] def doings(){ gp = new GenParaInOut(la)//turned out to be a problem with subtyping of generic types and refs //cannot qualify with the above got = gp.x got2 = gp\.x//type was also not correctly extracted here "" + [got, got2] } ~~~~~ //##99. bug since vectorized code was not being copied def doings(){ shared numbers = [1, 2, 3, 4, 5, 6] complete = {numbers += 1; true}! //add one to each element await(complete) ""+numbers } ~~~~~ //##100. bug with defo assignment use within block def tt() => false def doings(){ a String if(tt()){ a = "hi" g=a//used to think it as unset }else{ a = "its false" } "" + a } ~~~~~ //##101. idx fix def doings(){ indxes =0 for(x in 1 to 10; idx){ indxes += idx if(idx == 0){ continue } f=9999 } "ok" + indxes } ~~~~~ //##102. idx fix on while def doings(){ indxes =0L x=0 while(x++ <== 10; idx){ indxes += idx if(idx == 0L){ continue } f=9999 } "ok" + indxes } ~~~~~ //##103. idx fix on while with ret def doings(){ indxes =0L x=0 meme = while(x++ <== 10; idx){ indxes += idx if(idx == 0L){ continue } 9999 } "ok" + [indxes, meme] } ~~~~~ //##104. while ret def doings(){ indxes =0L x=0 meme = while(x++ <== 10){ 9999 }else{ null } "ok" + [indxes, meme] } ~~~~~ //##105. while ret 2 def doings(){ indxes =0L x=0 meme = while(x++ <== 10){ 9999 } "ok" + [indxes, meme] } ~~~~~ //##106. if used to nop def doings(){ indxes =0 for(x in 1 to 10; idx){ indxes += idx if(idx == 0){ continue } } "ok" + indxes } ~~~~~ //##107. if used to nop 2 def doings(){ indxes =0 for(x in 1 to 10; idx){ indxes += idx if(idx == 0){ break } } "ok" + indxes } ~~~~~ //##108. another one def doings(){ indxes =0 motto = for(x in 1 to 10; idx){ indxes += idx if(idx == 0){ continue } idx } "ok" + [indxes, motto] } ~~~~~ //##109. while idx variable problem when defined at module level from java.util import Arrays mm=1000; def doings(){ x=0 one4 = ""+ while(x++ <10; mm) { [mm, mm+x] } "" + one4 } ~~~~~ //##110. for idx variable problem when defined at module level from java.util import Arrays mm=1000; thing = Arrays.asList([new Integer(1) 1 2 2 3 3 4 4 5 5 10]) def doings(){ x=0 one4 = "" for(x in thing; mm) { one4+=[mm mm+x] } "" + one4 } ~~~~~ //##111. ast redirect of expr list needs should be preserved on stack call from java.util import ArrayList def doings(){ range = 0 to 25 az = 'a' + x as char for x in range prefixes = new ArrayList<String>() for(l1 in az){ for(l2 in az){ prefixes add ("" + l1 + l2) } } "" + prefixes.size() } ~~~~~ //##112. ensure idx for for loop is captured correctly def something(a long, b int) => a+b items = 0 to 10 def doings(){ dude = 10 xx = for(x in items; idx){ something(idx, dude)! } "" + (x for x in xx) } ~~~~~ //##113. ensure idx for while loop is captured correctly def something(a long, b int) => a+b items = 0 to 10 def doings(){ dude = 10 a=0 xx = while(a++ < 10; idx){ something(idx, dude)! } "" + (x for x in xx) } ~~~~~ //##114. parfor list compre works def something(){ "ok" } items = 0 to 10 def doings(){ res2 = sync{something()! for a in items} res1 = something() parforsync a in items "" + (res1, res2) } ~~~~~ //##115. used to incorrectly store state def doings(){ x3b = ""+sync{888 } "" + x3b } ~~~~~ //##116. and so this is fine now ar = [1 2 3 4] def doings(){ x3b = ""+sync{ for(n in ar){ {n + 10}! } } //} "" + x3b } ~~~~~ //##117. try catch label allocator needs to ignore things inside async blocks ar = [1 2 3 4] def doings(){ x3b = try{for(na in ar){ {try{ "fine" }finally{p=3}}! }}finally{o=9} "" + x3b } ~~~~~ //##118. try catch label allocator needs to ignore things inside async blocks ar = [1 2 3 4] def doings(){ x3b = parforsync(na in ar){ try{ "fine" }finally{p=3} } "" + x3b } ~~~~~ //##119. bug with nested sync not setting should be kept on stack correctly ar = [1 2 3 4] def doings(){ x3b = for(na in ar){ (sync{for(n in ar){ "x" }})! } "" + x3b } ~~~~~ //##120. set nested ret type ar = [1 2 3 4] def doings(){ x3b = parforsync(na in ar){ ""+parforsync(n in ar){ n + 10 } } "" + x3b } ~~~~~ //##121. nested for list comprehension with parforsync ar = [1 2 3 4] def doings(){ x3b = (a, b) parforsync a in 0 to 1 parforsync b in 0 to 3 "" + x3b } ~~~~~ //##122. bug with imm loader //##MODULE com.myorg.code2 class AbstractClass{ def aMethod() int } //##MODULE from com.myorg.code2 import AbstractClass class MyClass < AbstractClass {//}~ MyTrait def aMethod() => 56 } def doings(){ thing AbstractClass = MyClass() "" + with(thing){ aMethod(), aMethod()} } ~~~~~ //##123. type not being directed to asttype enum Color{ Blue, Green, Yellow } class Record(public age int, public friendcnt int, public name String, public favColor Color){ override toString() => "{age}, {friendcnt}, {name}, {favColor}" } def matcher(an Object){ /*match(an){ Record(age == 2, friendcnt > age) => "record: {an.age}" x => x }*/ with(an as Record) { cpobjCheck = 2 == age; //cpobjCheck and= 2 > age ; cpobjCheck ; } } def doings() { "" + matcher( new Record(2, 3, "Dave", Color.Blue) ) } ~~~~~ //##124. function defined at module leve within a block f=7 x = { def thing(aa int, bb int) => aa+bb + f thing(2, 3) } def doings(){ "" + x } ~~~~~ //##125. function defined at module level within block using external deps f=7 x = { z=100 def thing(aa int, bb int) => aa+bb + f + z thing(2, 3) } def doings(){ "" + x } ~~~~~ //##126. function defined at module level within block using external deps - if stmts f=7 def dd() => true x = { z=100 def thing(aa int, bb int) => aa+bb + f + z thing(2, 3) } if dd() else 3333//ensure that block is correctly marked for capture def doings(){ "" + x } ~~~~~ //##127. looks cool //##MODULE com.myorg.code from com.concurnas.lang.precompiled import JustAClass y boolean: class MyClass def weirf(){ { y=true }! mm = JustAClass.aMethod() y.get() } //##MODULE from com.myorg.code import weirf, MyClass def doings(){ mc = MyClass() "" + weirf() } ~~~~~ //##128. problem with fiberization of globalized clinit //##MODULE com.myorg.code from com.concurnas.lang.precompiled import JustAClass y boolean: def weirf(){ { y=true }! mm = JustAClass.aMethod() y.get()//used to hate this } public xx = weirf() //##MODULE from com.myorg.code import xx def doings(){ "" + xx } ~~~~~ //##129. module level actors class MyClass(a int, b int){ override hashCode() => 1 override equals(an Object) => false override toString() => "cool" } actor X of MyClass{}; def wtf(){ new X(1, 2) } x = wtf() def doings(){ "ok: " + x } ~~~~~ //##130. more module level actors open class ID{ def operate(a int) int => a override hashCode() => 1 override equals(an Object) => false } x = {class Henry < ID{}; actor X of Henry{}; c = new X() c } def doings(){ "" + x.operate(10) } ~~~~~ //##131. try catch labels when wrapping loops etc def sxt1(){ ab=2 h = x =0 try{ while(ab++ < 2){ h=100 } //j=99999 } catch(e){ x=10 }//finally{x=666} (h, x) } def sxt2(){ ab=2 h = x =0 try{ while(ab++ < 2){ h=100 } j=99999 } catch(e){ x=10 }//finally{x=666} (h, x) } def sxt3(){ ab=2 h = x =0 try{ while(ab++ < 2){ h=100 } //j=99999 } catch(e){ x=10 }finally{x=666} (h, x) } def sxt4(){ ab=2 h = x =0 try{ while(ab++ < 2){ h=100 } j=99999 } catch(e){ x=10 }finally{x=666} (h, x) } def doings() String{ "ok: " + [sxt1() sxt2() sxt3() sxt4()] } ~~~~~ //##132. branch implicit and explicit returns def ff()=> false def sdf() void{} def doer1(){ if(ff()){ return 9 }else{ 20//ok } } def doings(){ "" + doer1() } ~~~~~ //##133. constructor ref on new op overload bug on vars class MyGenClass(x String, y String){ override toString() => "MyGenClass " + [x,y] } class MyProvider{ override equals(a Object) => false override hashCode() => 1 def \new(className String, x String, y String) { MyGenClass(x, y) } } def doings(){ a=1 b=2 d=4 mp = MyProvider() what = mp.new MyGenClass&("77", ? String) "" + what('lovely') } ~~~~~ //##134. bridge method not needed for notify below from java.util import ArrayList trait NotificationService<X>{ def notifyx(msg X) } class MessageCapture<X> ~ NotificationService<X>{ public items = new ArrayList<X>() def notifyx(msg X){ items.add(msg);; } } inject class Client<X>(public noti NotificationService<X>){ def doperation(thing X){ noti.notifyx(thing) } } def doings(){ cl Client<String> = new Client<String>(new MessageCapture<String>()) cl.doperation("hi") "ok" + (cl.noti as MessageCapture<String>).items } ~~~~~ //##135. field created by default creator when referenced in supercon avar = 88 open class MyClass( operate int){ override toString() => ""+[avar operate avar] override hashCode() => 1 override equals(an Object) => false } class SubMyClass < MyClass({f = "ok"; 222}){//used to accidentally create a field override toString() => super.toString() override hashCode() => 1 override equals(an Object) => false } def doings(){ xx = SubMyClass() "" + xx } ~~~~~ //##136. lets estimate pi cnt = 20 repeats = 20 def esimatePI(){ incir = 0. x=0 xs = java.util.Random().doubles().iterator() while(x++ <== cnt){ if((xs.next()**2 + xs.next()**2)**.5 <== 1){ incir++ } } (incir/cnt)*4 } actor Accumilator(stopon int){ ~done boolean: ~sofar double: private accumilatedAnswer double=0 private resCnt=0 def addRes(ans double){ if(resCnt < stopon){ accumilatedAnswer += ans sofar = accumilatedAnswer/++resCnt if(resCnt == stopon){ done=true } } resCnt == stopon } } def doings(){ acc = Accumilator(repeats) for(n = 0; n < Concurnas.cores(); n++){ { loop{ if(acc.addRes(esimatePI())){ break } } }! } await(acc.done) //await(acc.done; acc.done as boolean) //await(acc.done; acc.done) "complete: {acc.sofar:get() as int}" } ~~~~~ //##137. fix locked ref cast actor Thing{ ~a boolean: = false } def doings(){ t = Thing() "ugh" + (t.a as boolean)//unsed to be unable to cast in this way as ref from function call is locked } ~~~~~ //##138. fix locked ref cast 2 cnt = 10 repeats = 10 def esimatePI(){ incir = 0. x=0 xs = java.util.Random().doubles().iterator() while(x++ <== cnt){ if((xs.next()**2 + xs.next()**2)**.5 <== 1){ incir++ } } (incir/cnt)*4 } actor Accumilator(stopon int){ ~done boolean: ~sofar double: private accumilatedAnswer double=0 private resCnt=0 def addRes(ans double){ if(resCnt < stopon){ accumilatedAnswer += ans sofar = accumilatedAnswer/++resCnt if(resCnt == stopon){ done=true } } resCnt == stopon } } def doings(){ acc = Accumilator(repeats) for(n = 0; n < Concurnas.cores(); n++){ { loop{ if(acc.addRes(esimatePI())){ break } } }! } //await(acc.done) await(acc.done; acc.done as boolean) //await(acc.done; acc.done) got = "{acc.sofar:get() as int}" "complete: " + (got in ["2", "3"]) } ~~~~~ //##139. can extend Function0 cnt = 0 class Thing < com.concurnas.bootstrap.lang.Lambda.Function0<Void?>(null){//ignore InvokeUncreatable object def apply() Void? => cnt++; null } def doings(){ inst = Thing() inst.apply() "" + cnt } ~~~~~ //##140. five ways to access a thing exending function0 cnt = 0 class Thing < com.concurnas.bootstrap.lang.Lambda.Function0<Void?>(null){ def apply() Void? => cnt++; null } def doings(){ inst = Thing() inst.apply() (inst as Object as () Void)() (inst as Object as com.concurnas.bootstrap.lang.Lambda.Function0<Void>)() (inst as Object as () Void)() (inst as com.concurnas.bootstrap.lang.Lambda.Function0<Void>)() "" + cnt } ~~~~~ //##141. generic type upper bound on rhs can be set to type of upper bound on lhs class TakesGen<X Number>{ def thing(an Another<X>) => an def xxx(an X){ b Number = an //used to extract X as Object which is incorrect as upper bound is Number } } class Another<X Number>{ override toString()=> "hi" } def doings() => ""+TakesGen<int>().thing(Another<int>()) ~~~~~ //##142. has line number for lambda def doer(thing (String?) String ) => thing(null) def doings(){ "has line number for lambda " + try{ doer(a String? => "" + a??.charAt(0)) }catch(e){ e.getStackTrace()[0].getLineNumber() > 0 } } ~~~~~ //##143. local class may have references to external vars trait AThing{ def doit(an int) int } def doings(){ bb=90 xx = new AThing{ def doit(an int) => an + bb } "ok" + xx.doit(10) } ~~~~~ //##144. nested inner var use default var trait AThing{ def doit(an int) int } def maker(attempts = 10) AThing{ attemptsn = attempts xx = new AThing{ def doit(an int) => an + attempts//n } xx } def doings(){ bb=90 xx = maker() "ok" + xx.doit(10) } ~~~~~ //##145. nested inner var use default var 2 trait AThing{ def doit(an int) int } def maker(attempts int = 10) AThing{//? attemptsn = attempts xx = new AThing{ def doit(an int) => an + attempts//n } xx } def doings(){ bb=90 xx = maker() "ok" + xx.doit(10) } ~~~~~ //##146. bug with funcrefs with no args having captured vars def provideLoggerFor(middle String) (String) String{ def defaultLogger(msg String) => "{middle} {msg}" return defaultLogger&//(String) } def doings(){ thing = provideLoggerFor("hi") "" + thing("message") } ~~~~~ //##147. actor constructor with default args actor MyActor1(a int, b =100){ override hashCode () => 1 override equals(an Object) => false } def doings(){ ma = MyActor1(12) "ok" } ~~~~~ //##148. actor method with default args actor MyActor2{ override hashCode () => 1 override equals(an Object) => false def something(attempts = 10) => attempts } def doings(){ ma = MyActor2() "ok" + ma.something() } ~~~~~ //##149. local class as default param DEFAULT_CONC_PORT = 42000 trait LoggerProvider(){ def provideLoggerFor(theClass Class<?>) (String) void } private shared dateLog = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z"); private defaultLoggerProvider = new LoggerProvider{ def provideLoggerFor(theClass Class<?>) (String) void{ className String = theClass getSimpleName def defaultLogger(msg String){ System.out.println("{dateLog.format(new java.util.Date())} {className} {msg}") } return defaultLogger& } } class MyClass(~thing int = DEFAULT_CONC_PORT, dlx = defaultLoggerProvider){ override hashCode() => 1 override equals(an Object) => false } def doings(){ mc = new MyClass() ""+mc.thing } ~~~~~ //##150. override trait method differing ret type trait MyTrait{ def echo() MyTrait } class MyClass ~ MyTrait{ def echo() MyClass => this override toString() => "its ok" } def doings(){ mc= new MyClass() "ok " + mc.echo() } ~~~~~ //##151. override super method differing ret type open class MyTrait{ def echo() MyTrait } class MyClass < MyTrait{ def echo() => this override toString() => "its ok" } def doings(){ mc= new MyClass() "ok " + mc.echo() } ~~~~~ //##152. override super method differing ret type - both trait MyTrait{ def echo1() MyTrait } open class SupClass{ def echo2() SupClass } class MyClass < SupClass ~ MyTrait{ def echo1() => this def echo2() => this override toString() => "its ok" } def doings(){ mc= new MyClass() "ok " + [mc.echo1() mc.echo2()] } ~~~~~ //##153. catch blocks throwing bug tt = 9 def thing(){ try{ while(tt++ < 12){ if(tt){ 12 } } }catch(e){ throw e } } def doings() => "uh oh" + thing() ~~~~~ //##154. bc genneration for await was incorrect //##MODULE com.myorg.code2 def domthins(an int:){ await(an)//was gennerated wrong code path } //##MODULE def doings(){ com.myorg.code2.domthins(12:) "ok" } ~~~~~ //##155. bc genneration for classreferences was incorrect //##MODULE com.myorg.code2 from java.util import Iterator x=0 def iterator() Iterator<Integer>{ ret = class() ~ Iterator<Integer>{ def hasNext(){ x++ < 10 } def next() Integer{ x } } ret() } //##MODULE def doings(){ com.myorg.code2.iterator() "ok" } ~~~~~ //##156. ret lambda ok def mayRetLAmbda() (String) String{ def (a String) => a } def doings(){ "" + mayRetLAmbda()("ok") } ~~~~~ //##157. do things with pre compiled variable the long way //##MODULE com.myorg.code2 public shared a Integer = 100 //##MODULE com.myorg.code2.a = 23//the long way def doings(){ "ok" + com.myorg.code2.a } ~~~~~ //##158. functype needs to treat int params as Integer etc from com.concurnas.tests.helpers.traits import OperationOnIntList from java.util import List class Imp ~ OperationOnIntList{ def ack1(input List<int>) (int) int => input.get&(int) def ack2(input List<int>) => input.get&(int) } input = [1, 2, 3] def doings(){ ii = Imp() "" + [ii.ack1(input)(0) ii.ack2(input)(0)] } ~~~~~ //##159. from primative to other boxed type an = 2 def doings(){ x1 double = an x2 = an as double t1 Double = an t2 = an as Double "" + [x1 x2 t1 t2] } ~~~~~ //##160. from boxed to other boxed type an = Integer(2) def doings(){ x1 double = an x2 = an as double t1 Double = an t2 = an as Double "" + [x1 x2 t1 t2] } ~~~~~ //##161. check protected open class Sup{ protected def prot() => 1 private def priv() => 1 } class Child < Sup{ def somet(supinst Sup){ a = super.prot() b = supinst.prot()//same package so ok (a, b) } } def doings(){ cc = Child() "" + cc.somet(cc) } ~~~~~ //##162. injectable actor double create constructor err inject actor TaskStore {//used to genenrate two injectable methods def setSuccess(taskId long, another long, something Object ){ } } def doings(){ ts = new TaskStore() "ok" } ~~~~~ //##163. inf loop bug res boolean: done boolean:=false def thing(){ x=0 while(true){//for(x in 0 to 10){//TODO: why loop fails? if(x==10){ res=true; } if(done){ return } x++;; } } def doings(){ thing()! await(res) done = true "ok" } ~~~~~ //##164. reset local var counter at end of isolated block with direct parent being module level from java.util import HashMap, HashSet enum Protocol{ sERROR, cERROR, cCONNECT, sCONNECT_OK, sCONNECT_AUTH_NEEDED, cDISCONNECT, cSUBMIT, sRESPONSE, cHEARTBEAT, sHEARTBEAT, sREQUESTDEPENDENCY, cPROVIDEDEPENDENCY; def getCode() long => this.ordinal() } codeToProtocol = new HashMap<long, Protocol>() {//this block was affecting the local variable counter for(p in Protocol.values()){ codeToProtocol[p.code] = p } } enum TaskStatus{ PENDING, FAIL, SUCCESS def getCode() long => this.ordinal() } def doings(){ ts = TaskStatus.SUCCESS "" + ts } ~~~~~ //##165. can throw thing held in ref def what(){ tothrow Throwable: = new RuntimeException("hi") throw tothrow } def doings(){ "" + try{ what() "fail" }catch(e){ e } } ~~~~~ //##166. custom ref param convertion for primative array types from com.concurnas.lang import BlockingLocalRef from java.util import HashMap class DistClassStore{ private nameToBytecode = new HashMap<String, byte[]:BlockingLocalRef>()//TODO: default map would be better here def getBytecode(name String) byte[]:BlockingLocalRef { if(name not in nameToBytecode){ toFetch byte[]:BlockingLocalRef nameToBytecode[name] = toFetch //nameToBytecode.put(name, toFetch:) } nameToBytecode[name] } def onClientDisconnect(){ for(name in nameToBytecode){ nameToBytecode[name]:setException(null) } } def onClientRespond(name String, code byte[]){ if(name in nameToBytecode){ nameToBytecode[name] = code }else{ br byte[]:BlockingLocalRef br = code nameToBytecode[name] := br } } def onClientMissingClass(name String){ if(name not in nameToBytecode){ toFetch byte[]:BlockingLocalRef nameToBytecode[name] = toFetch } nameToBytecode[name]:setException(null) } } def doings(){ "ok" } ~~~~~ //##167. bugfix try catch label nested in if def tt() => false def tryme(){ if(tt()){ try{ 12 }catch(e){ 13 } }else{ 999 } } def doings(){ "ok" } ~~~~~ //##168. catch may return something def something(name String) byte[] => null def somethingelse(name String) byte[] => throw new Exception("uh oh") def getBytecode(name String) Object{//check parent first fromParent = something(name) if(fromParent == null){ try{ somethingelse(name) }catch(e){ return null } }else{ "clive" } } def doings() { "ok" + (getBytecode "ok") } ~~~~~ //##169. checkcast on array return type bugfix def thing() Integer[] { things = [Integer(1) 2 3 4] things[0 ... 2] //before this was not being checkcasted to the correct expected type } def doings(){ "ok"+thing() } ~~~~~ //##170. bug on idx casting type def getThings() { rtest = [1 2 3 4 5] gens = new int[rtest.length] for(x in 0 to rtest.length-1){ gens[x] = 0//x is an Integer, so we cast to int } gens } def doings(){ "" + getThings() } ~~~~~ //##171. bug on position of created for loop variable with same name from com.concurnas.bootstrap.runtime.cps import IsoTask from com.concurnas.lang import DependencyAnalyzer from com.concurnas.runtime import ConcurnasClassLoader from java.util import HashMap, Set, HashSet, List, ArrayList from com.concurnas.lang.offheap.serialization import SerializationEncoder, SerializationDecoder private class Dependancy(public val depName String, public val code byte[]){ public def getSucess() => code <> null } log (String) void = def(a String){ System.out.println(a); } connected = true def connect() => ;; def gennerateRequestId(task IsoTask<Object:>) => 1l def request(task IsoTask<Object:>){ taskName = "jobName" cls = 'cls' clsName = 'clsName' depKeys Set<String>? = null ohkevin = "ohkevin" for(clsName in depKeys??){//was casuing origonal var to be created in wrong slot //mostDeps.add(new Dependancy(clsName, depMap[clsName] as byte[])) } ohkevin = "kevinwhy" log("...Request submit for iso: {clsName} with Jobname: {taskName}, requestId: , with dependencies: {depKeys}") //submit request and run } def doings(){ "ok" } ~~~~~ //##172. catch can return what=9 def thing(){ what = try{ 12 }catch(e){ return// doesnt adversly affect the return value of the try block - thats still int } //what } def doings(){ "ok" + [what, { thing(); what}] } ~~~~~ //##173. lca type of tuples defined as par below from java.util import Set, List, ArrayList, HashSet class Dependency(name String, code byte[]) def thingy() (Set<String>, ArrayList<Dependency>){ new HashSet<String>(), new ArrayList<Dependency>() } def tt() => true def user(a Set<String>, b ArrayList<Dependency>){ "ok" } def doings(){ (a, b) = if(tt()){ thingy() }else{ new HashSet<String>(), new ArrayList<Dependency>() } user(a, b) } ~~~~~ //##174. lambda gen signature corrected for arrays class OnCopy(-x = 0){ def inc() => x++ override hashCode() => 1 override equals(an Object) => false } def runIncer(a OnCopy[]) => a^inc() def runIncerSingle(a OnCopy) => a.inc() def doings(){ shared oc1 = OnCopy() shared oc2 = OnCopy() x1 = {f = 100; runIncer&([oc1 oc2])}! x2 = {f = 100; runIncerSingle&(oc1)}! res1 = x1() res2 = x2() "" + [oc1.x, oc2.x, res1, res2] }//0,0 ~~~~~ //##175. return from catch needs convertion to object type def something(){ throw new Exception("me") } def callanother() void{} def doings(){ res = try{ something() "fail" }catch(e){ 'me' in '{e}'//needs convertion to object } finally{ callanother() } "ok" + res } ~~~~~ //##176. trans block missing isolated=true on main work block def tt() => true def doings(){ x := { if(tt()){ throw new Exception("uh oh") } 22 }! await(x) trans{ if(not x:hasException()){ x:setException(new Exception("another")) } } try{ "fail: " + x }catch(e){ "" + e.getMessage() } } ~~~~~ //##177. allow dot over multiple lines from java.util.stream import Collectors from java.util import List def doings(){ mylist = [1, 2, 3, 4, 5] a1 = mylist.stream() .map( def (a int) { a+10 } ) .collect(Collectors.toList()) a2 = mylist.stream().map( def (a Integer) { a+10 } ).collect(Collectors.toList()) a3 = mylist.stream().map(a int => a+10).collect(Collectors.toList()) a4 = mylist.stream().map(a => a+10).collect(Collectors.toList()) "" + [a1 a2 a3 a4] } ~~~~~ //##178. transactions is closed def doings(){ ok String: done int: every(ok){ trans{ ok.close() done = 1 } } ok = "" await(done) "" + ok:isClosed() } ~~~~~ //##179. sub string expressions - nested def doings(){ f=9 g=8 ""+for(x in [false true]){ "hey: {'one:{f}' if x else 'two:{g}'} nice {6} ok" } } ~~~~~ //##180. sub string expressions - none def doings(){ f=9 g=8 ""+for(x in [false true]){ "hey: " } } ~~~~~ //##181. sub string expressions - starts with thing def doings(){ f=9 g=8 ""+for(x in [false true]){ "{2+2}" } } ~~~~~ //##182. sub string expressions - escape char def doings(){ f=9 g=8 ""+for(x in [false true]){ "\{2+2}" } } ~~~~~ //##183. sub string expressions - failed def doings(){ f=9 g=8 ""+for(x in [false true]){ "f {2+2 sdf" } } ~~~~~ //##184. neste neste def tt()=> true def doings(){ avar = "something" //"result is: {'got: {avar}' if tt() else 'nope'}" //"result is: {avar}" "result{ {avar} }" } ~~~~~ //##185. bugfix on op overload redirect def doings() { InitialA = 100 b := 0 a := InitialA calls := "" done :=false cnt:=0 xx = async{ pre{ lastVal Integer? = null } onchange(a,b){ if(null <> lastVal){ if(lastVal <== a)//op overload - was not being nested repointed as op overload was being overwritten { return false } } lastVal = a cnt++ true } } n=0 while(n++<InitialA){ { trans{ a--; b++; } }! } await(cnt, xx ; (not xx) or cnt==InitialA) "" + [a,b, xx] } ~~~~~ //##186. bugfix on op overload redirect pt 2 InitialA = 100 b := 0 def doings() { a := InitialA calls := "" done :=false cnt:=0 xx = async{ pre{ lastVal Integer? = null } onchange(a,b){ if(null <> lastVal){ if(lastVal <== a) { return false } } lastVal = a cnt++ true } } n=0 while(n++<InitialA){ { trans{ a--; b++; } }! } await(cnt, xx ; (not xx) or cnt==InitialA) "" + [a,b, xx] } ~~~~~ //##187. loop idx ddefault to int from java.util import List def doings(){ alist = 0 to 20 step 4 what List<(int, int)> = for(a in alist; idx ){ (idx, a) } "ok: " + what } ~~~~~ //##188. loop idx take thing on righ from java.util import List def doings(){ alist = 0 to 20 step 4 what0 List<(int, int)> = for(a in alist; idx ){ (a, idx) } what1 List<(int, long)> = for(a in alist; idx = 0l){ (a, idx) } what2 List<(int, long)> = for(a in alist; idx long = 0l){ (a, idx) } what3 List<(int, long)> = for(a in alist; idx long){ (a, idx) } "ok: " + [what0, what1, what2, what3] } ~~~~~ //##189. loop idx take thing on righ - while from java.util import List def doings(){ n=0; what0 List<(int, int)> = while(n++ < 4; idx ){ (n, idx) } n=0; what1 List<(int, long)> = while(n++ < 4; idx = 0l){ (n, idx) } n=0; what2 List<(int, long)> = while(n++ < 4; idx long = 0l){ (n, idx) } n=0; what3 List<(int, long)> = while(n++ < 4; idx long){ (n, idx) } n=0; what4 List<(int, int)> = while(n++ < 4; idx int){ (n, idx) } "ok: " + [what0, what1, what2, what3, what4] } ~~~~~ //##190. loop idx take thing on righ - loop from java.util import List def doings(){ n=0; what0 List<(int, int)> = loop(idx ){ if(n++ > 4){ break}; (n, idx) } n=0; what1 List<(int, long)> = loop(idx = 0l){ if(n++ > 4){ break}; (n, idx) } n=0; what2 List<(int, long)> = loop(idx long = 0l){if(n++ > 4){ break}; (n, idx) } n=0; what3 List<(int, long)> = loop(idx long){if(n++ > 4){ break}; (n, idx) } n=0; what4 List<(int, int)> = loop(idx int){if(n++ > 4){ break}; (n, idx) } "ok: " + [what0, what1, what2, what3, what4] } ~~~~~ //##191. example from book def doings(){ items = [2 3 4 5 2 1 3 4 2 2 1] res1 = for(x in items; idx) { "{x, idx}" }//idx implicitly set to 0 res2 = for(x in items; idx long) { "{x, idx}" }//idx implicitly set to 0L res3 = for(x in items; idx = 100) { "{x, idx}" } res4 = for(x in items; idx long = 100) { "{x, idx}" } alreadyIdx = 10//index defined outside of loop res5 = for(x in items; alreadyIdx) { "{x, alreadyIdx}" } "ok: " + [res1, res2, res3, res4, res5] } ~~~~~ //##192. example from book 2 def doings(){ items = [2 3 4 5 2 1 3 4 2 2 1] n=0; res1 = while(n++ < 10; idx) { "{n, idx}" }//idx implicitly set to 0 n=0; res2 = loop(idx) {if(n++ > 10){break} "{n, idx}" }//idx implicitly set to 0L "ok: " + [res1, res2] } ~~~~~ //##193. null on funcref used to blow up def funcNullable(a String?){ } def doings(){ y=funcNullable&(null)//ok now "err" } ~~~~~ //##194. tests from manual class Complex(real double, imag double){ def +(other Complex) => new Complex(this.real + other.real, this.imag + other.imag) def +(other double) => new Complex(this.real + other, this.imag) def +=(other Complex) => this.real += other.real; this.imag += other.imag def +=(other double) => this.real += other override toString() => "Complex({real}, {imag})" } c1 = Complex(2, 3) c2 = c1@ c3 = c1@ c4 = Complex(3, 4) result1 = c1 + c4 result2 = c1 + 10. c2 += c4 //compound plus assignment c3 += 10.//compound plus assignment def doings(){ "" + [result1, result2, c2, c3] } ~~~~~ //##195. used to blow up def int gbp() => this def long mil() => this*1000000L def doings(){ "ok" + 1 .. mil ( ) . gbp ( ) } ~~~~~ //##196. bug on choice of items if one or more void def dsf() => true def thing(){//returns void now if(dsf()){ a = 9 }else{ dsf() } } def doings(){ "ok" } ~~~~~ //##197. similar bug to above unecisary cast trait NotificationService{ def notify(msg String) } def sdf() => false class ConsoleNotify ~ NotificationService{ def notify(msg String){ if(sdf()){ a=3 }else{ System err println msg } } } def doings() => "oh" ~~~~~ //##198. nice little filter and lazy example from java.util import Iterator, NoSuchElementException private class Filtered(src Iterator<int>, op (int) boolean) ~ Iterator<Integer>{//TODO allow prim here nextVal Integer? def hasNext(){ null <> obtainNext() } def obtainNext(){ if(nextVal == null){ while(src.hasNext()){ candi = src.next() if(op(candi)){ nextVal = candi break }//bug here with loop jump } } nextVal } def next() Integer{ ret = obtainNext() this.nextVal = null if(null == ret){ throw new NoSuchElementException(); } ret?? as int } } class Thing(me Iterable<int>, op (int) boolean) ~ Iterable<int>{ def iterator() => Filtered(me.iterator(), op) } def Iterable<int> filter(op (int) boolean) Iterable<int> { new Thing(this, op) } def Iterable<int> sum(){ ret = 0L; for(x in this){ ret += x} ret } lazy slowValue = {(1 to 1000).filter(x => x mod 113 == 0).sum()} def doings(){ "" + slowValue } ~~~~~ //##199. bug concerning local classes in extension functions from java.util import Iterator, NoSuchElementException private class Filtered(src Iterator<int>, op (int) boolean) ~ Iterator<Integer>{//TODO allow prim here def hasNext(){ true } def next() Integer{ 1 } } def Iterable<int> filter(op (int) boolean) Iterable<int> { class Thing(me Iterable<int>, op (int) boolean) ~ Iterable<int>{ def iterator() => Filtered(me.iterator(), op) }//due to this new Thing(this, op) } def doings(){ "ok" } ~~~~~ //##200. ext funcs lazy eval with anon class from java.util import Iterator, NoSuchElementException private class Filtered(src Iterator<int>, op (int) boolean) ~ Iterator<Integer>{//TODO allow prim here nextVal Integer? def hasNext(){ null <> obtainNext() } def obtainNext(){ if(nextVal == null){ while(src.hasNext()){ candi = src.next() if(op(candi)){ nextVal = candi break }//bug here with loop jump } } nextVal } def next() Integer{ ret = obtainNext() this.nextVal = null if(null == ret){ throw new NoSuchElementException(); } ret?? as int } } def Iterable<int> filter(op (int) boolean) Iterable<int> { me = this new Iterable<int>{ def iterator() => Filtered(me.iterator(), op) } } def Iterable<int> sum(){ ret = 0L; for(x in this){ ret += x} ret } lazy slowValue = {(1 to 1000).filter(x => x mod 113 == 0).sum()} def doings(){ "" + slowValue } ~~~~~ //##201. ext funcs lazy eval with anon class and local class from java.util import Iterator, NoSuchElementException def Iterable<int> filter(op (int) boolean) Iterable<int> { src = this new Iterable<int>{ def iterator(){ class Filtered(src Iterator<int>, op (int) boolean) ~ Iterator<int>{//trait quali can be prim which gets boxed nextVal Integer? def hasNext(){ null <> obtainNext() } def obtainNext(){ if(nextVal == null){ while(src.hasNext()){ candi = src.next() if(op(candi)){ nextVal = candi break }//bug here with loop jump } } nextVal } def next() Integer{ ret = obtainNext() this.nextVal = null if(null == ret){ throw new NoSuchElementException(); } ret?? as int } } new Filtered(src.iterator(), op) } } } def Iterable<int> sum(){ ret = 0L; for(x in this){ ret += x} ret } lazy slowValue = {(1 to 1000).filter(x => x mod 113 == 0).sum()} def doings(){ "" + slowValue } ~~~~~ //##202. bug now ok from com.concurnas.tests.helpers.distHelpers import EverythingToParentButClassLoader def doings(){ ebcl = EverythingToParentButClassLoader() "ok" } ~~~~~ //##203. jumps bug from java.util import ArrayList def matcher(a Object){ kk="" match(a){ case(x int){ kk="small" } case(x String){ kk="said hi" } } kk } def doings(){ "" + [matcher(2), matcher(3), matcher("hello"), matcher(new ArrayList<String>())] } ~~~~~ //##204. invokedynamic was not passing the fiber from com.concurnas.lang.precompiled import TestInvokeDynamic def doings(){ TestInvokeDynamic.runIt() "ok" } ~~~~~ //##205. invokedynamic bugfix from java.nio.file import Paths, Path, Files from java.util.stream import Collectors def readFile(ppath Path) { try(lines = Files.lines(ppath)){ String.join("\n", lines.collect(Collectors.toList())) } } private def processFile(ppath Path){ data String = readFile(ppath) data } def convertDoc(fname String){ ppath = Paths.get(fname) processFile ppath } def doings(){ "" + convertDoc("./tests/assets/text.txt") } ~~~~~ //##206. invokedynamic bugfix - alt method from java.nio.file import Paths, Path, Files from java.util.stream import Collectors dx=Collectors.joining("\n") def readFile(ppath Path) { try(lines = Files.lines(ppath)){ lines.collect(dx) //lines.collect(Collectors.toList()) } } def doings(){ "" + readFile(Paths.get("./tests/assets/text.txt")) } ~~~~~ //##207. partially qualified lambda expr import java.util.stream.Collectors; def doings(){ ret = (1 to 15).stream().map((a int) => "{a}").collect(Collectors.toList()) "" + ret } ~~~~~ //##208. nested inner func mapping with default params def myMethod(){ ar = new list<String>() def processTextNode(line String, sec = false) void { ar.add(line) }//nested inner function with default params being incorrectly created processTextNode("") } def doings(){ myMethod() "fine" } ~~~~~ //##209. bug on tuplederef within for loop things = zip([1, 2, 3], [4, 5, 6]) def doings(){ res1= for( (a, b) in things){//foreced as new now b } res2=for( (a, b) in things){ a } "" + [res1, res2] } ~~~~~ //##210. import star class from java.util import * def doings(){ "ok" + new ArrayList<String>() } ~~~~~ //##211. import star static assets from com.concurnas.lang.precompiled.ImportStar import * def doings(){ "ok" + [anInteger afunction()] } ~~~~~ //##212. onchange was not utilizing existing return value ref a = 1: b = 2: ccc <= a + b; def doings(){ "ok" + ccc } ~~~~~ //##213. top level every and await a = 1: b = 2: ccc <= a + b; a=100; await(ccc; ccc == 102) def doings(){ "ok" + ccc } ~~~~~ //##214. const folding bugfix def doings(){//folding constants div = 3/2.//this was incorrect before mul = 3*2. mo = 3 mod 2 plus1 = 2 + 3. plus2 = 2. + 3 eq1 = 2 == 2. eq2 = 2. == 2 "" + (div, mul, mo, plus1, plus2, eq1, eq2) } ~~~~~ //##215. syntax err previously for tuple declaration class Holder(a int) def doings(){ lowhigh (Holder, Holder, Holder) "ok" } ~~~~~ //##216. syntax err previously for tuple declaration async class Holder(a int) def doings(){ lowhigh (Holder, Holder, Holder): "ok" } ~~~~~ //##217.parfor or for at top level result1 = for(b in 0 to 5){ {b+1000}! } result2 = parfor(b in 0 to 5){ b+1000 } def doings(){ "hi: " + (result1, result2) } ~~~~~ //##218. op overload on a ref def doings(){ aa String: = "ok" "" + aa[1] } ~~~~~ //##219. nice little map function def java.util.List<X> map<X>(func (X) X) => func(x) for x in this def java.util.List<X> map2<X>(func (X) X) => xx java.util.List<X> = this; func(x) for x in xx def doings(){ "" + [1, 2, 3, 4].map(x => x+10).map2(x => x+10) } ~~~~~ //##220. top level nesting of for loop within isolate def log(formatString String, args Object...) => 1//System.out.println(String.format(formatString, args)) for(x in [1 2 3 4 5]){ {for(z in [1 2 3 4 5]){ p = z } log "hello world %s" x}! } def doings(){ "ok" }
{ "pile_set_name": "Github" }
%YAML 1.1 --- ### NOTE: Partial schemas("include", "schema") is "pykwalify" extension. ### Sometimes "required" does not function in partial schema. ## "cmd" item schema schema;cmd_schema: type: map mapping: "cmd_type": type: str enum: [ds, shell] required: true "cmd": type: str required: true "result": type: str "timeout": type: int default: 30 ## "cmds" item schema schema;cmds_schema: required: true type: seq sequence: - type: map mapping: "repetition_count": type: int range: {min: 1} default: 1 "repetition_time": type: int range: {min: 1} # minutes "cmds": type: seq required: true sequence: - include: cmd_schema ## TOP level schema type: map mapping: "use": type: seq sequence: - type: str enum: [lagopus, ryu] "mode": type: str enum: [sync, async] "setup": include: cmds_schema "teardown": include: cmds_schema "testcases": type: seq required: true sequence: - type: map mapping: "testcase": type: str required: true "test": required: true include: cmds_schema
{ "pile_set_name": "Github" }
> Task :compileJava FROM-CACHE
{ "pile_set_name": "Github" }
package org.simpleflatmapper.jdbc.converter.time; import org.simpleflatmapper.converter.Context; import org.simpleflatmapper.converter.ContextualConverter; import java.sql.Time; import java.time.OffsetTime; import java.time.ZoneOffset; public class TimeToOffsetTimeConverter implements ContextualConverter<Time, OffsetTime> { private final ZoneOffset offset; public TimeToOffsetTimeConverter(ZoneOffset offset) { this.offset = offset; } @Override public OffsetTime convert(Time in, Context context) throws Exception { if (in == null) return null; return in.toLocalTime().atOffset(offset); } }
{ "pile_set_name": "Github" }
#!/bin/bash # # Copyright 2015 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # momcwrapper runs momc and zips up the output. # This script only runs on darwin and you must have Xcode installed. # # $1 OUTZIP - the path to place the output zip file. # $2 NAME - output file name set -eu MY_LOCATION=${MY_LOCATION:-"$0.runfiles/bazel_tools/tools/objc"} REALPATH="${MY_LOCATION}/realpath" WRAPPER="${MY_LOCATION}/xcrunwrapper.sh" OUTZIP=$("${REALPATH}" "$1") NAME="$2" shift 2 TEMPDIR=$(mktemp -d "${TMPDIR:-/tmp}/momcZippingOutput.XXXXXX") trap "rm -rf \"$TEMPDIR\"" EXIT $WRAPPER momc "$@" "$TEMPDIR/$NAME" # Need to push/pop tempdir so it isn't the current working directory # when we remove it via the EXIT trap. pushd "$TEMPDIR" > /dev/null # Reset all dates to Zip Epoch so that two identical zips created at different # times appear the exact same for comparison purposes. find . -exec touch -h -t 198001010000 {} \+ # Added include "*" to fix case where we may want an empty zip file because # there is no data. zip --compression-method store --symlinks --recurse-paths --quiet "$OUTZIP" . --include "*" popd > /dev/null
{ "pile_set_name": "Github" }
// Copyright 2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pretty import ( "fmt" "strings" "testing" ) type S struct { X int Y bool z *string } func TestSprint(t *testing.T) { Indent = "~" i := 17 for _, test := range []struct { value interface{} want string }{ // primitives and pointer {nil, "nil"}, {3, "3"}, {9.8, "9.8"}, {true, "true"}, {"foo", `"foo"`}, {&i, "&17"}, // array and slice {[3]int{1, 2, 3}, "[3]int{\n~1,\n~2,\n~3,\n}"}, {[]int{1, 2, 3}, "[]int{\n~1,\n~2,\n~3,\n}"}, {[]int{}, "[]int{}"}, {[]string{"foo"}, "[]string{\n~\"foo\",\n}"}, // map {map[int]bool{}, "map[int]bool{}"}, {map[int]bool{1: true, 2: false, 3: true}, "map[int]bool{\n~1: true,\n~3: true,\n}"}, // struct {S{}, "pretty.S{\n}"}, {S{3, true, ptr("foo")}, "pretty.S{\n~X: 3,\n~Y: true,\n~z: &\"foo\",\n}"}, // interface {[]interface{}{&i}, "[]interface {}{\n~&17,\n}"}, // nesting {[]S{{1, false, ptr("a")}, {2, true, ptr("b")}}, `[]pretty.S{ ~pretty.S{ ~~X: 1, ~~z: &"a", ~}, ~pretty.S{ ~~X: 2, ~~Y: true, ~~z: &"b", ~}, }`}, } { got := fmt.Sprintf("%v", Value(test.value)) if got != test.want { t.Errorf("%v: got:\n%q\nwant:\n%q", test.value, got, test.want) } } } func TestWithDefaults(t *testing.T) { Indent = "~" for _, test := range []struct { value interface{} want string }{ {map[int]bool{1: true, 2: false, 3: true}, "map[int]bool{\n~1: true,\n~2: false,\n~3: true,\n}"}, {S{}, "pretty.S{\n~X: 0,\n~Y: false,\n~z: nil,\n}"}, } { got := fmt.Sprintf("%+v", Value(test.value)) if got != test.want { t.Errorf("%v: got:\n%q\nwant:\n%q", test.value, got, test.want) } } } func TestBadVerb(t *testing.T) { got := fmt.Sprintf("%d", Value(8)) want := "%!d(" if !strings.HasPrefix(got, want) { t.Errorf("got %q, want prefix %q", got, want) } } func ptr(s string) *string { return &s }
{ "pile_set_name": "Github" }
Please distribute this file with the SDL runtime environment: The Simple DirectMedia Layer (SDL for short) is a cross-platform library designed to make it easy to write multi-media software, such as games and emulators. The Simple DirectMedia Layer library source code is available from: https://www.libsdl.org/ This library is distributed under the terms of the zlib license: http://www.zlib.net/zlib_license.html
{ "pile_set_name": "Github" }
# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2014-03-22 16:34+EET\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: ENCODING\n" "Generated-By: pygettext.py 1.5\n" #: config.py:42 msgid "Would you like to add some bad words?" msgstr "" #: config.py:43 msgid "What words? (separate individual words by spaces)" msgstr "" #: config.py:55 msgid "" "Determines what words are\n" " considered to be 'bad' so the bot won't say them." msgstr "" #: config.py:58 msgid "" "Determines whether the bot will require bad\n" " words to be independent words, or whether it will censor them within other\n" " words. For instance, if 'darn' is a bad word, then if this is true, 'darn'\n" " will be censored, but 'darnit' will not. You probably want this to be\n" " false. After changing this setting, the BadWords regexp needs to be\n" " regenerated by adding/removing a word to the list, or reloading the\n" " plugin." msgstr "" #: config.py:75 msgid "" "Determines what characters will replace bad words; a\n" " chunk of these characters matching the size of the replaced bad word will\n" " be used to replace the bad words you've configured." msgstr "" #: config.py:83 msgid "" "Determines the manner in which\n" " bad words will be replaced. 'nastyCharacters' (the default) will replace a\n" " bad word with the same number of 'nasty characters' (like those used in\n" " comic books; configurable by supybot.plugins.BadWords.nastyChars).\n" " 'simple' will replace a bad word with a simple strings (regardless of the\n" " length of the bad word); this string is configurable via\n" " supybot.plugins.BadWords.simpleReplacement." msgstr "" #: config.py:91 msgid "" "Determines what word will replace bad\n" " words if the replacement method is 'simple'." msgstr "" #: config.py:94 msgid "" "Determines whether the bot will strip\n" " formatting characters from messages before it checks them for bad words.\n" " If this is False, it will be relatively trivial to circumvent this plugin's\n" " filtering. If it's True, however, it will interact poorly with other\n" " plugins that do coloring or bolding of text." msgstr "" #: config.py:101 msgid "" "Determines whether the bot will kick people with\n" " a warning when they use bad words." msgstr "" #: config.py:104 msgid "" "You have been kicked for using a word\n" " prohibited in the presence of this bot. Please use more appropriate\n" " language in the future." msgstr "" #: config.py:106 msgid "" "Determines the kick message used by the\n" " bot when kicking users for saying bad words." msgstr "" #: plugin.py:46 #, docstring msgid "" "Maintains a list of words that the bot is not allowed to say.\n" " Can also be used to kick people that say these words, if the bot\n" " has op." msgstr "" #: plugin.py:115 #, docstring msgid "" "takes no arguments\n" "\n" " Returns the list of words being censored.\n" " " msgstr "" #: plugin.py:125 msgid "I'm not currently censoring any bad words." msgstr "" #: plugin.py:130 #, docstring msgid "" "<word> [<word> ...]\n" "\n" " Adds all <word>s to the list of words being censored.\n" " " msgstr "" #: plugin.py:142 #, docstring msgid "" "<word> [<word> ...]\n" "\n" " Removes <word>s from the list of words being censored.\n" " " msgstr ""
{ "pile_set_name": "Github" }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include <sys/param.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/icmp6.h> */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sockaddrInet6 C.struct_sockaddr_in6 type inet6Pktinfo C.struct_in6_pktinfo type ipv6Mtuinfo C.struct_ip6_mtuinfo type ipv6Mreq C.struct_ipv6_mreq type icmpv6Filter C.struct_icmp6_filter
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <VCProjectVersion>15.0</VCProjectVersion> <ProjectGuid>{356DCF99-2D8A-4047-8BA2-0E3693CA2558}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>muplugtest</RootNamespace> <WindowsTargetPlatformVersion>7.0</WindowsTargetPlatformVersion> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v141_xp</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="Shared"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader>Use</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>WIN32;_DEBUG;MUPLUGTEST_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PrecompiledHeader>Use</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>_DEBUG;MUPLUGTEST_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <PrecompiledHeader>Use</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>WIN32;NDEBUG;MUPLUGTEST_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> <PostBuildEvent> <Command>copy /Y /V $(TargetPath) ..\\src\\Release</Command> </PostBuildEvent> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <PrecompiledHeader>Use</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> <PreprocessorDefinitions>NDEBUG;MUPLUGTEST_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ConformanceMode>true</ConformanceMode> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemGroup> <ClInclude Include="stdafx.h" /> <ClInclude Include="targetver.h" /> </ItemGroup> <ItemGroup> <ClCompile Include="dllmain.cpp" /> <ClCompile Include="muplug_test.cpp" /> <ClCompile Include="stdafx.cpp"> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader> </ClCompile> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>
{ "pile_set_name": "Github" }
!!!succeeded(test_hash1) !!!succeeded(test_hash2) !!!succeeded(test_hash3)
{ "pile_set_name": "Github" }
var path = require('path'); var test = require('tape'); var resolve = require('../'); test('foo', function (t) { var dir = path.join(__dirname, 'resolver'); t.equal( resolve.sync('./foo', { basedir: dir }), path.join(dir, 'foo.js') ); t.equal( resolve.sync('./foo.js', { basedir: dir }), path.join(dir, 'foo.js') ); t.throws(function () { resolve.sync('foo', { basedir: dir }); }); t.end(); }); test('bar', function (t) { var dir = path.join(__dirname, 'resolver'); t.equal( resolve.sync('foo', { basedir: path.join(dir, 'bar') }), path.join(dir, 'bar/node_modules/foo/index.js') ); t.end(); }); test('baz', function (t) { var dir = path.join(__dirname, 'resolver'); t.equal( resolve.sync('./baz', { basedir: dir }), path.join(dir, 'baz/quux.js') ); t.end(); }); test('biz', function (t) { var dir = path.join(__dirname, 'resolver/biz/node_modules'); t.equal( resolve.sync('./grux', { basedir: dir }), path.join(dir, 'grux/index.js') ); t.equal( resolve.sync('tiv', { basedir: path.join(dir, 'grux') }), path.join(dir, 'tiv/index.js') ); t.equal( resolve.sync('grux', { basedir: path.join(dir, 'tiv') }), path.join(dir, 'grux/index.js') ); t.end(); }); test('normalize', function (t) { var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); t.equal( resolve.sync('../grux', { basedir: dir }), path.join(dir, 'index.js') ); t.end(); }); test('cup', function (t) { var dir = path.join(__dirname, 'resolver'); t.equal( resolve.sync('./cup', { basedir: dir, extensions: ['.js', '.coffee'] }), path.join(dir, 'cup.coffee') ); t.equal( resolve.sync('./cup.coffee', { basedir: dir }), path.join(dir, 'cup.coffee') ); t.throws(function () { resolve.sync('./cup', { basedir: dir, extensions: ['.js'] }); }); t.end(); }); test('mug', function (t) { var dir = path.join(__dirname, 'resolver'); t.equal( resolve.sync('./mug', { basedir: dir }), path.join(dir, 'mug.js') ); t.equal( resolve.sync('./mug', { basedir: dir, extensions: ['.coffee', '.js'] }), path.join(dir, 'mug.coffee') ); t.equal( resolve.sync('./mug', { basedir: dir, extensions: ['.js', '.coffee'] }), path.join(dir, 'mug.js') ); t.end(); }); test('other path', function (t) { var resolverDir = path.join(__dirname, 'resolver'); var dir = path.join(resolverDir, 'bar'); var otherDir = path.join(resolverDir, 'other_path'); t.equal( resolve.sync('root', { basedir: dir, paths: [otherDir] }), path.join(resolverDir, 'other_path/root.js') ); t.equal( resolve.sync('lib/other-lib', { basedir: dir, paths: [otherDir] }), path.join(resolverDir, 'other_path/lib/other-lib.js') ); t.throws(function () { resolve.sync('root', { basedir: dir }); }); t.throws(function () { resolve.sync('zzz', { basedir: dir, paths: [otherDir] }); }); t.end(); }); test('incorrect main', function (t) { var resolverDir = path.join(__dirname, 'resolver'); var dir = path.join(resolverDir, 'incorrect_main'); t.equal( resolve.sync('./incorrect_main', { basedir: resolverDir }), path.join(dir, 'index.js') ); t.end(); }); test('#25: node modules with the same name as node stdlib modules', function (t) { var resolverDir = path.join(__dirname, 'resolver/punycode'); t.equal( resolve.sync('punycode', { basedir: resolverDir }), path.join(resolverDir, 'node_modules/punycode/index.js') ); t.end(); }); var stubStatSync = function stubStatSync(fn) { var fs = require('fs'); var statSync = fs.statSync; try { fs.statSync = function () { throw new EvalError('Unknown Error'); }; return fn(); } finally { fs.statSync = statSync; } }; test('#79 - re-throw non ENOENT errors from stat', function (t) { var dir = path.join(__dirname, 'resolver'); stubStatSync(function () { t.throws(function () { resolve.sync('foo', { basedir: dir }); }, /Unknown Error/); }); t.end(); }); test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { var dir = path.join(__dirname, 'resolver'); t.equal( resolve.sync('./foo', { basedir: path.join(dir, 'same_names') }), path.join(dir, 'same_names/foo.js') ); t.equal( resolve.sync('./foo/', { basedir: path.join(dir, 'same_names') }), path.join(dir, 'same_names/foo/index.js') ); t.end(); }); test('sync: #121 - treating an existing file as a dir when no basedir', function (t) { var testFile = path.basename(__filename); t.test('sanity check', function (st) { st.equal( resolve.sync('./' + testFile), __filename, 'sanity check' ); st.end(); }); t.test('with a fake directory', function (st) { function run() { return resolve.sync('./' + testFile + '/blah'); } st.throws(run, 'throws an error'); try { run(); } catch (e) { st.equal(e.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); st.equal( e.message, 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', 'can not find nonexistent module' ); } st.end(); }); t.end(); }); test('sync dot main', function (t) { var start = new Date(); t.equal(resolve.sync('./resolver/dot_main'), path.join(__dirname, 'resolver/dot_main/index.js')); t.ok(new Date() - start < 50, 'resolve.sync timedout'); t.end(); }); test('sync dot slash main', function (t) { var start = new Date(); t.equal(resolve.sync('./resolver/dot_slash_main'), path.join(__dirname, 'resolver/dot_slash_main/index.js')); t.ok(new Date() - start < 50, 'resolve.sync timedout'); t.end(); });
{ "pile_set_name": "Github" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Shared.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Shared.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
{ "pile_set_name": "Github" }
agent doNOTl4unch_missiaaaaaaaaaaaaaaaa agent doNOTl4unchaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNaaaaaaaaaaaaaaaaaaaaaa agent doaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unchaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unaaaaaaaaaaaaaaaaa agent doNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_miaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_miaaaaaaaaaaa agent doNOTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_missiaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_maaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unchaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_missi1aaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_missi1esaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_missaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_missi1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa agent doNOTl4unch_missi1es! 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 4
{ "pile_set_name": "Github" }
/** */ package net.opengis.gml311.impl; import net.opengis.gml311.DirectionPropertyType; import net.opengis.gml311.Gml311Package; import net.opengis.gml311.LocationPropertyType; import net.opengis.gml311.MeasureType; import net.opengis.gml311.MovingObjectStatusType; import net.opengis.gml311.StringOrRefType; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.BasicFeatureMap; import org.eclipse.emf.ecore.util.FeatureMap; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Moving Object Status Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link net.opengis.gml311.impl.MovingObjectStatusTypeImpl#getLocationGroup <em>Location Group</em>}</li> * <li>{@link net.opengis.gml311.impl.MovingObjectStatusTypeImpl#getLocation <em>Location</em>}</li> * <li>{@link net.opengis.gml311.impl.MovingObjectStatusTypeImpl#getSpeed <em>Speed</em>}</li> * <li>{@link net.opengis.gml311.impl.MovingObjectStatusTypeImpl#getBearing <em>Bearing</em>}</li> * <li>{@link net.opengis.gml311.impl.MovingObjectStatusTypeImpl#getAcceleration <em>Acceleration</em>}</li> * <li>{@link net.opengis.gml311.impl.MovingObjectStatusTypeImpl#getElevation <em>Elevation</em>}</li> * <li>{@link net.opengis.gml311.impl.MovingObjectStatusTypeImpl#getStatus <em>Status</em>}</li> * </ul> * * @generated */ public class MovingObjectStatusTypeImpl extends AbstractTimeSliceTypeImpl implements MovingObjectStatusType { /** * The cached value of the '{@link #getLocationGroup() <em>Location Group</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLocationGroup() * @generated * @ordered */ protected FeatureMap locationGroup; /** * The cached value of the '{@link #getSpeed() <em>Speed</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSpeed() * @generated * @ordered */ protected MeasureType speed; /** * The cached value of the '{@link #getBearing() <em>Bearing</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBearing() * @generated * @ordered */ protected DirectionPropertyType bearing; /** * The cached value of the '{@link #getAcceleration() <em>Acceleration</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAcceleration() * @generated * @ordered */ protected MeasureType acceleration; /** * The cached value of the '{@link #getElevation() <em>Elevation</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getElevation() * @generated * @ordered */ protected MeasureType elevation; /** * The cached value of the '{@link #getStatus() <em>Status</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStatus() * @generated * @ordered */ protected StringOrRefType status; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MovingObjectStatusTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Gml311Package.eINSTANCE.getMovingObjectStatusType(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FeatureMap getLocationGroup() { if (locationGroup == null) { locationGroup = new BasicFeatureMap(this, Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION_GROUP); } return locationGroup; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LocationPropertyType getLocation() { return (LocationPropertyType)getLocationGroup().get(Gml311Package.eINSTANCE.getMovingObjectStatusType_Location(), true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetLocation(LocationPropertyType newLocation, NotificationChain msgs) { return ((FeatureMap.Internal)getLocationGroup()).basicAdd(Gml311Package.eINSTANCE.getMovingObjectStatusType_Location(), newLocation, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLocation(LocationPropertyType newLocation) { ((FeatureMap.Internal)getLocationGroup()).set(Gml311Package.eINSTANCE.getMovingObjectStatusType_Location(), newLocation); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MeasureType getSpeed() { return speed; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetSpeed(MeasureType newSpeed, NotificationChain msgs) { MeasureType oldSpeed = speed; speed = newSpeed; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED, oldSpeed, newSpeed); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSpeed(MeasureType newSpeed) { if (newSpeed != speed) { NotificationChain msgs = null; if (speed != null) msgs = ((InternalEObject)speed).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED, null, msgs); if (newSpeed != null) msgs = ((InternalEObject)newSpeed).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED, null, msgs); msgs = basicSetSpeed(newSpeed, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED, newSpeed, newSpeed)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DirectionPropertyType getBearing() { return bearing; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetBearing(DirectionPropertyType newBearing, NotificationChain msgs) { DirectionPropertyType oldBearing = bearing; bearing = newBearing; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING, oldBearing, newBearing); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBearing(DirectionPropertyType newBearing) { if (newBearing != bearing) { NotificationChain msgs = null; if (bearing != null) msgs = ((InternalEObject)bearing).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING, null, msgs); if (newBearing != null) msgs = ((InternalEObject)newBearing).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING, null, msgs); msgs = basicSetBearing(newBearing, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING, newBearing, newBearing)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MeasureType getAcceleration() { return acceleration; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetAcceleration(MeasureType newAcceleration, NotificationChain msgs) { MeasureType oldAcceleration = acceleration; acceleration = newAcceleration; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION, oldAcceleration, newAcceleration); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setAcceleration(MeasureType newAcceleration) { if (newAcceleration != acceleration) { NotificationChain msgs = null; if (acceleration != null) msgs = ((InternalEObject)acceleration).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION, null, msgs); if (newAcceleration != null) msgs = ((InternalEObject)newAcceleration).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION, null, msgs); msgs = basicSetAcceleration(newAcceleration, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION, newAcceleration, newAcceleration)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MeasureType getElevation() { return elevation; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetElevation(MeasureType newElevation, NotificationChain msgs) { MeasureType oldElevation = elevation; elevation = newElevation; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION, oldElevation, newElevation); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setElevation(MeasureType newElevation) { if (newElevation != elevation) { NotificationChain msgs = null; if (elevation != null) msgs = ((InternalEObject)elevation).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION, null, msgs); if (newElevation != null) msgs = ((InternalEObject)newElevation).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION, null, msgs); msgs = basicSetElevation(newElevation, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION, newElevation, newElevation)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StringOrRefType getStatus() { return status; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetStatus(StringOrRefType newStatus, NotificationChain msgs) { StringOrRefType oldStatus = status; status = newStatus; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS, oldStatus, newStatus); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStatus(StringOrRefType newStatus) { if (newStatus != status) { NotificationChain msgs = null; if (status != null) msgs = ((InternalEObject)status).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS, null, msgs); if (newStatus != null) msgs = ((InternalEObject)newStatus).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS, null, msgs); msgs = basicSetStatus(newStatus, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS, newStatus, newStatus)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION_GROUP: return ((InternalEList<?>)getLocationGroup()).basicRemove(otherEnd, msgs); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION: return basicSetLocation(null, msgs); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED: return basicSetSpeed(null, msgs); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING: return basicSetBearing(null, msgs); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION: return basicSetAcceleration(null, msgs); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION: return basicSetElevation(null, msgs); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS: return basicSetStatus(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION_GROUP: if (coreType) return getLocationGroup(); return ((FeatureMap.Internal)getLocationGroup()).getWrapper(); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION: return getLocation(); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED: return getSpeed(); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING: return getBearing(); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION: return getAcceleration(); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION: return getElevation(); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS: return getStatus(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION_GROUP: ((FeatureMap.Internal)getLocationGroup()).set(newValue); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION: setLocation((LocationPropertyType)newValue); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED: setSpeed((MeasureType)newValue); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING: setBearing((DirectionPropertyType)newValue); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION: setAcceleration((MeasureType)newValue); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION: setElevation((MeasureType)newValue); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS: setStatus((StringOrRefType)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION_GROUP: getLocationGroup().clear(); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION: setLocation((LocationPropertyType)null); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED: setSpeed((MeasureType)null); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING: setBearing((DirectionPropertyType)null); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION: setAcceleration((MeasureType)null); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION: setElevation((MeasureType)null); return; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS: setStatus((StringOrRefType)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION_GROUP: return locationGroup != null && !locationGroup.isEmpty(); case Gml311Package.MOVING_OBJECT_STATUS_TYPE__LOCATION: return getLocation() != null; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__SPEED: return speed != null; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__BEARING: return bearing != null; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ACCELERATION: return acceleration != null; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__ELEVATION: return elevation != null; case Gml311Package.MOVING_OBJECT_STATUS_TYPE__STATUS: return status != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (locationGroup: "); result.append(locationGroup); result.append(')'); return result.toString(); } } //MovingObjectStatusTypeImpl
{ "pile_set_name": "Github" }
{ "name": "@icedesign/account-features-block", "version": "3.0.1", "description": "罗列账户功能列表", "homepage": "https://unpkg.com/@icedesign/account-features-block/build/index.html", "author": "noyobo <nongyoubao@alibaba-inc.com>", "files": [ "src/", "build/", "screenshot.png" ], "repository": { "type": "git", "url": "https://github.com/ice-lab/react-materials/tree/master/blocks/AccountFeatures" }, "license": "MIT", "keywords": [ "ice", "react", "block" ], "publishConfig": { "access": "public" }, "dependencies": { "@icedesign/container": "^1.x", "prop-types": "^15.5.8", "react": "^16.2.0", "@alifd/next": "^1.x" }, "blockConfig": { "name": "account-features", "title": "账户特性", "categories": [ "列表" ], "screenshot": "https://unpkg.com/@icedesign/account-features-block/screenshot.png", "version-0.x": "1.0.0" }, "scripts": { "start": "../../node_modules/.bin/ice-scripts dev --config ../../ice.block.config.js", "build": "../../node_modules/.bin/ice-scripts build --config ../../ice.block.config.js", "screenshot": "../../node_modules/.bin/screenshot -l -s '#mountNode'", "prepublishOnly": "npm run build && npm run screenshot" }, "devDependencies": { "react-dom": "^16.2.0" } }
{ "pile_set_name": "Github" }
package main import ( "context" "time" ) import ( hessian "github.com/apache/dubbo-go-hessian2" "github.com/apache/dubbo-go/config" ) var userProvider = new(UserProvider) func init() { config.SetConsumerService(userProvider) hessian.RegisterPOJO(&User{}) } type User struct { Id string Name string Age int32 Time time.Time } type UserProvider struct { GetUser func(ctx context.Context, req []interface{}, rsp *User) error } func (u *UserProvider) Reference() string { return "UserProvider" } func (User) JavaClassName() string { return "com.ikurento.user.User" }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- """ oauthlib.oauth2.rfc6749 ~~~~~~~~~~~~~~~~~~~~~~~ This module is an implementation of various logic needed for consuming and providing OAuth 2.0 RFC6749. """ from __future__ import absolute_import, unicode_literals import logging from oauthlib.common import Request from oauthlib.oauth2.rfc6749 import utils from .base import BaseEndpoint, catch_errors_and_unavailability log = logging.getLogger(__name__) class TokenEndpoint(BaseEndpoint): """Token issuing endpoint. The token endpoint is used by the client to obtain an access token by presenting its authorization grant or refresh token. The token endpoint is used with every authorization grant except for the implicit grant type (since an access token is issued directly). The means through which the client obtains the location of the token endpoint are beyond the scope of this specification, but the location is typically provided in the service documentation. The endpoint URI MAY include an "application/x-www-form-urlencoded" formatted (per `Appendix B`_) query component, which MUST be retained when adding additional query parameters. The endpoint URI MUST NOT include a fragment component:: https://example.com/path?query=component # OK https://example.com/path?query=component#fragment # Not OK Since requests to the authorization endpoint result in user Since requests to the token endpoint result in the transmission of clear-text credentials (in the HTTP request and response), the authorization server MUST require the use of TLS as described in Section 1.6 when sending requests to the token endpoint:: # We will deny any request which URI schema is not with https The client MUST use the HTTP "POST" method when making access token requests:: # HTTP method is currently not enforced Parameters sent without a value MUST be treated as if they were omitted from the request. The authorization server MUST ignore unrecognized request parameters. Request and response parameters MUST NOT be included more than once:: # Delegated to each grant type. .. _`Appendix B`: https://tools.ietf.org/html/rfc6749#appendix-B """ def __init__(self, default_grant_type, default_token_type, grant_types): BaseEndpoint.__init__(self) self._grant_types = grant_types self._default_token_type = default_token_type self._default_grant_type = default_grant_type @property def grant_types(self): return self._grant_types @property def default_grant_type(self): return self._default_grant_type @property def default_grant_type_handler(self): return self.grant_types.get(self.default_grant_type) @property def default_token_type(self): return self._default_token_type @catch_errors_and_unavailability def create_token_response(self, uri, http_method='GET', body=None, headers=None, credentials=None, grant_type_for_scope=None, claims=None): """Extract grant_type and route to the designated handler.""" request = Request( uri, http_method=http_method, body=body, headers=headers) # 'scope' is an allowed Token Request param in both the "Resource Owner Password Credentials Grant" # and "Client Credentials Grant" flows # https://tools.ietf.org/html/rfc6749#section-4.3.2 # https://tools.ietf.org/html/rfc6749#section-4.4.2 request.scopes = utils.scope_to_list(request.scope) request.extra_credentials = credentials if grant_type_for_scope: request.grant_type = grant_type_for_scope # OpenID Connect claims, if provided. The server using oauthlib might choose # to implement the claims parameter of the Authorization Request. In this case # it should retrieve those claims and pass them via the claims argument here, # as a dict. if claims: request.claims = claims grant_type_handler = self.grant_types.get(request.grant_type, self.default_grant_type_handler) log.debug('Dispatching grant_type %s request to %r.', request.grant_type, grant_type_handler) return grant_type_handler.create_token_response( request, self.default_token_type)
{ "pile_set_name": "Github" }
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Mark Evans, <evansmp@uhura.aston.ac.uk> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche, <flla@stud.uni-sb.de> * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> * Linus Torvalds, <torvalds@cs.helsinki.fi> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Matthew Dillon, <dillon@apollo.west.oic.com> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Jorge Cwik, <jorge@laser.satlink.net> */ #include <linux/module.h> #include <linux/gfp.h> #include <net/tcp.h> int sysctl_tcp_syn_retries __read_mostly = TCP_SYN_RETRIES; int sysctl_tcp_synack_retries __read_mostly = TCP_SYNACK_RETRIES; int sysctl_tcp_keepalive_time __read_mostly = TCP_KEEPALIVE_TIME; int sysctl_tcp_keepalive_probes __read_mostly = TCP_KEEPALIVE_PROBES; int sysctl_tcp_keepalive_intvl __read_mostly = TCP_KEEPALIVE_INTVL; int sysctl_tcp_retries1 __read_mostly = TCP_RETR1; int sysctl_tcp_retries2 __read_mostly = TCP_RETR2; int sysctl_tcp_orphan_retries __read_mostly; int sysctl_tcp_thin_linear_timeouts __read_mostly; static void tcp_write_timer(unsigned long); static void tcp_delack_timer(unsigned long); static void tcp_keepalive_timer (unsigned long data); void tcp_init_xmit_timers(struct sock *sk) { inet_csk_init_xmit_timers(sk, &tcp_write_timer, &tcp_delack_timer, &tcp_keepalive_timer); } EXPORT_SYMBOL(tcp_init_xmit_timers); //关闭套接字并释放资源 static void tcp_write_err(struct sock *sk) { sk->sk_err = sk->sk_err_soft ? : ETIMEDOUT; sk->sk_error_report(sk); tcp_done(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONTIMEOUT); } /* Do not allow orphaned sockets to eat all our resources. * This is direct violation of TCP specs, but it is required * to prevent DoS attacks. It is called when a retransmission timeout * or zero probe timeout occurs on orphaned socket. * * Criteria is still not confirmed experimentally and may change. * We kill the socket, if: * 1. If number of orphaned sockets exceeds an administratively configured * limit. * 2. If we have strong memory pressure. */ static int tcp_out_of_resources(struct sock *sk, int do_reset) { struct tcp_sock *tp = tcp_sk(sk); int shift = 0; /* If peer does not open window for long time, or did not transmit * anything for long time, penalize it. */ if ((s32)(tcp_time_stamp - tp->lsndtime) > 2*TCP_RTO_MAX || !do_reset) shift++; /* If some dubious ICMP arrived, penalize even more. */ if (sk->sk_err_soft) shift++; if (tcp_too_many_orphans(sk, shift)) { if (net_ratelimit()) printk(KERN_INFO "Out of socket memory\n"); /* Catch exceptional cases, when connection requires reset. * 1. Last segment was sent recently. */ if ((s32)(tcp_time_stamp - tp->lsndtime) <= TCP_TIMEWAIT_LEN || /* 2. Window is closed. */ (!tp->snd_wnd && !tp->packets_out)) do_reset = 1; if (do_reset) tcp_send_active_reset(sk, GFP_ATOMIC); tcp_done(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONMEMORY); return 1; } return 0; } /* Calculate maximal number or retries on an orphaned socket. */ static int tcp_orphan_retries(struct sock *sk, int alive) { int retries = sysctl_tcp_orphan_retries; /* May be zero. */ /* We know from an ICMP that something is wrong. */ if (sk->sk_err_soft && !alive) retries = 0; /* However, if socket sent something recently, select some safe * number of retries. 8 corresponds to >100 seconds with minimal * RTO of 200msec. */ if (retries == 0 && alive) retries = 8; return retries; } static void tcp_mtu_probing(struct inet_connection_sock *icsk, struct sock *sk) { /* Black hole detection */ if (sysctl_tcp_mtu_probing) { if (!icsk->icsk_mtup.enabled) { icsk->icsk_mtup.enabled = 1; tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); } else { struct tcp_sock *tp = tcp_sk(sk); int mss; mss = tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low) >> 1; mss = min(sysctl_tcp_base_mss, mss); mss = max(mss, 68 - tp->tcp_header_len); icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, mss); tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); } } } /* This function calculates a "timeout" which is equivalent to the timeout of a * TCP connection after "boundary" unsuccessful, exponentially backed-off * retransmissions with an initial RTO of TCP_RTO_MIN or TCP_TIMEOUT_INIT if * syn_set flag is set. */ static bool retransmits_timed_out(struct sock *sk, unsigned int boundary, bool syn_set) { unsigned int timeout, linear_backoff_thresh; unsigned int start_ts; unsigned int rto_base = syn_set ? TCP_TIMEOUT_INIT : TCP_RTO_MIN; if (!inet_csk(sk)->icsk_retransmits) return false; if (unlikely(!tcp_sk(sk)->retrans_stamp)) start_ts = TCP_SKB_CB(tcp_write_queue_head(sk))->when; else start_ts = tcp_sk(sk)->retrans_stamp; linear_backoff_thresh = ilog2(TCP_RTO_MAX/rto_base); if (boundary <= linear_backoff_thresh) timeout = ((2 << boundary) - 1) * rto_base; else timeout = ((2 << linear_backoff_thresh) - 1) * rto_base + (boundary - linear_backoff_thresh) * TCP_RTO_MAX; return (tcp_time_stamp - start_ts) >= timeout; } /* A write timeout has occurred. Process the after effects. */ /* * 当发生重传之后,需要检测当前的资源使用 * 情况.如果重传达到上限则需要立即关闭套接字 */ static int tcp_write_timeout(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); int retry_until; bool do_reset, syn_set = 0; /* * 在建立连接阶段超时,则需要检测使用的 * 路由缓存项,并获取重试次数的最大值. */ if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) { if (icsk->icsk_retransmits) dst_negative_advice(sk); retry_until = icsk->icsk_syn_retries ? : sysctl_tcp_syn_retries; syn_set = 1; } else { /* * 当重传次数达到sysctl_tcp_retries1时,则需要进行 * 黑洞检测.完成黑洞检测后还需检测使用的 * 路由缓存项. * 系统启用路径MTU发现时,如果路径MTU发现的 * 控制数据块中的开关没有开启,则将其开启, * 并根据PMTU同步MSS.否则,将当前路径MTU发现 * 区间左端点的一半作为新区间的左端点重新 * 设定路径MTU发现区间,并根据路径MTU同步MSS. */ if (retransmits_timed_out(sk, sysctl_tcp_retries1, 0)) { /* Black hole detection */ tcp_mtu_probing(icsk, sk); dst_negative_advice(sk); } /* * 如果当前套接字连接已断开并即将关闭,则 * 需要对当前使用的资源进行检测.当前的孤 * 儿套接字数量达到sysctl_tcp_max_orphans或者当前 * 已使用内存达到硬性限制时,需要即刻关闭 * 该套接字,这虽然不符合TCP的规范,但为了防 * 止DoS攻击必须这么处理. */ retry_until = sysctl_tcp_retries2; if (sock_flag(sk, SOCK_DEAD)) { const int alive = (icsk->icsk_rto < TCP_RTO_MAX); retry_until = tcp_orphan_retries(sk, alive); do_reset = alive || !retransmits_timed_out(sk, retry_until, 0); if (tcp_out_of_resources(sk, do_reset)) return 1; } } /* * 当重传次数达到建立连接重传上限、超时 * 重传上限或确认连接异常期间重试上限这 * 三种上限之一时,都必须关闭套接字,并 * 且需要报告相应的错误。 */ if (retransmits_timed_out(sk, retry_until, syn_set)) { /* Has it gone just too far? */ tcp_write_err(sk); return 1; } return 0; } /* * 延时ACK"定时器在TCP收到必须被确认但无需马上发出 * 确认的段时设定,TCP在200ms后发送确认响应。如果在 * 这200ms内,有数据要在该连接上发送,延时ACK响应就 * 可随数据一起发送回对端,称为捎带确认。 */ static void tcp_delack_timer(unsigned long data) { struct sock *sk = (struct sock *)data; struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); bh_lock_sock(sk); /* * 如果传输控制块已被用户进程锁定, * 则此时不能作处理,只是重新设置 * 定时器超时时间,同时设置blocked * 标记。 */ if (sock_owned_by_user(sk)) { /* Try again later. */ icsk->icsk_ack.blocked = 1; NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOCKED); sk_reset_timer(sk, &icsk->icsk_delack_timer, jiffies + TCP_DELACK_MIN); goto out_unlock; } /* * 回收缓存 */ sk_mem_reclaim_partial(sk); /* * 如果TCP状态为CLOSE,或者没有启动延时发送 * ACK定时器,则无需作进一步处理。 */ if (sk->sk_state == TCP_CLOSE || !(icsk->icsk_ack.pending & ICSK_ACK_TIMER)) goto out; /* * 如果超时时间还未到,则重新复位定时器, * 然后退出。 */ if (time_after(icsk->icsk_ack.timeout, jiffies)) { sk_reset_timer(sk, &icsk->icsk_delack_timer, icsk->icsk_ack.timeout); goto out; } /* * 检测完成后,正式进入延迟确认处理之前, * 需去掉ICSK_ACK_TIMER标志。 */ icsk->icsk_ack.pending &= ~ICSK_ACK_TIMER; /* * 如果ucopy控制块中的prequeue队列不为空,则 * 通过sk_backlog_rcv接口处理sk_backlog_rcv队列中的 * SKB。TCP中sk_backlog_rcv接口为tcp_v4_do_rcv(),由这个函数添加到sk->sk_receive_queue队列中。 */ if (!skb_queue_empty(&tp->ucopy.prequeue)) { struct sk_buff *skb; NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSCHEDULERFAILED); while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL) sk_backlog_rcv(sk, skb); tp->ucopy.memory = 0; } /* * 如果此时有ACK需要发送,则调用tcp_send_ack()构造 * 并发送ACK段,在发送ACK段之前需先离开pingpong * 模式,并重新设定延时确认的估算值。 */ if (inet_csk_ack_scheduled(sk)) { if (!icsk->icsk_ack.pingpong) { /* Delayed ACK missed: inflate ATO. */ icsk->icsk_ack.ato = min(icsk->icsk_ack.ato << 1, icsk->icsk_rto); } else { /* Delayed ACK missed: leave pingpong mode and * deflate ATO. */ icsk->icsk_ack.pingpong = 0; icsk->icsk_ack.ato = TCP_ATO_MIN; } tcp_send_ack(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKS); } TCP_CHECK_TIMER(sk); out: if (tcp_memory_pressure) sk_mem_reclaim(sk); out_unlock: bh_unlock_sock(sk); sock_put(sk); } /* * "持续"定时器在对端通告接收窗口为0,阻止TCP继续发送 * 数据时设定。由于连接对端发送的窗口通告不可靠(只有 * 数据才会确认,ACK不会确认),允许TCP继续发送数据的后 * 续窗口更新有可能丢失,因此,如果TCP有数据发送,而 * 对端通告接收窗口为0,则持续定时器启动,超时后向 * 对端发送1字节的数据,以判断对端接收窗口是否已打开。 * 与重传定时器类似,持续定时器的超时值也是动态计算的, * 取决于连接的往返时间,在5~60s之间取值。 * tcp_probe_timer()为持续定时器超时的处理函数。探测定时器就是当接收到对端的window为0的时候,需要探测对端窗口是否变大, */ //真正的probe报文发送在tcp_send_probe0中的tcp_write_wakeup 探测定时器在tcp_ack函数中激活, 或者在__tcp_push_pending_frames中的tcp_check_probe_timer激活 static void tcp_probe_timer(struct sock *sk) ////tcp_write_timer包括数据报重传tcp_retransmit_timer和窗口探测定时器tcp_probe_timer { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int max_probes; if (tp->packets_out || !tcp_send_head(sk)) { icsk->icsk_probes_out = 0; return; } /* *WARNING* RFC 1122 forbids this * * It doesn't AFAIK, because we kill the retransmit timer -AK * * FIXME: We ought not to do it, Solaris 2.5 actually has fixing * this behaviour in Solaris down as a bug fix. [AC] * * Let me to explain. icsk_probes_out is zeroed by incoming ACKs * even if they advertise zero window. Hence, connection is killed only * if we received no ACKs for normal connection timeout. It is not killed * only because window stays zero for some time, window may be zero * until armageddon and even later. We are in full accordance * with RFCs, only probe timer combines both retransmission timeout * and probe timeout in one bottle. --ANK */ max_probes = sysctl_tcp_retries2; /* * 处理连接已断开,套接字即将关闭的情况 */ if (sock_flag(sk, SOCK_DEAD)) { /* * TCP协议规定RTT的最大值为120s(TCP_RTO_MAX),因此 * 可以通过将指数退避算法得出的超时时间与 * RTT最大值相比,来判断是否需要给对方发送 * RST。 */ const int alive = ((icsk->icsk_rto << icsk->icsk_backoff) < TCP_RTO_MAX); /* * 如果连接已断开,套接字即将关闭,则获取在 * 关闭本端TCP连接前重试次数的上限。 */ max_probes = tcp_orphan_retries(sk, alive); /* * 释放资源,如果该套接字在释放过程中被关闭, * 就无需再发送持续探测段了。 */ if (tcp_out_of_resources(sk, alive || icsk->icsk_probes_out <= max_probes)) return; } if (icsk->icsk_probes_out > max_probes) { tcp_write_err(sk); /* * 如果持续定时器或保活定时器周期性发送出但未被确认 * 的TCP段数目达到上限,则作出错处理,同时关闭TCP套接字。 */ } else { /* Only send another probe if we didn't close things up. */ /* * 否则,再一次发送持续定时器。 */ tcp_send_probe0(sk); } } /* * The TCP retransmit timer. */ ////tcp_write_timer包括数据报重传tcp_retransmit_timer和窗口探测定时器tcp_probe_timer //见tcp_event_new_data_sent,prior_packets为0时才会重启定时器,而prior_packets则是发送未确认的段的个数,也就是说如果发送了很多段,如果前面的段没有确认,那么后面发送的时候不会重启这个定时器. //tcp_rearm_rto ///为0说明所有的传输的段都已经acked。此时remove定时器。否则重启定时器。 void tcp_retransmit_timer(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); /* * 如果此时从发送队列输出的段都已 * 得到了确认,则无需重传处理. */ if (!tp->packets_out) goto out; WARN_ON(tcp_write_queue_empty(sk)); /* * 在重传过程中,如果超时重传超时上限TCP_RTO_MAX(120s)还没有接收 * 到对方的确认,则认为有错误发生,调用tcp_write_err()报告错误并 * 关闭套接字,然后返回;否则TCP进入拥塞控制的LOSS状态,并重新 * 传送重传队列中的第一个段。 */ if (!tp->snd_wnd && !sock_flag(sk, SOCK_DEAD) && !((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))) { /* Receiver dastardly shrinks window. Our retransmits * become zero probes, but we should not timeout this * connection. If the socket is an orphan, time it out, * we cannot allow such beasts to hang infinitely. */ #ifdef TCP_DEBUG struct inet_sock *inet = inet_sk(sk); if (sk->sk_family == AF_INET) { LIMIT_NETDEBUG(KERN_DEBUG "TCP: Peer %pI4:%u/%u unexpectedly shrunk window %u:%u (repaired)\n", &inet->inet_daddr, ntohs(inet->inet_dport), inet->inet_num, tp->snd_una, tp->snd_nxt); } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) else if (sk->sk_family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); LIMIT_NETDEBUG(KERN_DEBUG "TCP: Peer %pI6:%u/%u unexpectedly shrunk window %u:%u (repaired)\n", &np->daddr, ntohs(inet->inet_dport), inet->inet_num, tp->snd_una, tp->snd_nxt); } #endif #endif /* * 在重传过程中,如果超时重传超时上限TCP_RTO_MAX(120s)还没有接收 * 到对方的确认,则认为有错误发生,调用tcp_write_err()报告错误并 * 关闭套接字,然后返回;否则TCP进入拥塞控制的LOSS状态,并重新 * 传送重传队列中的第一个段。 */ if (tcp_time_stamp - tp->rcv_tstamp > TCP_RTO_MAX) { tcp_write_err(sk); goto out; } tcp_enter_loss(sk, 0); tcp_retransmit_skb(sk, tcp_write_queue_head(sk)); /* * 由于发生了重传,传输控制块中的路由缓存项需更新, * 因此将其清除,最后跳转到out_reset_timer标签处处理。 */ __sk_dst_reset(sk); goto out_reset_timer; } //走到下面说明是处于连接建立阶段或者对方的滑动窗口为0了 /* * 当发生重传之后,需要检测当前的资源使用 * 情况和重传的次数.如果重传次数达到上限, * 则需要报告错误并强行关闭套接字.如果只 * 是使用的资源达到使用的上限,则不进行此 * 次重传. */ if (tcp_write_timeout(sk)) goto out; /* * 如果重传次数为0,说明刚进入重传阶段,则 * 根据不同的拥塞状态进行相关的数据统计. 第一次重传可能是对方滑动窗口满,需要进行拥塞控制 */ if (icsk->icsk_retransmits == 0) { int mib_idx; if (icsk->icsk_ca_state == TCP_CA_Disorder) { if (tcp_is_sack(tp)) mib_idx = LINUX_MIB_TCPSACKFAILURES; else mib_idx = LINUX_MIB_TCPRENOFAILURES; } else if (icsk->icsk_ca_state == TCP_CA_Recovery) { if (tcp_is_sack(tp)) mib_idx = LINUX_MIB_TCPSACKRECOVERYFAIL; else mib_idx = LINUX_MIB_TCPRENORECOVERYFAIL; } else if (icsk->icsk_ca_state == TCP_CA_Loss) { mib_idx = LINUX_MIB_TCPLOSSFAILURES; } else { mib_idx = LINUX_MIB_TCPTIMEOUTS; } NET_INC_STATS_BH(sock_net(sk), mib_idx); } /* * 判断是否可使用F-RTO算法进行处理, * 如果可以则调用tcp_enter_frto()进行F-RTO * 算法的处理,否则调用tcp_enter_loss()进入 * 常规的RTO慢启动重传恢复阶段. */ if (tcp_use_frto(sk)) { tcp_enter_frto(sk); } else { tcp_enter_loss(sk, 0); } /* * 如果发送重传队列上的第一个SKB失败,则复位 * 重传定时器,等待下次重传. */ if (tcp_retransmit_skb(sk, tcp_write_queue_head(sk)) > 0) { /* Retransmission failed because of local congestion, * do not backoff. */ if (!icsk->icsk_retransmits) icsk->icsk_retransmits = 1; inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, min(icsk->icsk_rto, TCP_RESOURCE_PROBE_INTERVAL), TCP_RTO_MAX); goto out; } /* Increase the timeout each time we retransmit. Note that * we do not increase the rtt estimate. rto is initialized * from rtt, but increases here. Jacobson (SIGCOMM 88) suggests * that doubling rto each time is the least we can get away with. * In KA9Q, Karn uses this for the first few times, and then * goes to quadratic. netBSD doubles, but only goes up to *64, * and clamps at 1 to 64 sec afterwards. Note that 120 sec is * defined in the protocol as the maximum possible RTT. I guess * we'll have to use something other than TCP to talk to the * University of Mars. * * PAWS allows us longer timeouts and large windows, so once * implemented ftp to mars will work nicely. We will have to fix * the 120 second clamps though! */ /* * 发送成功后,递增指数退避算法指数icsk_backoff * 和累计重传次数icsk_retransmits. */ icsk->icsk_backoff++; icsk->icsk_retransmits++; out_reset_timer: /* If stream is thin, use linear timeouts. Since 'icsk_backoff' is * used to reset timer, set to 0. Recalculate 'icsk_rto' as this * might be increased if the stream oscillates between thin and thick, * thus the old value might already be too high compared to the value * set by 'tcp_set_rto' in tcp_input.c which resets the rto without * backoff. Limit to TCP_THIN_LINEAR_RETRIES before initiating * exponential backoff behaviour to avoid continue hammering * linear-timeout retransmissions into a black hole */ if (sk->sk_state == TCP_ESTABLISHED && (tp->thin_lto || sysctl_tcp_thin_linear_timeouts) && tcp_stream_is_thin(tp) && icsk->icsk_retransmits <= TCP_THIN_LINEAR_RETRIES) { icsk->icsk_backoff = 0; icsk->icsk_rto = min(__tcp_set_rto(tp), TCP_RTO_MAX);//计算rto,并重启定时器,这里使用karn算法,也就是下次超时时间增加一倍/ } else { /* Use normal (exponential) backoff */ icsk->icsk_rto = min(icsk->icsk_rto << 1, TCP_RTO_MAX); } /* * 完成重传后,需要设重传超时时间,然后复位重传 * 定时器,等待下次重传. */ inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, icsk->icsk_rto, TCP_RTO_MAX); if (retransmits_timed_out(sk, sysctl_tcp_retries1 + 1, 0)) __sk_dst_reset(sk); out:; } /* * 重传定时器在TCP发送数据时设定,如果定时器 * 已超时而对端确认还未到达,则TCP将重传数据。 * 重传定时器的超时时间值是动态计算的,取决于 * TCP为该连接测量的往返时间以及该段已被重传 * 的次数。 */ //tcp_write_timer包括数据报重传tcp_retransmit_timer和窗口探测定时器tcp_probe_timer static void tcp_write_timer(unsigned long data) { struct sock *sk = (struct sock *)data; struct inet_connection_sock *icsk = inet_csk(sk); int event; bh_lock_sock(sk); /* * 若传输控制块被用户进程锁定,则只能稍后再试, * 因此重新设置定时器超时时间。 */ if (sock_owned_by_user(sk)) { /* Try again later */ sk_reset_timer(sk, &icsk->icsk_retransmit_timer, jiffies + (HZ / 20)); goto out_unlock; } /* * TCP状态为CLOSE或未定义定时器事件,则 * 无需作处理。 */ if (sk->sk_state == TCP_CLOSE || !icsk->icsk_pending) goto out; /* * 如果还未到定时器超时时间,则无需 * 作处理,重新设置定时器的下次的超 * 时时间。 */ if (time_after(icsk->icsk_timeout, jiffies)) { sk_reset_timer(sk, &icsk->icsk_retransmit_timer, icsk->icsk_timeout); goto out; } /* * 由于重传定时器和持续定时器功能是共用了 * 一个定时器实现的,因此需根据定时器事件 * 来区分激活的是哪种定时器;如果event为 * ICSK_TIME_RETRANS,则调用tcp_retransmit_timer()进行重传 * 处理;如果为ICSK_TIME_PROBE0,则调用tcp_probe_timer() * 进行持续定时器的处理. */ event = icsk->icsk_pending; icsk->icsk_pending = 0; switch (event) { case ICSK_TIME_RETRANS: tcp_retransmit_timer(sk); break; case ICSK_TIME_PROBE0: tcp_probe_timer(sk); break; } TCP_CHECK_TIMER(sk); out: sk_mem_reclaim(sk); out_unlock: bh_unlock_sock(sk); sock_put(sk); } /* * Timer for listening sockets */ /* * tcp_synack_timer()只是简单地调用inet_csk_reqsk_queue_prune(), * 用来扫描半连接散列表。然后再设定建立连接 * 定时器,间隔时间为TCP_SYNQ_INTERVAL。 */ static void tcp_synack_timer(struct sock *sk) { inet_csk_reqsk_queue_prune(sk, TCP_SYNQ_INTERVAL, TCP_TIMEOUT_INIT, TCP_RTO_MAX); } void tcp_syn_ack_timeout(struct sock *sk, struct request_sock *req) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPTIMEOUTS); } EXPORT_SYMBOL(tcp_syn_ack_timeout); void tcp_set_keepalive(struct sock *sk, int val) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) return; if (val && !sock_flag(sk, SOCK_KEEPOPEN)) inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tcp_sk(sk))); else if (!val) inet_csk_delete_keepalive_timer(sk); } /* * tcp_keepalive_timer()实现了TCP中的三个定时器:连接建立定时器、 * 保活定时器和FIN_WAIT_2定时器。这是由于这三个定时器分别 * 处于LISTEN、ESTABLISHED和FIN_WAIT_2三种状态,因此不必区分它们, * 只需简单地通过当前的TCP状态就能判断当前执行的是何种 * 定时器。 * * "保活"定时器在应用进程选取了套接字SO_KEEPALIVE选项时生效。 * 如果连接的连续空闲时间超过2小时,则保活定时器超时,向 * 对端发送连接探测段,强迫对端响应。 * 1)如果能接收到预期的响应,则TCP可确定对端主机工作正常, * 在该连接再次空闲超过2小时之前,TCP不会再进行保活探测。 * 2)如果收到的是其他响应,则TCP可能确定对端主机已重启。 * 3)如果是连续若干次保活测试都未收到响应,则TCP假定对端 * 主机已崩溃,尽管它无法区分是主机故障(例如系统崩溃而 * 尚未重启)还是连接故障(例如中间的路由器发送故障或电话线 * 断了)。 * * * FIN_WAIT_1定时器: * 当某个连接从FIN_WAIT_1状态变迁到FIN_WAIT_2状态,且不能再接收 * 任何新数据时,则意味着应用进程调用了close()而非shutdown(), * 没有利用TCP的半关闭功能,FIN_WAIT_2定时器启动,超时时间为 * 10min,在定时器第一次超时后,重新设置超时时间为75s,第二次 * 超时后关闭连接。加入这个定时器的目的是为了避免对端一直 * 不发FIN,某个连接会永远滞留在FIN_WAIT_2状态。 * FIN_WAIT_2定时器并不是全部由tcp_keepalive_timer()来实现,事实上,只有 * 在处于FIN_WAIT_2状态的时间超过60s时,才会将该传输控制块放到 * tcp_keepalive_timer()中处理,在sk_timer定时器中延时60s以后的部分,由 * tcp_time_wait()继续处理。见tcp_rcv_state_process */ //通过TCP的不同状态,来实现连接定时器、FIN_WAIT_2定时器以及TCP保活定时器 ////??疑问:重传定时器和探测定时器为什么后面的定时器不会把前面sk_reset_timer的定时器给覆盖了呢,那前面的定时器不是不起作用吗? //因为在启用重传定时器的过程中,表示对端窗口是不为0的,在启动探测定时器的时候也会检查是否有未被确认的ack等。他们处于不同的阶段,所以他们是不可能同时存在的 //这里的tcp_keepalive_timer定时器也是一样的 static void tcp_keepalive_timer (unsigned long data) { struct sock *sk = (struct sock *) data; struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); u32 elapsed; /* Only process if socket is not in use. */ bh_lock_sock(sk); /* * 如果传输控制块被用户进程锁定,则重新设定 * 定时时间,0.05s后再次激活。 */ if (sock_owned_by_user(sk)) { /* Try again later. */ inet_csk_reset_keepalive_timer (sk, HZ/20); goto out; } /* * 如果当前TCP状态为LISTEN,则说明执行的是连接 * 建立定时器,调用tcp_synack_timer()处理。 */ if (sk->sk_state == TCP_LISTEN) { //说明是在建立TCP连接的过程中的定时器处理过程 tcp_synack_timer(sk); goto out; } /* * 处理FIN_WAIT_2状态定时器时,TCP状态必须为 * FIN_WAIT_2且套接字状态为DEAD。 */ //tcp_rcv_state_process中收到第一个FIN ack后会进入TCP_FIN_WAIT2状态 if (sk->sk_state == TCP_FIN_WAIT2 && sock_flag(sk, SOCK_DEAD)) { //TCP关闭过程中的定时器处理过程,从tcp_rcv_state_process跳转过来 /* * 停留在FIN_WAIT_2状态的时间大于或等于0的情况下, * 如果FIN_WAIT_2定时器剩余时间大于0,则调用 * tcp_time_wait()继续处理;否则给对端发送RST后 * 关闭套接字。 */ if (tp->linger2 >= 0) { const int tmo = tcp_fin_time(sk) - TCP_TIMEWAIT_LEN; if (tmo > 0) { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); //在tcp_rcv_state_process中的WAIT1状态,用掉了tcp_fin_time-TCP_TIMEWAIT_LEN,所以多余的的时间这里处理 goto out; } } tcp_send_active_reset(sk, GFP_ATOMIC); goto death; } //下面是TCP连接建立过程中的保活处理过程 /* * 如果未启用保活功能或TCP状态为CLOSE,则不作 * 处理返回。 */ if (!sock_flag(sk, SOCK_KEEPOPEN) || sk->sk_state == TCP_CLOSE) goto out; /* * 如果有已输出未确认的段,或者发送队列中还 * 存在未发送的段,则无需作处理,只需重新设 * 定保活定时器的超时时间。 */ elapsed = keepalive_time_when(tp); /* It is alive without keepalive 8) */ if (tp->packets_out || tcp_send_head(sk)) goto resched; elapsed = keepalive_time_elapsed(tp); if (elapsed >= keepalive_time_when(tp)) { /* * 如果持续空闲时间超过了允许时间,并且在未设置 * 保活探测次数时,已发送保活探测段数超过了系统 * 默认的允许数tcp_keepalive_probes;或者在已设置保活探测 * 段的次数时,已发送次数超过了保活探测次数,则 * 需要断开连接,给对方发送RST段,并报告相应错误, * 关闭相应的传输控制块。 */ if (icsk->icsk_probes_out >= keepalive_probes(tp)) { tcp_send_active_reset(sk, GFP_ATOMIC); tcp_write_err(sk); goto out; } /* 发送保活段,并计算下次激活保活定时器的时间。*/ if (tcp_write_wakeup(sk) <= 0) { icsk->icsk_probes_out++; elapsed = keepalive_intvl_when(tp); } else { /* If keepalive was lost due to local congestion, * try harder. */ elapsed = TCP_RESOURCE_PROBE_INTERVAL; } } else { /* It is tp->rcv_tstamp + keepalive_time_when(tp) */ elapsed = keepalive_time_when(tp) - elapsed; } TCP_CHECK_TIMER(sk); sk_mem_reclaim(sk); resched: inet_csk_reset_keepalive_timer (sk, elapsed); goto out; death: tcp_done(sk); out: bh_unlock_sock(sk); sock_put(sk); }
{ "pile_set_name": "Github" }
/** * \file config.h * * Based on XySSL: Copyright (C) 2006-2008 Christophe Devine * * Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the names of PolarSSL or XySSL 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. * * This set of compile-time options may be used to enable * or disable features selectively, and reduce the global * memory footprint. */ #ifndef POLARSSL_CONFIG_H #define POLARSSL_CONFIG_H #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif /* * Uncomment if native integers are 8-bit wide. * #define POLARSSL_HAVE_INT8 */ /* * Uncomment if native integers are 16-bit wide. * #define POLARSSL_HAVE_INT16 */ /* * Uncomment if the compiler supports long long. #define POLARSSL_HAVE_LONGLONG */ /* * Uncomment to enable the use of assembly code. */ /* #define POLARSSL_HAVE_ASM */ /* * Uncomment if the CPU supports SSE2 (IA-32 specific). * #define POLARSSL_HAVE_SSE2 */ /* * Enable all SSL/TLS debugging messages. */ #define POLARSSL_DEBUG_MSG /* * Enable the checkup functions (*_self_test). */ #define POLARSSL_SELF_TEST /* * Enable the prime-number generation code. */ #define POLARSSL_GENPRIME /* * Uncomment this macro to store the AES tables in ROM. * #define POLARSSL_AES_ROM_TABLES */ /* * Module: library/aes.c * Caller: library/ssl_tls.c * * This module enables the following ciphersuites: * SSL_RSA_AES_128_SHA * SSL_RSA_AES_256_SHA * SSL_EDH_RSA_AES_256_SHA */ #define POLARSSL_AES_C /* * Module: library/arc4.c * Caller: library/ssl_tls.c * * This module enables the following ciphersuites: * SSL_RSA_RC4_128_MD5 * SSL_RSA_RC4_128_SHA */ #define POLARSSL_ARC4_C /* * Module: library/base64.c * Caller: library/x509parse.c * * This module is required for X.509 support. */ #define POLARSSL_BASE64_C /* * Module: library/bignum.c * Caller: library/dhm.c * library/rsa.c * library/ssl_tls.c * library/x509parse.c * * This module is required for RSA and DHM support. */ #define POLARSSL_BIGNUM_C /* * Module: library/camellia.c * Caller: * * This module enabled the following cipher suites: */ #define POLARSSL_CAMELLIA_C /* * Module: library/certs.c * Caller: * * This module is used for testing (ssl_client/server). */ #define POLARSSL_CERTS_C /* * Module: library/debug.c * Caller: library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c * * This module provides debugging functions. */ #define POLARSSL_DEBUG_C /* * Module: library/des.c * Caller: library/ssl_tls.c * * This module enables the following ciphersuites: * SSL_RSA_DES_168_SHA * SSL_EDH_RSA_DES_168_SHA */ #define POLARSSL_DES_C /* * Module: library/dhm.c * Caller: library/ssl_cli.c * library/ssl_srv.c * * This module enables the following ciphersuites: * SSL_EDH_RSA_DES_168_SHA * SSL_EDH_RSA_AES_256_SHA */ #define POLARSSL_DHM_C /* * Module: library/havege.c * Caller: * * This module enables the HAVEGE random number generator. */ #define POLARSSL_HAVEGE_C /* * Module: library/md2.c * Caller: library/x509parse.c * * Uncomment to enable support for (rare) MD2-signed X.509 certs. * #define POLARSSL_MD2_C */ /* * Module: library/md4.c * Caller: library/x509parse.c * * Uncomment to enable support for (rare) MD4-signed X.509 certs. * #define POLARSSL_MD4_C */ /* * Module: library/md5.c * Caller: library/ssl_tls.c * library/x509parse.c * * This module is required for SSL/TLS and X.509. */ #define POLARSSL_MD5_C /* * Module: library/net.c * Caller: * * This module provides TCP/IP networking routines. */ #define POLARSSL_NET_C /* * Module: library/padlock.c * Caller: library/aes.c * * This modules adds support for the VIA PadLock on x86. */ #define POLARSSL_PADLOCK_C /* * Module: library/rsa.c * Caller: library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c * library/x509.c * * This module is required for SSL/TLS and MD5-signed certificates. */ #define POLARSSL_RSA_C /* * Module: library/sha1.c * Caller: library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c * library/x509parse.c * * This module is required for SSL/TLS and SHA1-signed certificates. */ #define POLARSSL_SHA1_C /* * Module: library/sha2.c * Caller: * * This module adds support for SHA-224 and SHA-256. */ #define POLARSSL_SHA2_C /* * Module: library/sha4.c * Caller: * * This module adds support for SHA-384 and SHA-512. */ #define POLARSSL_SHA4_C /* * Module: library/ssl_cli.c * Caller: * * This module is required for SSL/TLS client support. */ #define POLARSSL_SSL_CLI_C /* * Module: library/ssl_srv.c * Caller: * * This module is required for SSL/TLS server support. */ #define POLARSSL_SSL_SRV_C /* * Module: library/ssl_tls.c * Caller: library/ssl_cli.c * library/ssl_srv.c * * This module is required for SSL/TLS. */ #define POLARSSL_SSL_TLS_C /* * Module: library/timing.c * Caller: library/havege.c * * This module is used by the HAVEGE random number generator. */ #define POLARSSL_TIMING_C /* * Module: library/x509parse.c * Caller: library/ssl_cli.c * library/ssl_srv.c * library/ssl_tls.c * * This module is required for X.509 certificate parsing. */ #define POLARSSL_X509_PARSE_C /* * Module: library/x509_write.c * Caller: * * This module is required for X.509 certificate writing. */ #define POLARSSL_X509_WRITE_C /* * Module: library/xtea.c * Caller: */ #define POLARSSL_XTEA_C #endif /* config.h */
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 26561101b47502a44abba67849dda126 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
module.exports = require('./forEachRight');
{ "pile_set_name": "Github" }
# # Makefile for Cavium crypto device drivers # obj-$(CONFIG_CRYPTO_DEV_CAVIUM_ZIP) += zip/
{ "pile_set_name": "Github" }
Icon component is a simple wrapper around SVG element with additional properties, for example, `spin` #### HTMLElement attributes You can use any HTMLElement attributes, like `id`, `class`, `style`, `data-*` and so on #### Events Any events
{ "pile_set_name": "Github" }
/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/statistics.h" #include "common/clockFunctions.h" #include "ngsi/ParseData.h" #include "ngsi/StatusCode.h" #include "ngsi10/UpdateContextResponse.h" #include "rest/ConnectionInfo.h" #include "rest/uriParamNames.h" #include "serviceRoutines/postUpdateContext.h" #include "serviceRoutines/deleteIndividualContextEntity.h" /* **************************************************************************** * * deleteIndividualContextEntity - * * Corresponding Standard Operation: UpdateContext/DELETE * * DELETE /v1/contextEntities/{entityId::id} * * Payload In: None * Payload Out: StatusCode * * URI parameters: * - entity::type=TYPE * - note that '!exist=entity::type' and 'exist=entity::type' are not supported by convenience operations * that use the standard operation UpdateContext as there is no restriction within UpdateContext. * * 00. URI params * 01. Fill in UpdateContextRequest from URL-data + URI params * 02. Call postUpdateContext standard service routine * 03. Translate UpdateContextResponse to StatusCode * 04. If not found, put entity info in details * 05. Cleanup and return result */ std::string deleteIndividualContextEntity ( ConnectionInfo* ciP, int components, std::vector<std::string>& compV, ParseData* parseDataP ) { std::string answer; std::string entityId = compV[2]; std::string entityType = ciP->uriParam[URI_PARAM_ENTITY_TYPE]; StatusCode response; // 01. Fill in UpdateContextRequest fromURL-data + URI params parseDataP->upcr.res.fill(entityId, entityType, "false", "", ActionTypeDelete); // 02. Call postUpdateContext standard service routine answer = postUpdateContext(ciP, components, compV, parseDataP); // 03. Translate UpdateContextResponse to StatusCode response.fill(parseDataP->upcrs.res); // 04. If not found, put entity info in details if ((response.code == SccContextElementNotFound) && (response.details.empty())) { response.details = entityId; } // 05. Cleanup and return result TIMED_RENDER(answer = response.toJsonV1(false, false)); response.release(); parseDataP->upcr.res.release(); return answer; }
{ "pile_set_name": "Github" }
--- logohandle: skyfonts sort: skyfonts title: SkyFonts website: 'http://skyfonts.com/' ---
{ "pile_set_name": "Github" }
#. extracted from intro.txt #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2015-02-22 10:27+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Translate Toolkit 1.12.0\n" #: intro.txt:1 msgid "" "calcurse Online Help\n" "====================" msgstr "" #: intro.txt:4 msgid "" "Welcome to the calcurse online help. The online help system allows for " "easily\n" "getting help on specific calcurse features." msgstr "" #: intro.txt:7 msgid "" "On the calcurse main screen, type `:help <feature>` (e.g. `:help add`) or\n" "`:help <key>` (e.g. `:help ^A`) to get help on a specific feature or key\n" "binding. Type `:help` without any parameter to display this introduction or\n" "simply use the corresponding keyboard shortcut (`?` by default)." msgstr "" #: intro.txt:12 msgid "" "All help texts are displayed using an external pager. You need to exit the\n" "pager in order to get back to calcurse (pressing `q` should almost always\n" "work). The default pager can be changed by setting the PAGER environment\n" "variable." msgstr ""
{ "pile_set_name": "Github" }
# Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.2.0, available at https://www.contributor-covenant.org/version/1/2/0/code-of-conduct.html.
{ "pile_set_name": "Github" }
// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. package bidi // Class is the Unicode BiDi class. Each rune has a single class. type Class uint const ( L Class = iota // LeftToRight R // RightToLeft EN // EuropeanNumber ES // EuropeanSeparator ET // EuropeanTerminator AN // ArabicNumber CS // CommonSeparator B // ParagraphSeparator S // SegmentSeparator WS // WhiteSpace ON // OtherNeutral BN // BoundaryNeutral NSM // NonspacingMark AL // ArabicLetter Control // Control LRO - PDI numClass LRO // LeftToRightOverride RLO // RightToLeftOverride LRE // LeftToRightEmbedding RLE // RightToLeftEmbedding PDF // PopDirectionalFormat LRI // LeftToRightIsolate RLI // RightToLeftIsolate FSI // FirstStrongIsolate PDI // PopDirectionalIsolate unknownClass = ^Class(0) ) var controlToClass = map[rune]Class{ 0x202D: LRO, // LeftToRightOverride, 0x202E: RLO, // RightToLeftOverride, 0x202A: LRE, // LeftToRightEmbedding, 0x202B: RLE, // RightToLeftEmbedding, 0x202C: PDF, // PopDirectionalFormat, 0x2066: LRI, // LeftToRightIsolate, 0x2067: RLI, // RightToLeftIsolate, 0x2068: FSI, // FirstStrongIsolate, 0x2069: PDI, // PopDirectionalIsolate, } // A trie entry has the following bits: // 7..5 XOR mask for brackets // 4 1: Bracket open, 0: Bracket close // 3..0 Class type const ( openMask = 0x10 xorMaskShift = 5 )
{ "pile_set_name": "Github" }
/* * Debugging macro for DaVinci * * Author: Kevin Hilman, MontaVista Software, Inc. <source@mvista.com> * * 2007 (c) MontaVista Software, Inc. This file is licensed under * the terms of the GNU General Public License version 2. This program * is licensed "as is" without any warranty of any kind, whether express * or implied. */ /* Modifications * Jan 2009 Chaithrika U S Added senduart, busyuart, waituart * macros, based on debug-8250.S file * but using 32-bit accesses required for * some davinci devices. */ #include <linux/serial_reg.h> #include <mach/serial.h> #define UART_SHIFT 2 .pushsection .data davinci_uart_phys: .word 0 davinci_uart_virt: .word 0 .popsection .macro addruart, rp, rv, tmp /* Use davinci_uart_phys/virt if already configured */ 10: adr \rp, 99f @ get effective addr of 99f ldr \rv, [\rp] @ get absolute addr of 99f sub \rv, \rv, \rp @ offset between the two ldr \rp, [\rp, #4] @ abs addr of omap_uart_phys sub \tmp, \rp, \rv @ make it effective ldr \rp, [\tmp, #0] @ davinci_uart_phys ldr \rv, [\tmp, #4] @ davinci_uart_virt cmp \rp, #0 @ is port configured? cmpne \rv, #0 bne 100f @ already configured /* Check the debug UART address set in uncompress.h */ and \rp, pc, #0xff000000 ldr \rv, =DAVINCI_UART_INFO_OFS add \rp, \rp, \rv /* Copy uart phys address from decompressor uart info */ ldr \rv, [\rp, #0] str \rv, [\tmp, #0] /* Copy uart virt address from decompressor uart info */ ldr \rv, [\rp, #4] str \rv, [\tmp, #4] b 10b .align 99: .word . .word davinci_uart_phys .ltorg 100: .endm .macro senduart,rd,rx str \rd, [\rx, #UART_TX << UART_SHIFT] .endm .macro busyuart,rd,rx 1002: ldr \rd, [\rx, #UART_LSR << UART_SHIFT] and \rd, \rd, #UART_LSR_TEMT | UART_LSR_THRE teq \rd, #UART_LSR_TEMT | UART_LSR_THRE bne 1002b .endm .macro waituart,rd,rx #ifdef FLOW_CONTROL 1001: ldr \rd, [\rx, #UART_MSR << UART_SHIFT] tst \rd, #UART_MSR_CTS beq 1001b #endif .endm
{ "pile_set_name": "Github" }
#pragma once /* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vector> namespace ZXing { class GenericGF; /** * <p>Implements Reed-Solomon decoding, as the name implies.</p> * * <p>The algorithm will not be explained here, but the following references were helpful * in creating this implementation:</p> * * <ul> * <li>Bruce Maggs. * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps"> * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li> * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf"> * "Chapter 5. Generalized Reed-Solomon Codes"</a> * (see discussion of Euclidean algorithm)</li> * </ul> * * <p>Much credit is due to William Rucklidge since portions of this code are an indirect * port of his C++ Reed-Solomon implementation.</p> * * @author Sean Owen * @author William Rucklidge * @author sanfordsquires */ class ReedSolomonDecoder { public: /** * <p>Decodes given set of received codewords, which include both data and error-correction * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, * in the input.</p> * * @param received data and error-correction codewords * @param twoS number of error-correction codewords available * @throws ReedSolomonException if decoding fails for any reason */ static bool Decode(const GenericGF& field, std::vector<int>& received, int twoS); }; } // ZXing
{ "pile_set_name": "Github" }
(cl:in-package #:cleavir-hir-transformations) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; CONVERT-CONSTANT-TO-IMMEDIATE. ;;; ;;; Before LOAD-TIME-VALUE-INPUTs are hoisted, we make a pass to see ;;; whether any of them should be converted to an IMMEDIATE-INPUT. ;;; Whether such a conversion should take place depends on the ;;; implementation. For that reason, we call the generic function ;;; CONVERT-CONSTANT-TO-IMMEDIATE to do the conversion. ;;; ;;; The function CONVERT-CONSTANT-TO-IMMEDIATE may return NIL, meaning ;;; that this constant does not have a representation as an immediate ;;; value, or it may return a possibly-negative integer which is ;;; taken to be the representation of the constant as an immediate ;;; machine word. A default method is provided that always returns ;;; NIL. ;;; ;;; Client code should provide a method on this generic function that ;;; specialized on the SYSTEM parameter. (defgeneric convert-constant-to-immediate (constant system)) (defmethod convert-constant-to-immediate (constant system) (declare (ignore constant system)) nil) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; CONVERT-CONSTANTS-TO-IMMEDIATE. ;;; (defun convert-constants-to-immediate (initial-instruction system) (cleavir-ir:map-instructions-arbitrary-order (lambda (instruction) (loop for input in (cleavir-ir:inputs instruction) when (and (typep input 'cleavir-ir:load-time-value-input) (load-time-value-is-constant-p input)) do (let* ((constant (load-time-value-constant input)) (possible-immediate (convert-constant-to-immediate constant system))) (unless (null possible-immediate) (change-class input 'cleavir-ir:immediate-input :value possible-immediate))))) initial-instruction))
{ "pile_set_name": "Github" }
defmodule Explorer.Chain.Address.Name do @moduledoc """ Represents a name for an Address. """ use Explorer.Schema import Ecto.Changeset alias Ecto.Changeset alias Explorer.Chain.{Address, Hash} @typedoc """ * `address` - the `t:Explorer.Chain.Address.t/0` with `value` at end of `block_number`. * `address_hash` - foreign key for `address`. * `name` - name for the address * `primary` - flag for if the name is the primary name for the address """ @type t :: %__MODULE__{ address: %Ecto.Association.NotLoaded{} | Address.t(), address_hash: Hash.Address.t(), name: String.t(), primary: boolean(), metadata: map() } @primary_key false schema "address_names" do field(:name, :string) field(:primary, :boolean) field(:metadata, :map) belongs_to(:address, Address, foreign_key: :address_hash, references: :hash, type: Hash.Address) timestamps() end @required_fields ~w(address_hash name)a @optional_fields ~w(primary metadata)a @allowed_fields @required_fields ++ @optional_fields def changeset(%__MODULE__{} = struct, params \\ %{}) do struct |> cast(params, @allowed_fields) |> validate_required(@required_fields) |> trim_name() |> foreign_key_constraint(:address_hash) end defp trim_name(%Changeset{valid?: false} = changeset), do: changeset defp trim_name(%Changeset{valid?: true} = changeset) do case get_change(changeset, :name) do nil -> changeset name -> put_change(changeset, :name, String.trim(name)) end end end
{ "pile_set_name": "Github" }
/* * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.stream; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.Spliterator; import java.util.concurrent.CountedCompleter; import java.util.function.Predicate; import java.util.function.Supplier; /** * Factory for instances of a short-circuiting {@code TerminalOp} that searches * for an element in a stream pipeline, and terminates when it finds one. * Supported variants include find-first (find the first element in the * encounter order) and find-any (find any element, may not be the first in * encounter order.) * * @since 1.8 */ final class FindOps { private FindOps() { } /** * Constructs a {@code TerminalOp} for streams of objects. * * @param <T> the type of elements of the stream * @param mustFindFirst whether the {@code TerminalOp} must produce the * first element in the encounter order * @return a {@code TerminalOp} implementing the find operation */ @SuppressWarnings("unchecked") public static <T> TerminalOp<T, Optional<T>> makeRef(boolean mustFindFirst) { return (TerminalOp<T, Optional<T>>) (mustFindFirst ? FindSink.OfRef.OP_FIND_FIRST : FindSink.OfRef.OP_FIND_ANY); } /** * Constructs a {@code TerminalOp} for streams of ints. * * @param mustFindFirst whether the {@code TerminalOp} must produce the * first element in the encounter order * @return a {@code TerminalOp} implementing the find operation */ public static TerminalOp<Integer, OptionalInt> makeInt(boolean mustFindFirst) { return mustFindFirst ? FindSink.OfInt.OP_FIND_FIRST : FindSink.OfInt.OP_FIND_ANY; } /** * Constructs a {@code TerminalOp} for streams of longs. * * @param mustFindFirst whether the {@code TerminalOp} must produce the * first element in the encounter order * @return a {@code TerminalOp} implementing the find operation */ public static TerminalOp<Long, OptionalLong> makeLong(boolean mustFindFirst) { return mustFindFirst ? FindSink.OfLong.OP_FIND_FIRST : FindSink.OfLong.OP_FIND_ANY; } /** * Constructs a {@code FindOp} for streams of doubles. * * @param mustFindFirst whether the {@code TerminalOp} must produce the * first element in the encounter order * @return a {@code TerminalOp} implementing the find operation */ public static TerminalOp<Double, OptionalDouble> makeDouble(boolean mustFindFirst) { return mustFindFirst ? FindSink.OfDouble.OP_FIND_FIRST : FindSink.OfDouble.OP_FIND_ANY; } /** * A short-circuiting {@code TerminalOp} that searches for an element in a * stream pipeline, and terminates when it finds one. Implements both * find-first (find the first element in the encounter order) and find-any * (find any element, may not be the first in encounter order.) * * @param <T> the output type of the stream pipeline * @param <O> the result type of the find operation, typically an optional * type */ private static final class FindOp<T, O> implements TerminalOp<T, O> { private final StreamShape shape; final int opFlags; final O emptyValue; final Predicate<O> presentPredicate; final Supplier<TerminalSink<T, O>> sinkSupplier; /** * Constructs a {@code FindOp}. * * @param mustFindFirst if true, must find the first element in * encounter order, otherwise can find any element * @param shape stream shape of elements to search * @param emptyValue result value corresponding to "found nothing" * @param presentPredicate {@code Predicate} on result value * corresponding to "found something" * @param sinkSupplier supplier for a {@code TerminalSink} implementing * the matching functionality */ FindOp(boolean mustFindFirst, StreamShape shape, O emptyValue, Predicate<O> presentPredicate, Supplier<TerminalSink<T, O>> sinkSupplier) { this.opFlags = StreamOpFlag.IS_SHORT_CIRCUIT | (mustFindFirst ? 0 : StreamOpFlag.NOT_ORDERED); this.shape = shape; this.emptyValue = emptyValue; this.presentPredicate = presentPredicate; this.sinkSupplier = sinkSupplier; } @Override public int getOpFlags() { return opFlags; } @Override public StreamShape inputShape() { return shape; } @Override public <S> O evaluateSequential(PipelineHelper<T> helper, Spliterator<S> spliterator) { O result = helper.wrapAndCopyInto(sinkSupplier.get(), spliterator).get(); return result != null ? result : emptyValue; } @Override public <P_IN> O evaluateParallel(PipelineHelper<T> helper, Spliterator<P_IN> spliterator) { // This takes into account the upstream ops flags and the terminal // op flags and therefore takes into account findFirst or findAny boolean mustFindFirst = StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags()); return new FindTask<>(this, mustFindFirst, helper, spliterator).invoke(); } } /** * Implementation of @{code TerminalSink} that implements the find * functionality, requesting cancellation when something has been found * * @param <T> The type of input element * @param <O> The result type, typically an optional type */ private abstract static class FindSink<T, O> implements TerminalSink<T, O> { boolean hasValue; T value; FindSink() {} // Avoid creation of special accessor @Override public void accept(T value) { if (!hasValue) { hasValue = true; this.value = value; } } @Override public boolean cancellationRequested() { return hasValue; } /** Specialization of {@code FindSink} for reference streams */ static final class OfRef<T> extends FindSink<T, Optional<T>> { @Override public Optional<T> get() { return hasValue ? Optional.of(value) : null; } static final TerminalOp<?, ?> OP_FIND_FIRST = new FindOp<>(true, StreamShape.REFERENCE, Optional.empty(), Optional::isPresent, FindSink.OfRef::new); static final TerminalOp<?, ?> OP_FIND_ANY = new FindOp<>(false, StreamShape.REFERENCE, Optional.empty(), Optional::isPresent, FindSink.OfRef::new); } /** Specialization of {@code FindSink} for int streams */ static final class OfInt extends FindSink<Integer, OptionalInt> implements Sink.OfInt { @Override public void accept(int value) { // Boxing is OK here, since few values will actually flow into the sink accept((Integer) value); } @Override public OptionalInt get() { return hasValue ? OptionalInt.of(value) : null; } static final TerminalOp<Integer, OptionalInt> OP_FIND_FIRST = new FindOp<>(true, StreamShape.INT_VALUE, OptionalInt.empty(), OptionalInt::isPresent, FindSink.OfInt::new); static final TerminalOp<Integer, OptionalInt> OP_FIND_ANY = new FindOp<>(false, StreamShape.INT_VALUE, OptionalInt.empty(), OptionalInt::isPresent, FindSink.OfInt::new); } /** Specialization of {@code FindSink} for long streams */ static final class OfLong extends FindSink<Long, OptionalLong> implements Sink.OfLong { @Override public void accept(long value) { // Boxing is OK here, since few values will actually flow into the sink accept((Long) value); } @Override public OptionalLong get() { return hasValue ? OptionalLong.of(value) : null; } static final TerminalOp<Long, OptionalLong> OP_FIND_FIRST = new FindOp<>(true, StreamShape.LONG_VALUE, OptionalLong.empty(), OptionalLong::isPresent, FindSink.OfLong::new); static final TerminalOp<Long, OptionalLong> OP_FIND_ANY = new FindOp<>(false, StreamShape.LONG_VALUE, OptionalLong.empty(), OptionalLong::isPresent, FindSink.OfLong::new); } /** Specialization of {@code FindSink} for double streams */ static final class OfDouble extends FindSink<Double, OptionalDouble> implements Sink.OfDouble { @Override public void accept(double value) { // Boxing is OK here, since few values will actually flow into the sink accept((Double) value); } @Override public OptionalDouble get() { return hasValue ? OptionalDouble.of(value) : null; } static final TerminalOp<Double, OptionalDouble> OP_FIND_FIRST = new FindOp<>(true, StreamShape.DOUBLE_VALUE, OptionalDouble.empty(), OptionalDouble::isPresent, FindSink.OfDouble::new); static final TerminalOp<Double, OptionalDouble> OP_FIND_ANY = new FindOp<>(false, StreamShape.DOUBLE_VALUE, OptionalDouble.empty(), OptionalDouble::isPresent, FindSink.OfDouble::new); } } /** * {@code ForkJoinTask} implementing parallel short-circuiting search * @param <P_IN> Input element type to the stream pipeline * @param <P_OUT> Output element type from the stream pipeline * @param <O> Result type from the find operation */ @SuppressWarnings("serial") private static final class FindTask<P_IN, P_OUT, O> extends AbstractShortCircuitTask<P_IN, P_OUT, O, FindTask<P_IN, P_OUT, O>> { private final FindOp<P_OUT, O> op; private final boolean mustFindFirst; FindTask(FindOp<P_OUT, O> op, boolean mustFindFirst, PipelineHelper<P_OUT> helper, Spliterator<P_IN> spliterator) { super(helper, spliterator); this.mustFindFirst = mustFindFirst; this.op = op; } FindTask(FindTask<P_IN, P_OUT, O> parent, Spliterator<P_IN> spliterator) { super(parent, spliterator); this.mustFindFirst = parent.mustFindFirst; this.op = parent.op; } @Override protected FindTask<P_IN, P_OUT, O> makeChild(Spliterator<P_IN> spliterator) { return new FindTask<>(this, spliterator); } @Override protected O getEmptyResult() { return op.emptyValue; } private void foundResult(O answer) { if (isLeftmostNode()) shortCircuit(answer); else cancelLaterNodes(); } @Override protected O doLeaf() { O result = helper.wrapAndCopyInto(op.sinkSupplier.get(), spliterator).get(); if (!mustFindFirst) { if (result != null) shortCircuit(result); return null; } else { if (result != null) { foundResult(result); return result; } else return null; } } @Override public void onCompletion(CountedCompleter<?> caller) { if (mustFindFirst) { for (FindTask<P_IN, P_OUT, O> child = leftChild, p = null; child != p; p = child, child = rightChild) { O result = child.getLocalResult(); if (result != null && op.presentPredicate.test(result)) { setLocalResult(result); foundResult(result); break; } } } super.onCompletion(caller); } } }
{ "pile_set_name": "Github" }
/** * file : Http.h * author : bushaofeng * create : 2016-08-25 00:51 * func : Http * history: */ #ifndef __Http_H_ #define __Http_H_ #include "bs.h" #include <string> #include <vector> using namespace std; /* http头 */ typedef pair_t(string_t, string_t) http_header_t; void* http_header_init(void* p); void http_header_set(http_header_t* header, const char* key, const char* value); void http_header_destroy(void* p); namespace mc { /// 回调 class HttpCallback{ public: virtual void done(int http_code, status_t st, char* text) = 0; }; class DownCallback{ public: /// writen:本次下载字节数, total_writen:已经下载字节数,total_expect_write:总下载字节数 virtual void progress(uint64_t writen, uint64_t total_writen, uint64_t total_expect_write) = 0; virtual void done(int http_code, status_t st, const char* location) = 0; }; class IOSEnv; /// http class HttpSession{ public: HttpSession(void* threadpool=NULL); ~HttpSession(); virtual void get(const char* url, HttpCallback* callback = NULL); virtual void post(const char* url, const char* body, uint32_t length = 0,HttpCallback* callback = NULL); virtual void put(const char* url, const char* body, uint32_t length = 0,HttpCallback* callback = NULL); virtual void del(const char* url, HttpCallback* callback = NULL); virtual void http(const char* url, const char* method, const char* body = NULL, uint32_t length = 0, HttpCallback* callback = NULL); virtual void download(const char* url, const char* path, DownCallback* callback); void addHttpHeader(const char* key, const char* value); const static uint32_t HTTP_TIMEOUT = 10; // 过期时间 protected: void setOpt(void* curl, http_method_t method, const char* body, uint32_t length); vector<pair<string, string> > m_headers; void* m_thread_pool; #ifdef __IOS__ IOSEnv* m_iosenv; #endif }; /// https class HttpsSession: public HttpSession{ public: }; } #endif
{ "pile_set_name": "Github" }
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: dev \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "constant"; object momentumTransport.liquid; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // simulationType laminar; // ************************************************************************* //
{ "pile_set_name": "Github" }
from __future__ import absolute_import from . import driver from . import objective from . import plugin from . import technique
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef __NVKM_DEVINIT_H__ #define __NVKM_DEVINIT_H__ #include <core/subdev.h> struct nvkm_devinit; struct nvkm_devinit { const struct nvkm_devinit_func *func; struct nvkm_subdev subdev; bool post; bool force_post; }; u32 nvkm_devinit_mmio(struct nvkm_devinit *, u32 addr); int nvkm_devinit_pll_set(struct nvkm_devinit *, u32 type, u32 khz); void nvkm_devinit_meminit(struct nvkm_devinit *); u64 nvkm_devinit_disable(struct nvkm_devinit *); int nvkm_devinit_post(struct nvkm_devinit *, u64 *disable); int nv04_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int nv05_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int nv10_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int nv1a_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int nv20_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int nv50_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int g84_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int g98_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int gt215_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int mcp89_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int gf100_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int gm107_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); int gm200_devinit_new(struct nvkm_device *, int, struct nvkm_devinit **); #endif
{ "pile_set_name": "Github" }
<?php namespace Config; use CodeIgniter\Config\BaseConfig; class Filters extends BaseConfig { // Makes reading things below nicer, // and simpler to change out script that's used. public $aliases = [ 'csrf' => \CodeIgniter\Filters\CSRF::class, 'toolbar' => \CodeIgniter\Filters\DebugToolbar::class, 'honeypot' => \CodeIgniter\Filters\Honeypot::class, 'authFilter' => \App\Filters\AuthFilter::class, ]; // Always applied before every request public $globals = [ 'before' => [ //'honeypot' // 'csrf', ], 'after' => [ 'toolbar', //'honeypot' ], ]; // Works on all of a particular HTTP method // (GET, POST, etc) as BEFORE filters only // like: 'post' => ['CSRF', 'throttle'], public $methods = []; // List filter aliases and any before/after uri patterns // that they should run on, like: // 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']], public $filters = [ 'authFilter' => [ 'before' => [ 'api/user/*', 'api/user', ], ], ]; }
{ "pile_set_name": "Github" }
<!doctype html> <html> <head> <title>CodeMirror 2: Oracle PL/SQL mode</title> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="plsql.js"></script> <link rel="stylesheet" href="../../theme/default.css"> <link rel="stylesheet" href="../../css/docs.css"> <style>.CodeMirror {border: 2px inset #dee;}</style> </head> <body> <h1>CodeMirror 2: Oracle PL/SQL mode</h1> <form><textarea id="code" name="code"> -- Oracle PL/SQL Code Demo /* based on c-like mode, adapted to PL/SQL by Peter Raganitsch ( http://www.oracle-and-apex.com/ ) April 2011 */ DECLARE vIdx NUMBER; vString VARCHAR2(100); cText CONSTANT VARCHAR2(100) := 'That''s it! Have fun with CodeMirror 2'; BEGIN vIdx := 0; -- FOR rDATA IN ( SELECT * FROM EMP ORDER BY EMPNO ) LOOP vIdx := vIdx + 1; vString := rDATA.EMPNO || ' - ' || rDATA.ENAME; -- UPDATE EMP SET SAL = SAL * 101/100 WHERE EMPNO = rDATA.EMPNO ; END LOOP; -- SYS.DBMS_OUTPUT.Put_Line (cText); END; -- </textarea></form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, indentUnit: 4, mode: "text/x-plsql" }); </script> <p> Simple mode that handles Oracle PL/SQL language (and Oracle SQL, of course). </p> <p><strong>MIME type defined:</strong> <code>text/x-plsql</code> (PLSQL code) </html>
{ "pile_set_name": "Github" }
comment = 'Test code for SECURITY LABEL feature' default_version = '1.0' module_pathname = '$libdir/dummy_seclabel' relocatable = true
{ "pile_set_name": "Github" }
--- title: KSPROPERTY\_TVAUDIO\_CAPS description: The KSPROPERTY\_TVAUDIO\_CAPS property retrieves the capabilities of the TV audio device. This property must be implemented. ms.assetid: a5b7348e-0f85-430c-acf0-c35e289ef338 keywords: ["KSPROPERTY_TVAUDIO_CAPS Streaming Media Devices"] topic_type: - apiref api_name: - KSPROPERTY_TVAUDIO_CAPS api_location: - Ksmedia.h api_type: - HeaderDef ms.date: 11/28/2017 ms.localizationpriority: medium --- # KSPROPERTY\_TVAUDIO\_CAPS The KSPROPERTY\_TVAUDIO\_CAPS property retrieves the capabilities of the TV audio device. This property must be implemented. ## <span id="ddk_ksproperty_tvaudio_caps_ks"></span><span id="DDK_KSPROPERTY_TVAUDIO_CAPS_KS"></span> ### Usage Summary Table <table> <colgroup> <col width="20%" /> <col width="20%" /> <col width="20%" /> <col width="20%" /> <col width="20%" /> </colgroup> <thead> <tr class="header"> <th>Get</th> <th>Set</th> <th>Target</th> <th>Property descriptor type</th> <th>Property value type</th> </tr> </thead> <tbody> <tr class="odd"> <td><p>Yes</p></td> <td><p>No</p></td> <td><p>Pin</p></td> <td><p><a href="/windows-hardware/drivers/ddi/ksmedia/ns-ksmedia-ksproperty_tvaudio_caps_s" data-raw-source="[&lt;strong&gt;KSPROPERTY_TVAUDIO_CAPS_S&lt;/strong&gt;](/windows-hardware/drivers/ddi/ksmedia/ns-ksmedia-ksproperty_tvaudio_caps_s)"><strong>KSPROPERTY_TVAUDIO_CAPS_S</strong></a></p></td> <td><p>ULONG</p></td> </tr> </tbody> </table> The property value (operation data) is a ULONG that specifies the capabilities of the TV audio device, such as stereo versus mono audio support and multiple language capabilities. Remarks ------- The **Capabilities** member of the KSPROPERTY\_TVAUDIO\_CAPS\_S structure specifies the capabilities of the TV audio device. Requirements ------------ <table> <colgroup> <col width="50%" /> <col width="50%" /> </colgroup> <tbody> <tr class="odd"> <td><p>Header</p></td> <td>Ksmedia.h (include Ksmedia.h)</td> </tr> </tbody> </table> ## See also [**KSPROPERTY**](/windows-hardware/drivers/ddi/ks/ns-ks-ksidentifier) [**KSPROPERTY\_TVAUDIO\_CAPS\_S**](/windows-hardware/drivers/ddi/ksmedia/ns-ksmedia-ksproperty_tvaudio_caps_s)
{ "pile_set_name": "Github" }
if(NOT IS_DIRECTORY "${EXPECTED_WORKING_DIR}") message(FATAL_ERROR "EXPECTED_WORKING_DIR is not a directory: ${EXPECTED_WORKING_DIR}") endif() foreach(d CMAKE_BINARY_DIR CMAKE_CURRENT_BINARY_DIR CMAKE_SOURCE_DIR CMAKE_CURRENT_SOURCE_DIR) if(NOT DEFINED ${d}) message(FATAL_ERROR "${d} is not defined") endif() if(EXPECTED_WORKING_DIR STREQUAL "${${d}}") message(STATUS "${d} is the expected working directory (${EXPECTED_WORKING_DIR})") else() message(FATAL_ERROR "${d} = \"${${d}}\" is not the expected working directory (${EXPECTED_WORKING_DIR})") endif() endforeach()
{ "pile_set_name": "Github" }
// go run mksysnum.go https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,openbsd package unix const ( SYS_EXIT = 1 // { void sys_exit(int rval); } SYS_FORK = 2 // { int sys_fork(void); } SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, size_t nbyte); } SYS_OPEN = 5 // { int sys_open(const char *path, int flags, ... mode_t mode); } SYS_CLOSE = 6 // { int sys_close(int fd); } SYS_GETENTROPY = 7 // { int sys_getentropy(void *buf, size_t nbyte); } SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, size_t psize); } SYS_LINK = 9 // { int sys_link(const char *path, const char *link); } SYS_UNLINK = 10 // { int sys_unlink(const char *path); } SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, int options, struct rusage *rusage); } SYS_CHDIR = 12 // { int sys_chdir(const char *path); } SYS_FCHDIR = 13 // { int sys_fchdir(int fd); } SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, dev_t dev); } SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); } SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, gid_t gid); } SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); } SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, struct rusage *rusage); } SYS_GETPID = 20 // { pid_t sys_getpid(void); } SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, int flags, void *data); } SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); } SYS_SETUID = 23 // { int sys_setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t sys_getuid(void); } SYS_GETEUID = 25 // { uid_t sys_geteuid(void); } SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, int data); } SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, const struct msghdr *msg, int flags); } SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlenaddr); } SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, socklen_t *anamelen); } SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, socklen_t *alen); } SYS_ACCESS = 33 // { int sys_access(const char *path, int amode); } SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); } SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); } SYS_SYNC = 36 // { void sys_sync(void); } SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); } SYS_GETPPID = 39 // { pid_t sys_getppid(void); } SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); } SYS_DUP = 41 // { int sys_dup(int fd); } SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, struct stat *buf, int flag); } SYS_GETEGID = 43 // { gid_t sys_getegid(void); } SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, u_long offset, u_int scale); } SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, int facs, pid_t pid); } SYS_SIGACTION = 46 // { int sys_sigaction(int signum, const struct sigaction *nsa, struct sigaction *osa); } SYS_GETGID = 47 // { gid_t sys_getgid(void); } SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); } SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); } SYS_ACCT = 51 // { int sys_acct(const char *path); } SYS_SIGPENDING = 52 // { int sys_sigpending(void); } SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); } SYS_IOCTL = 54 // { int sys_ioctl(int fd, u_long com, ... void *data); } SYS_REBOOT = 55 // { int sys_reboot(int opt); } SYS_REVOKE = 56 // { int sys_revoke(const char *path); } SYS_SYMLINK = 57 // { int sys_symlink(const char *path, const char *link); } SYS_READLINK = 58 // { ssize_t sys_readlink(const char *path, char *buf, size_t count); } SYS_EXECVE = 59 // { int sys_execve(const char *path, char * const *argp, char * const *envp); } SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); } SYS_CHROOT = 61 // { int sys_chroot(const char *path); } SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, int flags); } SYS_STATFS = 63 // { int sys_statfs(const char *path, struct statfs *buf); } SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); } SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, struct statfs *buf); } SYS_VFORK = 66 // { int sys_vfork(void); } SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, struct timezone *tzp); } SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, const struct timezone *tzp); } SYS_SETITIMER = 69 // { int sys_setitimer(int which, const struct itimerval *itv, struct itimerval *oitv); } SYS_GETITIMER = 70 // { int sys_getitimer(int which, struct itimerval *itv); } SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); } SYS_KEVENT = 72 // { int sys_kevent(int fd, const struct kevent *changelist, int nchanges, struct kevent *eventlist, int nevents, const struct timespec *timeout); } SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, int prot); } SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, int behav); } SYS_UTIMES = 76 // { int sys_utimes(const char *path, const struct timeval *tptr); } SYS_FUTIMES = 77 // { int sys_futimes(int fd, const struct timeval *tptr); } SYS_MINCORE = 78 // { int sys_mincore(void *addr, size_t len, char *vec); } SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, gid_t *gidset); } SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, const gid_t *gidset); } SYS_GETPGRP = 81 // { int sys_getpgrp(void); } SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, pid_t pgid); } SYS_FUTEX = 83 // { int sys_futex(uint32_t *f, int op, int val, const struct timespec *timeout, uint32_t *g); } SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, const struct timespec *times, int flag); } SYS_FUTIMENS = 85 // { int sys_futimens(int fd, const struct timespec *times); } SYS_KBIND = 86 // { int sys_kbind(const struct __kbind *param, size_t psize, int64_t proc_cookie); } SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, struct timespec *tp); } SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, const struct timespec *tp); } SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, struct timespec *tp); } SYS_DUP2 = 90 // { int sys_dup2(int from, int to); } SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, struct timespec *rmtp); } SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); } SYS_ACCEPT4 = 93 // { int sys_accept4(int s, struct sockaddr *name, socklen_t *anamelen, int flags); } SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, clockid_t clock_id, const struct timespec *tp, void *lock, const int *abort); } SYS_FSYNC = 95 // { int sys_fsync(int fd); } SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); } SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); } SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, socklen_t namelen); } SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); } SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); } SYS_PIPE2 = 101 // { int sys_pipe2(int *fdp, int flags); } SYS_DUP3 = 102 // { int sys_dup3(int from, int to, int flags); } SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); } SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, socklen_t namelen); } SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, const void *val, socklen_t valsize); } SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); } SYS_CHFLAGSAT = 107 // { int sys_chflagsat(int fd, const char *path, u_int flags, int atflags); } SYS_PLEDGE = 108 // { int sys_pledge(const char *promises, const char *execpromises); } SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *mask); } SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *mask); } SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); } SYS_SENDSYSLOG = 112 // { int sys_sendsyslog(const char *buf, size_t nbyte, int flags); } SYS_UNVEIL = 114 // { int sys_unveil(const char *path, const char *permissions); } SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, void *val, socklen_t *avalsize); } SYS_THRKILL = 119 // { int sys_thrkill(pid_t tid, int signum, void *tcb); } SYS_READV = 120 // { ssize_t sys_readv(int fd, const struct iovec *iovp, int iovcnt); } SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, const struct iovec *iovp, int iovcnt); } SYS_KILL = 122 // { int sys_kill(int pid, int signum); } SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); } SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); } SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); } SYS_FLOCK = 131 // { int sys_flock(int fd, int how); } SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); } SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); } SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, int protocol, int *rsv); } SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int sys_rmdir(const char *path); } SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, struct timeval *olddelta); } SYS_GETLOGIN_R = 141 // { int sys_getlogin_r(char *namebuf, u_int namelen); } SYS_SETSID = 147 // { int sys_setsid(void); } SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, int uid, char *arg); } SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); } SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); } SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); } SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, size_t nbyte, int pad, off_t offset); } SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, size_t nbyte, int pad, off_t offset); } SYS_SETGID = 181 // { int sys_setgid(gid_t gid); } SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); } SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); } SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); } SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); } SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); } SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, struct rlimit *rlp); } SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, const struct rlimit *rlp); } SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, int flags, int fd, long pad, off_t pos); } SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, int whence); } SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, off_t length); } SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); } SYS_SYSCTL = 202 // { int sys_sysctl(const int *name, u_int namelen, void *old, size_t *oldlenp, void *new, size_t newlen); } SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); } SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); } SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, size_t len); } SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); } SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); } SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); } SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, int shmflg); } SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); } SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, int inherit); } SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, u_int nfds, int timeout); } SYS_ISSETUGID = 253 // { int sys_issetugid(void); } SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); } SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); } SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); } SYS_PIPE = 263 // { int sys_pipe(int *fdp); } SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); } SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, const struct iovec *iovp, int iovcnt, int pad, off_t offset); } SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, const struct iovec *iovp, int iovcnt, int pad, off_t offset); } SYS_KQUEUE = 269 // { int sys_kqueue(void); } SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); } SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); } SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); } SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, uid_t suid); } SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); } SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, gid_t sgid); } SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, int flags, int fd, long pad, off_t pos); } SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); } SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, struct sigaltstack *oss); } SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); } SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, size_t nsops); } SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, struct stat *sb); } SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, union semun *arg); } SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, struct shmid_ds *buf); } SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, struct msqid_ds *buf); } SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); } SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); } SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, int n); } SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); } SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, siginfo_t *info, const struct timespec *timeout); } SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); } SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, int64_t *oldfreq); } SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); } SYS_GETRTABLE = 311 // { int sys_getrtable(void); } SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, int amode, int flag); } SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, mode_t mode, int flag); } SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, uid_t uid, gid_t gid, int flag); } SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, const char *path2, int flag); } SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, mode_t mode); } SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, mode_t mode); } SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, mode_t mode, dev_t dev); } SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, ... mode_t mode); } SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, char *buf, size_t count); } SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, int tofd, const char *to); } SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, const char *link); } SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, int flag); } SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); } SYS___GET_TCB = 330 // { void *sys___get_tcb(void); } )
{ "pile_set_name": "Github" }
<?php /** * ALIPAY API: alipay.mobile.public.account.query request * * @author auto create * * @since 1.0, 2016-03-31 21:02:46 */ namespace Alipay\Request; class AlipayMobilePublicAccountQueryRequest extends AbstractAlipayRequest { /** * 业务信息:userId,这是个json字段 **/ private $bizContent; public function setBizContent($bizContent) { $this->bizContent = $bizContent; $this->apiParams['biz_content'] = $bizContent; } public function getBizContent() { return $this->bizContent; } }
{ "pile_set_name": "Github" }
/**************************************************************************** * TinySMB * Nintendo Wii/GameCube SMB implementation * * Copyright softdev * Modified by Tantric to utilize NTLM authentication * PathInfo added by rodries * SMB devoptab by scip, rodries * * You will find WireShark (http://www.wireshark.org/) * invaluable for debugging SAMBA implementations. * * Recommended Reading * Implementing CIFS - Christopher R Hertel * http://www.ubiqx.org/cifs/SMB.html * * License: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ****************************************************************************/ #include <asm.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <malloc.h> #include <ctype.h> #include <wchar.h> #include <gccore.h> #include <network.h> #include <processor.h> #include <lwp_threads.h> #include <lwp_objmgr.h> #include <ogc/lwp_watchdog.h> #include <sys/statvfs.h> #include <errno.h> #include <fcntl.h> #include <smb.h> #define IOS_O_NONBLOCK 0x04 #define RECV_TIMEOUT 3000 // in ms #define CONN_TIMEOUT 6000 /** * Field offsets. */ #define SMB_OFFSET_PROTO 0 #define SMB_OFFSET_CMD 4 #define SMB_OFFSET_NTSTATUS 5 #define SMB_OFFSET_ECLASS 5 #define SMB_OFFSET_ECODE 7 #define SMB_OFFSET_FLAGS 9 #define SMB_OFFSET_FLAGS2 10 #define SMB_OFFSET_EXTRA 12 #define SMB_OFFSET_TID 24 #define SMB_OFFSET_PID 26 #define SMB_OFFSET_UID 28 #define SMB_OFFSET_MID 30 #define SMB_HEADER_SIZE 32 /*** SMB Headers are always 32 bytes long ***/ /** * Message / Commands */ #define NBT_SESSISON_MSG 0x00 #define SMB_NEG_PROTOCOL 0x72 #define SMB_SETUP_ANDX 0x73 #define SMB_TREEC_ANDX 0x75 #define NBT_KEEPALIVE_MSG 0x85 #define KEEPALIVE_SIZE 4 /** * SMBTrans2 */ #define SMB_TRANS2 0x32 #define SMB_OPEN2 0 #define SMB_FIND_FIRST2 1 #define SMB_FIND_NEXT2 2 #define SMB_QUERY_FS_INFO 3 #define SMB_QUERY_PATH_INFO 5 #define SMB_SET_PATH_INFO 6 #define SMB_QUERY_FILE_INFO 7 #define SMB_SET_FILE_INFO 8 #define SMB_CREATE_DIR 13 #define SMB_FIND_CLOSE2 0x34 #define SMB_QUERY_FILE_ALL_INFO 0x107 /** * File I/O */ #define SMB_OPEN_ANDX 0x2d #define SMB_WRITE_ANDX 0x2f #define SMB_READ_ANDX 0x2e #define SMB_CLOSE 0x04 /** * SMB_COM */ #define SMB_COM_CREATE_DIRECTORY 0x00 #define SMB_COM_DELETE_DIRECTORY 0x01 #define SMB_COM_DELETE 0x06 #define SMB_COM_RENAME 0x07 #define SMB_COM_QUERY_INFORMATION_DISK 0x80 /** * TRANS2 Offsets */ #define T2_WORD_CNT (SMB_HEADER_SIZE) #define T2_PRM_CNT (T2_WORD_CNT+1) #define T2_DATA_CNT (T2_PRM_CNT+2) #define T2_MAXPRM_CNT (T2_DATA_CNT+2) #define T2_MAXBUFFER (T2_MAXPRM_CNT+2) #define T2_SETUP_CNT (T2_MAXBUFFER+2) #define T2_SPRM_CNT (T2_SETUP_CNT+10) #define T2_SPRM_OFS (T2_SPRM_CNT+2) #define T2_SDATA_CNT (T2_SPRM_OFS+2) #define T2_SDATA_OFS (T2_SDATA_CNT+2) #define T2_SSETUP_CNT (T2_SDATA_OFS+2) #define T2_SUB_CMD (T2_SSETUP_CNT+2) #define T2_BYTE_CNT (T2_SUB_CMD+2) #define SMB_PROTO 0x424d53ff #define SMB_HANDLE_NULL 0xffffffff #define SMB_MAX_NET_READ_SIZE (16*1024) // see smb_recv #define SMB_MAX_NET_WRITE_SIZE 4096 // see smb_sendv #define SMB_MAX_TRANSMIT_SIZE 65472 #define CAP_LARGE_FILES 0x00000008 // 64-bit file sizes and offsets supported #define CAP_UNICODE 0x00000004 // Unicode supported #define CIFS_FLAGS1 0x08 // Paths are caseless #define CIFS_FLAGS2_UNICODE 0x8001 // Server may return long components in paths in the response - use 0x8001 for Unicode support #define CIFS_FLAGS2 0x0001 // Server may return long components in paths in the response - use 0x0001 for ASCII support #define SMB_CONNHANDLES_MAX 8 #define SMB_FILEHANDLES_MAX (32*SMB_CONNHANDLES_MAX) #define SMB_OBJTYPE_HANDLE 7 #define SMB_CHECK_HANDLE(hndl) \ { \ if(((hndl)==SMB_HANDLE_NULL) || (LWP_OBJTYPE(hndl)!=SMB_OBJTYPE_HANDLE)) \ return NULL; \ } /* NBT Session Service Packet Type Codes */ #define SESS_MSG 0x00 #define SESS_REQ 0x81 #define SESS_POS_RESP 0x82 #define SESS_NEG_RESP 0x83 #define SESS_RETARGET 0x84 #define SESS_KEEPALIVE 0x85 struct _smbfile { lwp_node node; u16 sfid; SMBCONN conn; }; /** * NBT/SMB Wrapper */ typedef struct _nbtsmb { u8 msg; /*** NBT Message ***/ u8 length_high; u16 length; /*** Length, excluding NBT ***/ u8 smb[SMB_MAX_TRANSMIT_SIZE+128]; } NBTSMB; /** * Session Information */ typedef struct _smbsession { u16 TID; u16 PID; u16 UID; u16 MID; u32 sKey; u32 capabilities; u32 MaxBuffer; u16 MaxMpx; u16 MaxVCS; u8 challenge[10]; u8 p_domain[64]; s64 timeOffset; u16 count; u16 eos; bool challengeUsed; u8 securityLevel; } SMBSESSION; typedef struct _smbhandle { lwp_obj object; char *user; char *pwd; char *share_name; char *server_name; s32 sck_server; struct sockaddr_in server_addr; bool conn_valid; SMBSESSION session; NBTSMB message; bool unicode; } SMBHANDLE; static u32 smb_dialectcnt = 1; static bool smb_inited = false; static lwp_objinfo smb_handle_objects; static lwp_queue smb_filehandle_queue; static struct _smbfile smb_filehandles[SMB_FILEHANDLES_MAX]; static const char *smb_dialects[] = {"NT LM 0.12",NULL}; extern void ntlm_smb_nt_encrypt(const char *passwd, const u8 * challenge, u8 * answer); // UTF conversion functions size_t utf16_to_utf8(char* dst, char* src, size_t len) { mbstate_t ps; size_t count = 0; int bytes; char buff[MB_CUR_MAX]; int i; unsigned short c; memset(&ps, 0, sizeof(mbstate_t)); while (count < len && *src != '\0') { c = *(src + 1) << 8 | *src; // little endian if (c == 0) break; bytes = wcrtomb(buff, c, &ps); if (bytes < 0) { *dst = '\0'; return -1; } if (bytes > 0) { for (i = 0; i < bytes; i++) { *dst++ = buff[i]; } src += 2; count += 2; } else { break; } } *dst = '\0'; return count; } size_t utf8_to_utf16(char* dst, char* src, size_t len) { mbstate_t ps; wchar_t tempWChar; char *tempChar; int bytes; size_t count = 0; tempChar = (char*) &tempWChar; memset(&ps, 0, sizeof(mbstate_t)); while (count < len - 1 && *src != '\0') { bytes = mbrtowc(&tempWChar, src, MB_CUR_MAX, &ps); if (bytes > 0) { *dst = tempChar[3]; dst++; *dst = tempChar[2]; dst++; src += bytes; count += 2; } else if (bytes == 0) { break; } else { *dst = '\0'; dst++; *dst = '\0'; return -1; } } *dst = '\0'; dst++; *dst = '\0'; return count; } /** * SMB Endian aware supporting functions * * SMB always uses Intel Little-Endian values, so htons etc are * of little or no use :) ... Thanks M$ */ /*** get unsigned char ***/ static __inline__ u8 getUChar(u8 *buffer,u32 offset) { return (u8)buffer[offset]; } /*** set unsigned char ***/ static __inline__ void setUChar(u8 *buffer,u32 offset,u8 value) { buffer[offset] = value; } /*** get signed short ***/ static __inline__ s16 getShort(u8 *buffer,u32 offset) { return (s16)((buffer[offset+1]<<8)|(buffer[offset])); } /*** get unsigned short ***/ static __inline__ u16 getUShort(u8 *buffer,u32 offset) { return (u16)((buffer[offset+1]<<8)|(buffer[offset])); } /*** set unsigned short ***/ static __inline__ void setUShort(u8 *buffer,u32 offset,u16 value) { buffer[offset] = (value&0xff); buffer[offset+1] = ((value&0xff00)>>8); } /*** get unsigned int ***/ static __inline__ u32 getUInt(u8 *buffer,u32 offset) { return (u32)((buffer[offset+3]<<24)|(buffer[offset+2]<<16)|(buffer[offset+1]<<8)|buffer[offset]); } /*** set unsigned int ***/ static __inline__ void setUInt(u8 *buffer,u32 offset,u32 value) { buffer[offset] = (value&0xff); buffer[offset+1] = ((value&0xff00)>>8); buffer[offset+2] = ((value&0xff0000)>>16); buffer[offset+3] = ((value&0xff000000)>>24); } /*** get unsigned long long ***/ static __inline__ u64 getULongLong(u8 *buffer,u32 offset) { return (u64)(getUInt(buffer, offset) | (u64)getUInt(buffer, offset+4) << 32); } static __inline__ SMBHANDLE* __smb_handle_open(SMBCONN smbhndl) { u32 level; SMBHANDLE *handle; SMB_CHECK_HANDLE(smbhndl); _CPU_ISR_Disable(level); handle = (SMBHANDLE*)__lwp_objmgr_getnoprotection(&smb_handle_objects,LWP_OBJMASKID(smbhndl)); _CPU_ISR_Restore(level); return handle; } static __inline__ void __smb_handle_free(SMBHANDLE *handle) { u32 level; _CPU_ISR_Disable(level); __lwp_objmgr_close(&smb_handle_objects,&handle->object); __lwp_objmgr_free(&smb_handle_objects,&handle->object); _CPU_ISR_Restore(level); } static void __smb_init() { smb_inited = true; __lwp_objmgr_initinfo(&smb_handle_objects,SMB_CONNHANDLES_MAX,sizeof(SMBHANDLE)); __lwp_queue_initialize(&smb_filehandle_queue,smb_filehandles,SMB_FILEHANDLES_MAX,sizeof(struct _smbfile)); } static SMBHANDLE* __smb_allocate_handle() { u32 level; SMBHANDLE *handle; _CPU_ISR_Disable(level); handle = (SMBHANDLE*)__lwp_objmgr_allocate(&smb_handle_objects); if(handle) { handle->user = NULL; handle->pwd = NULL; handle->server_name = NULL; handle->share_name = NULL; handle->sck_server = INVALID_SOCKET; handle->conn_valid = false; __lwp_objmgr_open(&smb_handle_objects,&handle->object); } _CPU_ISR_Restore(level); return handle; } static void __smb_free_handle(SMBHANDLE *handle) { if(handle->user) free(handle->user); if(handle->pwd) free(handle->pwd); if(handle->server_name) free(handle->server_name); if(handle->share_name) free(handle->share_name); handle->user = NULL; handle->pwd = NULL; handle->server_name = NULL; handle->share_name = NULL; handle->sck_server = INVALID_SOCKET; __smb_handle_free(handle); } static void MakeSMBHeader(u8 command,u8 flags,u16 flags2,SMBHANDLE *handle) { u8 *ptr = handle->message.smb; NBTSMB *nbt = &handle->message; SMBSESSION *sess = &handle->session; memset(nbt,0,sizeof(NBTSMB)); setUInt(ptr,SMB_OFFSET_PROTO,SMB_PROTO); setUChar(ptr,SMB_OFFSET_CMD,command); setUChar(ptr,SMB_OFFSET_FLAGS,flags); setUShort(ptr,SMB_OFFSET_FLAGS2,flags2); setUShort(ptr,SMB_OFFSET_TID,sess->TID); setUShort(ptr,SMB_OFFSET_PID,sess->PID); setUShort(ptr,SMB_OFFSET_UID,sess->UID); setUShort(ptr,SMB_OFFSET_MID,sess->MID); ptr[SMB_HEADER_SIZE] = 0; } /** * MakeTRANS2Hdr */ static void MakeTRANS2Header(u8 subcommand,SMBHANDLE *handle) { u8 *ptr = handle->message.smb; setUChar(ptr, T2_WORD_CNT, 15); setUShort(ptr, T2_MAXPRM_CNT, 10); setUShort(ptr, T2_MAXBUFFER, 16384); setUChar(ptr, T2_SSETUP_CNT, 1); setUShort(ptr, T2_SUB_CMD, subcommand); } /** * smb_send * * blocking call with timeout * will return when ALL data has been sent. Number of bytes sent is returned. * OR timeout. Timeout will return -1 * OR network error. -ve value will be returned */ static inline s32 smb_send(s32 s,const void *data,s32 size) { u64 t1,t2; s32 ret, len = size, nextsend; t1=ticks_to_millisecs(gettime()); while(len>0) { nextsend=len; if(nextsend>SMB_MAX_NET_WRITE_SIZE) nextsend=SMB_MAX_NET_WRITE_SIZE; //optimized value ret=net_send(s,data,nextsend,0); if(ret==-EAGAIN) { t2=ticks_to_millisecs(gettime()); if( (t2 - t1) > RECV_TIMEOUT) { return -1; // timeout } usleep(100); // allow system to perform work. Stabilizes system continue; } else if(ret<0) { return ret; // an error occurred } else { data+=ret; len-=ret; if(len==0) return size; t1=ticks_to_millisecs(gettime()); } usleep(100); } return size; } /** * smb_recv * * blocking call with timeout * will return when ANY data has been read from socket. Number of bytes read is returned. * OR timeout. Timeout will return -1 * OR network error. -ve value will be returned */ static s32 smb_recv(s32 s,void *mem,s32 len) { s32 ret,read,readtotal=0; u64 t1,t2; t1=ticks_to_millisecs(gettime()); while(len > 0) { read=len; if(read>SMB_MAX_NET_READ_SIZE) read=SMB_MAX_NET_READ_SIZE; // optimized value ret=net_recv(s,mem+readtotal,read,0); if(ret>0) { readtotal+=ret; len-=ret; if(len==0) return readtotal; } else { if(ret!=-EAGAIN) return ret; t2=ticks_to_millisecs(gettime()); if( (t2 - t1) > RECV_TIMEOUT) return -1; } usleep(1000); } return readtotal; } static void clear_network(s32 s,u8 *ptr) { u64 t1,t2; t1=ticks_to_millisecs(gettime()); while(true) { net_recv(s,ptr,SMB_MAX_NET_READ_SIZE,0); t2=ticks_to_millisecs(gettime()); if( (t2 - t1) > 600) return; usleep(100); } } /** * SMBCheck * * Do very basic checking on the return SMB * Read <readlen> bytes * if <readlen>==0 then read a single SMB packet * discard any non NBT_SESSISON_MSG packets along the way. */ static s32 SMBCheck(u8 command,SMBHANDLE *handle) { s32 ret; u8 *ptr = handle->message.smb; NBTSMB *nbt = &handle->message; u32 readlen; u64 t1,t2; if(handle->sck_server == INVALID_SOCKET) return SMB_ERROR; memset(nbt,0xFF,sizeof(NBTSMB)); //NBT_SESSISON_MSG is 0x00 so fill mem with 0xFF t1=ticks_to_millisecs(gettime()); /*keep going till we get a NBT session message*/ do{ ret=smb_recv(handle->sck_server, (u8*)nbt, 4); if(ret!=4) goto failed; if(nbt->msg!=NBT_SESSISON_MSG) { readlen=(u32)((nbt->length_high<<16)|nbt->length); if(readlen>0) { t1=ticks_to_millisecs(gettime()); smb_recv(handle->sck_server, ptr, readlen); //clear unexpected NBT message } } t2=ticks_to_millisecs(gettime()); if( (t2 - t1) > RECV_TIMEOUT * 2) goto failed; } while(nbt->msg!=NBT_SESSISON_MSG); /* obtain required length from NBT header if readlen==0*/ readlen=(u32)((nbt->length_high<<16)|nbt->length); // Get server message block ret=smb_recv(handle->sck_server, ptr, readlen); if(readlen!=ret) goto failed; /*** Do basic SMB Header checks ***/ ret = getUInt(ptr,SMB_OFFSET_PROTO); if(ret!=SMB_PROTO) goto failed; ret = getUChar(ptr, SMB_OFFSET_CMD); if(ret!=command) goto failed; ret = getUInt(ptr,SMB_OFFSET_NTSTATUS); if(ret) goto failed; return SMB_SUCCESS; failed: clear_network(handle->sck_server,ptr); return SMB_ERROR; } /** * SMB_SetupAndX * * Setup the SMB session, including authentication with the * magic 'NTLM Response' */ static s32 SMB_SetupAndX(SMBHANDLE *handle) { s32 pos; s32 bcpos; s32 i, ret; u8 *ptr = handle->message.smb; SMBSESSION *sess = &handle->session; char pwd[30], ntRespData[24]; if(handle->sck_server == INVALID_SOCKET) return SMB_ERROR; MakeSMBHeader(SMB_SETUP_ANDX,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; setUChar(ptr,pos,13); pos++; /*** Word Count ***/ setUChar(ptr,pos,0xff); pos++; /*** Next AndX ***/ setUChar(ptr,pos,0); pos++; /*** Reserved ***/ pos += 2; /*** Next AndX Offset ***/ setUShort(ptr,pos,sess->MaxBuffer); pos += 2; setUShort(ptr,pos,sess->MaxMpx); pos += 2; setUShort(ptr,pos,sess->MaxVCS); pos += 2; setUInt(ptr,pos,sess->sKey); pos += 4; setUShort(ptr,pos,24); /*** Password length (case-insensitive) ***/ pos += 2; setUShort(ptr,pos,24); /*** Password length (case-sensitive) ***/ pos += 2; setUInt(ptr,pos,0); pos += 4; /*** Reserved ***/ setUInt(ptr,pos,sess->capabilities); pos += 4; /*** Capabilities ***/ bcpos = pos; pos += 2; /*** Byte count ***/ /*** The magic 'NTLM Response' ***/ strcpy(pwd, handle->pwd); if (sess->challengeUsed) ntlm_smb_nt_encrypt((const char *) pwd, (const u8 *) sess->challenge, (u8*) ntRespData); /*** Build information ***/ memset(&ptr[pos],0,24); pos += 24; memcpy(&ptr[pos],ntRespData,24); pos += 24; pos++; /*** Account ***/ strcpy(pwd, handle->user); for(i=0;i<strlen(pwd);i++) pwd[i] = toupper((int)pwd[i]); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],pwd,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],pwd,strlen(pwd)); pos += strlen(pwd)+1; } /*** Primary Domain ***/ if(handle->user[0]=='\0') sess->p_domain[0] = '\0'; if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],(char*)sess->p_domain,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],sess->p_domain,strlen((const char*)sess->p_domain)); pos += strlen((const char*)sess->p_domain)+1; } /*** Native OS ***/ strcpy(pwd,"Unix (libOGC)"); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],pwd,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],pwd,strlen(pwd)); pos += strlen(pwd)+1; } /*** Native LAN Manager ***/ strcpy(pwd,"Nintendo Wii"); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],pwd,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],pwd,strlen(pwd)); pos += strlen (pwd)+1; } /*** Update byte count ***/ setUShort(ptr,bcpos,((pos-bcpos)-2)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons (pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret<=0) return SMB_ERROR; if((ret=SMBCheck(SMB_SETUP_ANDX,handle))==SMB_SUCCESS) { /*** Collect UID ***/ sess->UID = getUShort(handle->message.smb,SMB_OFFSET_UID); return SMB_SUCCESS; } return ret; } /** * SMB_TreeAndX * * Finally, net_connect to the remote share */ static s32 SMB_TreeAndX(SMBHANDLE *handle) { s32 pos, bcpos, ret; char path[512]; u8 *ptr = handle->message.smb; SMBSESSION *sess = &handle->session; if(handle->sck_server == INVALID_SOCKET) return SMB_ERROR; MakeSMBHeader(SMB_TREEC_ANDX,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; setUChar(ptr,pos,4); pos++; /*** Word Count ***/ setUChar(ptr,pos,0xff); pos++; /*** Next AndX ***/ pos++; /*** Reserved ***/ pos += 2; /*** Next AndX Offset ***/ pos += 2; /*** Flags ***/ setUShort(ptr,pos,1); pos += 2; /*** Password Length ***/ bcpos = pos; pos += 2; pos++; /*** NULL Password ***/ /*** Build server share path ***/ strcpy ((char*)path, "\\\\"); strcat ((char*)path, handle->server_name); strcat ((char*)path, "\\"); strcat ((char*)path, handle->share_name); for(ret=0;ret<strlen((const char*)path);ret++) path[ret] = (char)toupper((int)path[ret]); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],path,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],path,strlen((const char*)path)); pos += strlen((const char*)path)+1; } /*** Service ***/ strcpy((char*)path,"?????"); memcpy(&ptr[pos],path,strlen((const char*)path)); pos += strlen((const char*)path)+1; /*** Update byte count ***/ setUShort(ptr,bcpos,(pos-bcpos)-2); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons (pos); pos += 4; ret = smb_send(handle->sck_server,(char *)&handle->message,pos); if(ret<=0) return SMB_ERROR; if((ret=SMBCheck(SMB_TREEC_ANDX,handle))==SMB_SUCCESS) { /*** Collect Tree ID ***/ sess->TID = getUShort(handle->message.smb,SMB_OFFSET_TID); return SMB_SUCCESS; } return ret; } /** * SMB_NegotiateProtocol * * The only protocol we admit to is 'NT LM 0.12' */ static s32 SMB_NegotiateProtocol(const char *dialects[],int dialectc,SMBHANDLE *handle) { u8 *ptr; s32 pos; s32 bcnt,i,j; s32 ret,len; u32 serverMaxBuffer; SMBSESSION *sess; if(!handle || !dialects || dialectc<=0) return SMB_ERROR; if(handle->sck_server == INVALID_SOCKET) return SMB_ERROR; /*** Clear session variables ***/ sess = &handle->session; memset(sess,0,sizeof(SMBSESSION)); sess->PID = 0xdead; sess->MID = 1; sess->capabilities = 0; MakeSMBHeader(SMB_NEG_PROTOCOL,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE+3; ptr = handle->message.smb; for(i=0,bcnt=0;i<dialectc;i++) { len = strlen(dialects[i])+1; ptr[pos++] = '\x02'; memcpy(&ptr[pos],dialects[i],len); pos += len; bcnt += len+1; } /*** Update byte count ***/ setUShort(ptr,(SMB_HEADER_SIZE+1),bcnt); /*** Set NBT information ***/ handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret<=0) return SMB_ERROR; /*** Check response ***/ if((ret=SMBCheck(SMB_NEG_PROTOCOL,handle))==SMB_SUCCESS) { pos = SMB_HEADER_SIZE; ptr = handle->message.smb; /*** Collect information ***/ if(getUChar(ptr,pos)!=17) return SMB_PROTO_FAIL; // UCHAR WordCount; Count of parameter words = 17 pos++; if(getUShort(ptr,pos)!=0) return SMB_PROTO_FAIL; // USHORT DialectIndex; Index of selected dialect - should always be 0 since we only supplied 1! pos += 2; if(getUChar(ptr,pos) & 1) { // user level security sess->securityLevel = 1; } else { // share level security - can we skip SetupAndX? If so, we would need to specify the password in TreeAndX sess->securityLevel = 0; } pos++; sess->MaxMpx = getUShort(ptr, pos); //USHORT MaxMpxCount; Max pending outstanding requests pos += 2; sess->MaxVCS = getUShort(ptr, pos); //USHORT MaxNumberVcs; Max VCs between client and server pos += 2; serverMaxBuffer = getUInt(ptr, pos); //ULONG MaxBufferSize; Max transmit buffer size if(serverMaxBuffer>SMB_MAX_TRANSMIT_SIZE) sess->MaxBuffer = SMB_MAX_TRANSMIT_SIZE; else sess->MaxBuffer = serverMaxBuffer; pos += 4; pos += 4; //ULONG MaxRawSize; Maximum raw buffer size sess->sKey = getUInt(ptr,pos); pos += 4; u32 servcap = getUInt(ptr,pos); pos += 4; //ULONG Capabilities; Server capabilities pos += 4; //ULONG SystemTimeLow; System (UTC) time of the server (low). pos += 4; //ULONG SystemTimeHigh; System (UTC) time of the server (high). sess->timeOffset = getShort(ptr,pos) * 600000000LL; pos += 2; //SHORT ServerTimeZone; Time zone of server (minutes from UTC) //UCHAR EncryptionKeyLength - 0 or 8 if(getUChar(ptr,pos)!=8) { if (getUChar(ptr,pos)!=0) { return SMB_BAD_KEYLEN; } else { // Challenge key not used sess->challengeUsed = false; } } else { sess->challengeUsed = true; } pos++; getUShort(ptr,pos); // byte count if (sess->challengeUsed) { /*** Copy challenge key ***/ pos += 2; memcpy(&sess->challenge,&ptr[pos],8); } /*** Primary domain ***/ pos += 8; i = j = 0; while(ptr[pos+j]!=0) { sess->p_domain[i] = ptr[pos+j]; j += 2; i++; } sess->p_domain[i] = '\0'; // setup capabilities //if(servcap & CAP_LARGE_FILES) // sess->capabilities |= CAP_LARGE_FILES; if(servcap & CAP_UNICODE) { sess->capabilities |= CAP_UNICODE; handle->unicode = true; } return SMB_SUCCESS; } return ret; } static s32 do_netconnect(SMBHANDLE *handle) { u32 set = 1; s32 ret; s32 sock; u64 t1,t2; handle->sck_server = INVALID_SOCKET; /*** Create the global net_socket ***/ sock = net_socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if(sock==INVALID_SOCKET) return -1; // Switch off Nagle with TCP_NODELAY net_setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,&set,sizeof(set)); // create non blocking socket ret = net_ioctl(sock, FIONBIO, &set); if (ret < 0) { net_close(sock); return ret; } t1=ticks_to_millisecs(gettime()); while(1) { ret = net_connect(sock,(struct sockaddr*)&handle->server_addr,sizeof(handle->server_addr)); if(ret==-EISCONN) break; t2=ticks_to_millisecs(gettime()); usleep(1000); if((t2-t1) > CONN_TIMEOUT) break; // usually not more than 90ms } if(ret!=-EISCONN) { net_close(sock); return -1; } handle->sck_server = sock; return 0; } static s32 do_smbconnect(SMBHANDLE *handle) { s32 ret; if(handle->sck_server == INVALID_SOCKET) return -1; ret = SMB_NegotiateProtocol(smb_dialects,smb_dialectcnt,handle); if(ret!=SMB_SUCCESS) { net_close(handle->sck_server); handle->sck_server = INVALID_SOCKET; return -1; } ret = SMB_SetupAndX(handle); if(ret!=SMB_SUCCESS) { net_close(handle->sck_server); handle->sck_server = INVALID_SOCKET; return -1; } ret = SMB_TreeAndX(handle); if(ret!=SMB_SUCCESS) { net_close(handle->sck_server); handle->sck_server = INVALID_SOCKET; return -1; } handle->conn_valid = true; return 0; } /**************************************************************************** * Create an NBT SESSION REQUEST message. ****************************************************************************/ static int MakeSessReq(unsigned char *bufr, unsigned char *Called, unsigned char *Calling) { // Write the header. bufr[0] = SESS_REQ; bufr[1] = 0; bufr[2] = 0; bufr[3] = 68; // 2x34 bytes in length. // Copy the Called and Calling names into the buffer. (void) memcpy(&bufr[4], Called, 34); (void) memcpy(&bufr[38], Calling, 34); // Return the total message length. return 72; } static unsigned char *L1_Encode(unsigned char *dst, const unsigned char *name, const unsigned char pad, const unsigned char sfx) { int i = 0; int j = 0; int k = 0; while (('\0' != name[i]) && (i < 15)) { k = toupper(name[i++]); dst[j++] = 'A' + ((k & 0xF0) >> 4); dst[j++] = 'A' + (k & 0x0F); } i = 'A' + ((pad & 0xF0) >> 4); k = 'A' + (pad & 0x0F); while (j < 30) { dst[j++] = i; dst[j++] = k; } dst[30] = 'A' + ((sfx & 0xF0) >> 4); dst[31] = 'A' + (sfx & 0x0F); dst[32] = '\0'; return (dst); } static int L2_Encode(unsigned char *dst, const unsigned char *name, const unsigned char pad, const unsigned char sfx, const unsigned char *scope) { int lenpos; int i; int j; if (NULL == L1_Encode(&dst[1], name, pad, sfx)) return (-1); dst[0] = 0x20; lenpos = 33; if ('\0' != *scope) { do { for (i = 0, j = (lenpos + 1); ('.' != scope[i]) && ('\0' != scope[i]); i++, j++) dst[j] = toupper(scope[i]); dst[lenpos] = (unsigned char) i; lenpos += i + 1; scope += i; } while ('.' == *(scope++)); dst[lenpos] = '\0'; } return (lenpos + 1); } /**************************************************************************** * Send an NBT SESSION REQUEST over the TCP connection, then wait for a reply. ****************************************************************************/ static s32 SMB_RequestNBTSession(SMBHANDLE *handle) { unsigned char Called[34]; unsigned char Calling[34]; unsigned char bufr[128]; int result; if(handle->sck_server == INVALID_SOCKET) return -1; L2_Encode(Called, (const unsigned char*) "*SMBSERVER", 0x20, 0x20, (const unsigned char*) ""); L2_Encode(Calling, (const unsigned char*) "SMBCLIENT", 0x20, 0x00, (const unsigned char*) ""); // Create the NBT Session Request message. result = MakeSessReq(bufr, Called, Calling); //Send the NBT Session Request message. result = smb_send(handle->sck_server, bufr, result); if (result < 0) { // Error sending Session Request message return -1; } // Now wait for and handle the reply (2 seconds). result = smb_recv(handle->sck_server, bufr, 128); if (result <= 0) { // Timeout waiting for NBT Session Response return -1; } switch (*bufr) { case SESS_POS_RESP: // Positive Session Response return 0; case SESS_NEG_RESP: // Negative Session Response return -1; case SESS_RETARGET: // Retarget Session Response return -1; default: // Unexpected Session Response return -1; } } /**************************************************************************** * Primary setup, logon and connection all in one :) ****************************************************************************/ s32 SMB_Connect(SMBCONN *smbhndl, const char *user, const char *password, const char *share, const char *server) { s32 ret = 0; SMBHANDLE *handle; struct in_addr val; *smbhndl = SMB_HANDLE_NULL; if(!user || !password || !share || !server || strlen(user) > 20 || strlen(password) > 14 || strlen(share) > 80 || strlen(server) > 80) { return SMB_BAD_LOGINDATA; } if(!smb_inited) { u32 level; _CPU_ISR_Disable(level); __smb_init(); _CPU_ISR_Restore(level); } handle = __smb_allocate_handle(); if(!handle) return SMB_ERROR; handle->user = strdup(user); handle->pwd = strdup(password); handle->server_name = strdup(server); handle->share_name = strdup(share); handle->server_addr.sin_family = AF_INET; handle->server_addr.sin_port = htons(445); handle->unicode = false; if(strlen(server) < 16 && inet_aton(server, &val)) { handle->server_addr.sin_addr.s_addr = val.s_addr; } else // might be a hostname { #ifdef HW_RVL struct hostent *hp = net_gethostbyname(server); if (!hp || !(hp->h_addrtype == PF_INET)) ret = SMB_BAD_LOGINDATA; else memcpy((char *)&handle->server_addr.sin_addr.s_addr, hp->h_addr_list[0], hp->h_length); #else __smb_free_handle(handle); return SMB_ERROR; #endif } *smbhndl =(SMBCONN)(LWP_OBJMASKTYPE(SMB_OBJTYPE_HANDLE)|LWP_OBJMASKID(handle->object.id)); if(ret==0) { ret = do_netconnect(handle); if(ret==0) ret = do_smbconnect(handle); if(ret!=0) { // try port 139 handle->server_addr.sin_port = htons(139); ret = do_netconnect(handle); if(ret==0) ret = SMB_RequestNBTSession(handle); if(ret==0) ret = do_smbconnect(handle); } } if(ret!=0) { __smb_free_handle(handle); return SMB_ERROR; } return SMB_SUCCESS; } /**************************************************************************** * SMB_Destroy ****************************************************************************/ void SMB_Close(SMBCONN smbhndl) { SMBHANDLE *handle = __smb_handle_open(smbhndl); if(!handle) return; if(handle->sck_server!=INVALID_SOCKET) net_close(handle->sck_server); __smb_free_handle(handle); } s32 SMB_Reconnect(SMBCONN *_smbhndl, bool test_conn) { s32 ret = SMB_SUCCESS; SMBCONN smbhndl = *_smbhndl; SMBHANDLE *handle = __smb_handle_open(smbhndl); if(!handle) return SMB_ERROR; // we have no handle, so we can't reconnect if(handle->conn_valid && test_conn) { SMBDIRENTRY dentry; if(SMB_PathInfo("\\", &dentry, smbhndl)==SMB_SUCCESS) return SMB_SUCCESS; // no need to reconnect handle->conn_valid = false; // else connection is invalid } if(!handle->conn_valid) { // shut down connection if(handle->sck_server!=INVALID_SOCKET) { net_close(handle->sck_server); handle->sck_server = INVALID_SOCKET; } // reconnect if(handle->server_addr.sin_port > 0) { ret = do_netconnect(handle); if(ret==0 && handle->server_addr.sin_port == htons(139)) ret = SMB_RequestNBTSession(handle); if(ret==0) ret = do_smbconnect(handle); } else // initial connection { handle->server_addr.sin_port = htons(445); ret = do_netconnect(handle); if(ret==0) ret = do_smbconnect(handle); if(ret != 0) { // try port 139 handle->server_addr.sin_port = htons(139); ret = do_netconnect(handle); if(ret==0) ret = SMB_RequestNBTSession(handle); if(ret==0) ret = do_smbconnect(handle); } if(ret != 0) handle->server_addr.sin_port = 0; } } return ret; } SMBFILE SMB_OpenFile(const char *filename, u16 access, u16 creation,SMBCONN smbhndl) { s32 pos; s32 bpos,ret; u8 *ptr; struct _smbfile *fid = NULL; SMBHANDLE *handle; char realfile[512]; if(filename == NULL) return NULL; if(SMB_Reconnect(&smbhndl,true)!=SMB_SUCCESS) return NULL; handle = __smb_handle_open(smbhndl); if(!handle) return NULL; MakeSMBHeader(SMB_OPEN_ANDX,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 15); pos++; /*** Word Count ***/ setUChar(ptr, pos, 0xff); pos++; /*** AndXCommand 0xFF = None ***/ setUChar(ptr, pos, 0); pos++; /*** AndX Reserved must be 0 ***/ pos += 2; /*** Next AndX Offset to next Command ***/ pos += 2; /*** Flags ***/ setUShort(ptr, pos, access); pos += 2; /*** Access mode ***/ setUShort(ptr, pos, 0x6); pos += 2; /*** Type of file ***/ pos += 2; /*** File Attributes ***/ pos += 4; /*** File time - don't care - let server decide ***/ setUShort(ptr, pos, creation); pos += 2; /*** Creation flags ***/ pos += 4; /*** Allocation size ***/ setUInt(ptr, pos, 0); pos += 4; /*** Reserved[0] must be 0 ***/ setUInt(ptr, pos, 0); pos += 4; /*** Reserved[1] must be 0 ***/ pos += 2; /*** Byte Count ***/ bpos = pos; setUChar(ptr, pos, 0x04); /** Bufferformat **/ pos++; realfile[0]='\0'; if (filename[0] != '\\') strcpy(realfile,"\\"); strcat(realfile,filename); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],realfile,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],realfile,strlen(realfile)); pos += strlen(realfile)+1; } setUShort(ptr,(bpos-2),(pos-bpos)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret<0) goto failed; if(SMBCheck(SMB_OPEN_ANDX,handle)==SMB_SUCCESS) { /*** Check file handle ***/ fid = (struct _smbfile*)__lwp_queue_get(&smb_filehandle_queue); if(fid) { fid->conn = smbhndl; fid->sfid = getUShort(handle->message.smb,(SMB_HEADER_SIZE+5)); } } return (SMBFILE)fid; failed: handle->conn_valid = false; return NULL; } /** * SMB_CloseFile */ void SMB_CloseFile(SMBFILE sfid) { u8 *ptr; s32 pos, ret; SMBHANDLE *handle; struct _smbfile *fid = (struct _smbfile*)sfid; if(!fid) return; handle = __smb_handle_open(fid->conn); if(!handle) return; MakeSMBHeader(SMB_CLOSE,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 3); pos++; /** Word Count **/ setUShort(ptr, pos, fid->sfid); pos += 2; setUInt(ptr, pos, 0xffffffff); pos += 4; /*** Last Write ***/ pos += 2; /*** Byte Count ***/ handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret<0) handle->conn_valid = false; else SMBCheck(SMB_CLOSE,handle); __lwp_queue_append(&smb_filehandle_queue,&fid->node); } /** * SMB_CreateDirectory */ s32 SMB_CreateDirectory(const char *dirname, SMBCONN smbhndl) { s32 pos; s32 bpos,ret; u8 *ptr; SMBHANDLE *handle; char realfile[512]; if(dirname == NULL) return -1; if(SMB_Reconnect(&smbhndl,true)!=SMB_SUCCESS) return -1; handle = __smb_handle_open(smbhndl); if(!handle) return -1; MakeSMBHeader(SMB_COM_CREATE_DIRECTORY,CIFS_FLAGS1, handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 0); pos++; /*** Word Count ***/ pos += 2; /*** Byte Count ***/ bpos = pos; setUChar(ptr, pos, 0x04); /*** Buffer format ***/ pos++; realfile[0]='\0'; if (dirname[0] != '\\') strcpy(realfile,"\\"); strcat(realfile,dirname); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],realfile,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],realfile,strlen(realfile)); pos += strlen(realfile)+1; } setUShort(ptr,(bpos-2),(pos-bpos)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret < 0) goto failed; ret = SMBCheck(SMB_COM_CREATE_DIRECTORY,handle); return ret; failed: return ret; } /** * SMB_DeleteDirectory */ s32 SMB_DeleteDirectory(const char *dirname, SMBCONN smbhndl) { s32 pos; s32 bpos,ret; u8 *ptr; SMBHANDLE *handle; char realfile[512]; if(dirname == NULL) return -1; if(SMB_Reconnect(&smbhndl,true)!=SMB_SUCCESS) return -1; handle = __smb_handle_open(smbhndl); if(!handle) return -1; MakeSMBHeader(SMB_COM_DELETE_DIRECTORY,CIFS_FLAGS1, handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 0); pos++; /*** Word Count ***/ pos += 2; /*** Byte Count ***/ bpos = pos; setUChar(ptr, pos, 0x04); /** Bufferformat **/ pos++; realfile[0]='\0'; if (dirname[0] != '\\') strcpy(realfile,"\\"); strcat(realfile,dirname); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],realfile,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],realfile,strlen(realfile)); pos += strlen(realfile)+1; } setUShort(ptr,(bpos-2),(pos-bpos)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret < 0) goto failed; ret = SMBCheck(SMB_COM_DELETE_DIRECTORY,handle); return ret; failed: return ret; } /** * SMB_DeleteFile */ s32 SMB_DeleteFile(const char *filename, SMBCONN smbhndl) { s32 pos; s32 bpos,ret; u8 *ptr; SMBHANDLE *handle; char realfile[512]; if(filename == NULL) return -1; if(SMB_Reconnect(&smbhndl,true)!=SMB_SUCCESS) return -1; handle = __smb_handle_open(smbhndl); if(!handle) return -1; MakeSMBHeader(SMB_COM_DELETE,CIFS_FLAGS1, handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 1); pos++; /*** Word Count ***/ setUShort(ptr, pos, SMB_SRCH_HIDDEN); pos += 2; /*** SearchAttributes ***/ pos += 2; /*** Byte Count ***/ bpos = pos; setUChar(ptr, pos, 0x04); /** Bufferformat **/ pos++; realfile[0]='\0'; if (filename[0] != '\\') strcpy(realfile,"\\"); strcat(realfile,filename); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],realfile,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],realfile,strlen(realfile)); pos += strlen(realfile)+1; } setUShort(ptr,(bpos-2),(pos-bpos)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret < 0) goto failed; ret = SMBCheck(SMB_COM_DELETE,handle); return ret; failed: return ret; } /** * SMB_Rename */ s32 SMB_Rename(const char *filename, const char * newfilename, SMBCONN smbhndl) { s32 pos; s32 bpos,ret; u8 *ptr; SMBHANDLE *handle; char realfile[512]; char newrealfile[512]; if(filename == NULL || newfilename == NULL) return -1; if(SMB_Reconnect(&smbhndl,true)!=SMB_SUCCESS) return -1; handle = __smb_handle_open(smbhndl); if(!handle) return -1; MakeSMBHeader(SMB_COM_RENAME,CIFS_FLAGS1, handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 1); pos++; /*** Word Count ***/ setUShort(ptr, pos, SMB_SRCH_HIDDEN); pos += 2; /*** SearchAttributes ***/ pos += 2; /*** Byte Count ***/ bpos = pos; setUChar(ptr, pos, 0x04); /** Bufferformat **/ pos++; realfile[0]='\0'; if (filename[0] != '\\') strcpy(realfile,"\\"); strcat(realfile,filename); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],realfile,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],realfile,strlen(realfile)); pos += strlen(realfile)+1; } pos++; setUChar(ptr, pos, 0x04); /** Bufferformat **/ pos++; newrealfile[0]='\0'; if (newfilename[0] != '\\') strcpy(newrealfile,"\\"); strcat(newrealfile,newfilename); if(handle->unicode) { pos += utf8_to_utf16((char*)&ptr[pos],newrealfile,SMB_MAXPATH-2); pos += 2; } else { memcpy(&ptr[pos],newrealfile,strlen(newrealfile)); pos += strlen(newrealfile)+1; } setUShort(ptr,(bpos-2),(pos-bpos)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret < 0) goto failed; ret = SMBCheck(SMB_COM_RENAME,handle); return ret; failed: return ret; } /** * SMB_DiskInformation */ s32 SMB_DiskInformation(struct statvfs *buf, SMBCONN smbhndl) { s32 pos; s32 ret; u16 TotalUnits, BlocksPerUnit, BlockSize, FreeUnits; u8 *ptr; SMBHANDLE *handle; if(SMB_Reconnect(&smbhndl,true)!=SMB_SUCCESS) return -1; handle = __smb_handle_open(smbhndl); if(!handle) return -1; MakeSMBHeader(SMB_COM_QUERY_INFORMATION_DISK,CIFS_FLAGS1, handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 0); pos++; /*** Word Count ***/ setUShort(ptr, pos, 0); pos += 2; /*** Byte Count ***/ handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret < 0) goto failed; if((ret=SMBCheck(SMB_COM_QUERY_INFORMATION_DISK, handle))==SMB_SUCCESS) { ptr = handle->message.smb; /** Read the received data ***/ /** WordCount **/ s32 recv_pos = 1; /** TotalUnits **/ TotalUnits = getUShort(ptr,(SMB_HEADER_SIZE+recv_pos)); recv_pos += 2; /** BlocksPerUnit **/ BlocksPerUnit = getUShort(ptr,(SMB_HEADER_SIZE+recv_pos)); recv_pos += 2; /** BlockSize **/ BlockSize = getUShort(ptr,(SMB_HEADER_SIZE+recv_pos)); recv_pos += 2; /** FreeUnits **/ FreeUnits = getUShort(ptr,(SMB_HEADER_SIZE+recv_pos)); recv_pos += 2; buf->f_bsize = (unsigned long) BlockSize; // File system block size. buf->f_frsize = (unsigned long) BlockSize; // Fundamental file system block size. buf->f_blocks = (fsblkcnt_t) (TotalUnits*BlocksPerUnit); // Total number of blocks on file system in units of f_frsize. buf->f_bfree = (fsblkcnt_t) (FreeUnits*BlocksPerUnit); // Total number of free blocks. buf->f_bavail = 0; // Number of free blocks available to non-privileged process. buf->f_files = 0; // Total number of file serial numbers. buf->f_ffree = 0; // Total number of free file serial numbers. buf->f_favail = 0; // Number of file serial numbers available to non-privileged process. buf->f_fsid = 0; // File system ID. 32bit ioType value buf->f_flag = 0; // Bit mask of f_flag values. buf->f_namemax = SMB_MAXPATH; // Maximum filename length. return SMB_SUCCESS; } failed: handle->conn_valid = false; return ret; } /** * SMB_Read */ s32 SMB_ReadFile(char *buffer, size_t size, off_t offset, SMBFILE sfid) { u8 *ptr; u32 pos, ret, ofs; u16 length = 0; SMBHANDLE *handle; size_t totalread=0,nextread; struct _smbfile *fid = (struct _smbfile*)sfid; if(!fid) return -1; // Check for invalid size if(size == 0) return -1; handle = __smb_handle_open(fid->conn); if(!handle) return -1; while(totalread < size) { if((size-totalread) > SMB_MAX_TRANSMIT_SIZE) nextread=SMB_MAX_TRANSMIT_SIZE; else nextread=size-totalread; MakeSMBHeader(SMB_READ_ANDX,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 12); pos++; /*** Word count ***/ setUChar(ptr, pos, 0xff); pos++; setUChar(ptr, pos, 0); pos++; /*** Reserved must be 0 ***/ pos += 2; /*** Next AndX Offset ***/ setUShort(ptr, pos, fid->sfid); pos += 2; /*** FID ***/ setUInt(ptr, pos, (offset+totalread) & 0xffffffff); pos += 4; /*** Offset ***/ setUShort(ptr, pos, nextread & 0xffff); pos += 2; setUShort(ptr, pos, nextread & 0xffff); pos += 2; setUInt(ptr, pos, 0); pos += 4; /*** Reserved must be 0 ***/ setUShort(ptr, pos, nextread & 0xffff); pos += 2; /*** Remaining ***/ setUInt(ptr, pos, (offset+totalread) >> 32); // offset high pos += 4; /*** OffsetHIGH ***/ pos += 2; /*** Byte count ***/ handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message, pos); if(ret<0) goto failed; /*** SMBCheck ***/ if(SMBCheck(SMB_READ_ANDX,handle)!=SMB_SUCCESS) goto failed; ptr = handle->message.smb; // Retrieve data length for this packet length = getUShort(ptr,(SMB_HEADER_SIZE+11)); if(length==0) break; // Retrieve offset to data ofs = getUShort(ptr,(SMB_HEADER_SIZE+13)); memcpy(&buffer[totalread],&ptr[ofs],length); totalread+=length; } return size; failed: handle->conn_valid = false; return SMB_ERROR; } /** * SMB_Write */ s32 SMB_WriteFile(const char *buffer, size_t size, off_t offset, SMBFILE sfid) { u8 *ptr,*src; s32 pos, ret; s32 blocks64; u32 copy_len; SMBHANDLE *handle; struct _smbfile *fid = (struct _smbfile*)sfid; if(!fid) return -1; handle = __smb_handle_open(fid->conn); if(!handle) return -1; MakeSMBHeader(SMB_WRITE_ANDX,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 14); pos++; /*** Word Count ***/ setUChar(ptr, pos, 0xff); pos += 2; /*** Next AndX ***/ pos += 2; /*** Next AndX Offset ***/ setUShort(ptr, pos, fid->sfid); pos += 2; setUInt(ptr, pos, offset & 0xffffffff); pos += 4; setUInt(ptr, pos, 0); /*** Reserved, must be 0 ***/ pos += 4; setUShort(ptr, pos, 0); /*** Write Mode ***/ pos += 2; pos += 2; /*** Remaining ***/ blocks64 = size >> 16; setUShort(ptr, pos, blocks64); pos += 2; /*** Length High ***/ setUShort(ptr, pos, size & 0xffff); pos += 2; /*** Length Low ***/ setUShort(ptr, pos, 63); pos += 2; /*** Data Offset ***/ setUInt(ptr, pos, offset >> 32); /*** OffsetHigh ***/ pos += 4; setUShort(ptr, pos, size & 0xffff); pos += 2; /*** Data Byte Count ***/ handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos+size); src = (u8*)buffer; copy_len = size; if((copy_len+pos)>SMB_MAX_TRANSMIT_SIZE) copy_len = (SMB_MAX_TRANSMIT_SIZE-pos); memcpy(&ptr[pos],src,copy_len); size -= copy_len; src += copy_len; pos += copy_len; pos += 4; /*** Send Header Information ***/ ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret<0) goto failed; if(size>0) { /*** Send the data ***/ ret = smb_send(handle->sck_server,src,size); if(ret<0) goto failed; } ret = 0; if(SMBCheck(SMB_WRITE_ANDX,handle)==SMB_SUCCESS) { ptr = handle->message.smb; ret = getUShort(ptr,(SMB_HEADER_SIZE+5)); } return ret; failed: handle->conn_valid = false; return ret; } /** * SMB_PathInfo */ s32 SMB_PathInfo(const char *filename, SMBDIRENTRY *sdir, SMBCONN smbhndl) { u8 *ptr; s32 pos; s32 ret; s32 bpos; int len; SMBHANDLE *handle; char realfile[512]; if(filename == NULL) return SMB_ERROR; handle = __smb_handle_open(smbhndl); if (!handle) return SMB_ERROR; MakeSMBHeader(SMB_TRANS2, CIFS_FLAGS1, handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2, handle); MakeTRANS2Header(SMB_QUERY_PATH_INFO, handle); bpos = pos = (T2_BYTE_CNT + 2); pos += 3; /*** Padding ***/ ptr = handle->message.smb; setUShort(ptr, pos, SMB_QUERY_FILE_ALL_INFO); pos += 2; /*** Level of information requested ***/ setUInt(ptr, pos, 0); pos += 4; /*** reserved ***/ realfile[0] = '\0'; if (filename[0] != '\\') strcpy(realfile,"\\"); strcat(realfile,filename); if(handle->unicode) { len = utf8_to_utf16((char*)&ptr[pos],realfile,SMB_MAXPATH-2); pos += len+2; len+=1; } else { len = strlen(realfile); memcpy(&ptr[pos],realfile,len); pos += len+1; } /*** Update counts ***/ setUShort(ptr, T2_PRM_CNT, (7 + len)); setUShort(ptr, T2_SPRM_CNT, (7 + len)); setUShort(ptr, T2_SPRM_OFS, 68); setUShort(ptr, T2_BYTE_CNT, (pos - bpos)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server, (char*) &handle->message, pos); if(ret<0) goto failed; ret = SMB_ERROR; if (SMBCheck(SMB_TRANS2, handle) == SMB_SUCCESS) { ptr = handle->message.smb; /*** Get parameter offset ***/ pos = getUShort(ptr, (SMB_HEADER_SIZE + 9)); pos += 4; // padding sdir->ctime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - creation time sdir->atime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - access time sdir->mtime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - write time pos += 8; // ULONGLONG - change time sdir->attributes = getUInt(ptr,pos); pos += 4; // ULONG - file attributes pos += 4; // padding pos += 8; // ULONGLONG - allocated file size sdir->size = getULongLong(ptr, pos); pos += 8; // ULONGLONG - file size pos += 4; // ULONG NumberOfLinks; pos += 2; // UCHAR DeletePending; pos += 2; // UCHAR Directory; pos += 2; // USHORT Pad2; // for alignment only pos += 4; // ULONG EaSize; pos += 4; // ULONG FileNameLength; strcpy(sdir->name,realfile); ret = SMB_SUCCESS; } return ret; failed: handle->conn_valid = false; return ret; } /** * SMB_FindFirst * * Uses TRANS2 to support long filenames */ s32 SMB_FindFirst(const char *filename, unsigned short flags, SMBDIRENTRY *sdir, SMBCONN smbhndl) { u8 *ptr; s32 pos; s32 ret; s32 bpos; unsigned int len; SMBHANDLE *handle; SMBSESSION *sess; if(filename == NULL) return SMB_ERROR; if(SMB_Reconnect(&smbhndl,true)!=SMB_SUCCESS) return SMB_ERROR; handle = __smb_handle_open(smbhndl); if(!handle) return SMB_ERROR; sess = &handle->session; MakeSMBHeader(SMB_TRANS2,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); MakeTRANS2Header(SMB_FIND_FIRST2,handle); ptr = handle->message.smb; bpos = pos = (T2_BYTE_CNT+2); pos += 3; /*** Padding ***/ setUShort(ptr, pos, flags); pos += 2; /*** Flags ***/ setUShort(ptr, pos, 1); pos += 2; /*** Count ***/ setUShort(ptr, pos, 6); pos += 2; /*** Internal Flags ***/ setUShort(ptr, pos, 260); // SMB_FIND_FILE_BOTH_DIRECTORY_INFO pos += 2; /*** Level of Interest ***/ pos += 4; /*** Storage Type == 0 ***/ if(handle->unicode) { len = utf8_to_utf16((char*)&ptr[pos], (char*)filename,SMB_MAXPATH-2); pos += len+2; len++; } else { len = strlen(filename); memcpy(&ptr[pos],filename,len); pos += len+1; } /*** Update counts ***/ setUShort(ptr, T2_PRM_CNT, (13+len)); setUShort(ptr, T2_SPRM_CNT, (13+len)); setUShort(ptr, T2_SPRM_OFS, 68); setUShort(ptr, T2_BYTE_CNT,(pos-bpos)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret<0) goto failed; sess->eos = 1; sess->count = 0; ret = SMB_ERROR; if(SMBCheck(SMB_TRANS2,handle)==SMB_SUCCESS) { ptr = handle->message.smb; /*** Get parameter offset ***/ pos = getUShort(ptr,(SMB_HEADER_SIZE+9)); sdir->sid = getUShort(ptr, pos); pos += 2; sess->count = getUShort(ptr, pos); pos += 2; sess->eos = getUShort(ptr, pos); pos += 2; pos += 2; // USHORT EaErrorOffset; pos += 2; // USHORT LastNameOffset; pos += 2; // padding? if (sess->count) { pos += 4; // ULONG NextEntryOffset; pos += 4; // ULONG FileIndex; sdir->ctime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - creation time sdir->atime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - access time sdir->mtime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - write time pos += 8; // ULONGLONG - change time low sdir->size = getULongLong(ptr, pos); pos += 8; pos += 8; sdir->attributes = getUInt(ptr, pos); pos += 4; len=getUInt(ptr, pos); pos += 34; if(handle->unicode) utf16_to_utf8(sdir->name,(char*)&ptr[pos],len); else strcpy(sdir->name,(const char*)&ptr[pos]); ret = SMB_SUCCESS; } } return ret; failed: handle->conn_valid = false; return ret; } /** * SMB_FindNext */ s32 SMB_FindNext(SMBDIRENTRY *sdir,SMBCONN smbhndl) { u8 *ptr; s32 pos; s32 ret; s32 bpos; SMBHANDLE *handle; SMBSESSION *sess; handle = __smb_handle_open(smbhndl); if(!handle) return SMB_ERROR; sess = &handle->session; if(sess->eos || sdir->sid==0) return SMB_ERROR; MakeSMBHeader(SMB_TRANS2,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); MakeTRANS2Header(SMB_FIND_NEXT2,handle); bpos = pos = (T2_BYTE_CNT+2); pos += 3; /*** Padding ***/ ptr = handle->message.smb; setUShort(ptr, pos, sdir->sid); pos += 2; /*** Search ID ***/ setUShort(ptr, pos, 1); pos += 2; /*** Count ***/ setUShort(ptr, pos, 260); // SMB_FIND_FILE_BOTH_DIRECTORY_INFO pos += 2; /*** Level of Interest ***/ pos += 4; /*** Storage Type == 0 ***/ setUShort(ptr, pos, 12); pos+=2; /*** Search flags ***/ pos++; int pad=0; if(handle->unicode)pad=1; pos+=pad; /*** Update counts ***/ setUShort(ptr, T2_PRM_CNT, 13+pad); setUShort(ptr, T2_SPRM_CNT, 13+pad); setUShort(ptr, T2_SPRM_OFS, 68); setUShort(ptr, T2_BYTE_CNT, (pos-bpos)); handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret<0) goto failed; ret = SMB_ERROR; if (SMBCheck(SMB_TRANS2,handle)==SMB_SUCCESS) { ptr = handle->message.smb; /*** Get parameter offset ***/ pos = getUShort(ptr,(SMB_HEADER_SIZE+9)); sess->count = getUShort(ptr, pos); pos += 2; sess->eos = getUShort(ptr, pos); pos += 2; pos += 2; // USHORT EaErrorOffset; pos += 2; // USHORT LastNameOffset; if (sess->count) { int len; pos += 4; // ULONG NextEntryOffset; pos += 4; // ULONG FileIndex; sdir->ctime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - creation time sdir->atime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - access time sdir->mtime = getULongLong(ptr, pos) - handle->session.timeOffset; pos += 8; // ULONGLONG - write time pos += 8; // ULONGLONG - change time low sdir->size = getULongLong(ptr, pos); pos += 8; pos += 8; sdir->attributes = getUInt(ptr, pos); pos += 4; len=getUInt(ptr, pos); pos += 34; if(handle->unicode) utf16_to_utf8(sdir->name, (char*)&ptr[pos],len); else strcpy (sdir->name, (const char*)&ptr[pos]); ret = SMB_SUCCESS; } } return ret; failed: handle->conn_valid = false; return ret; } /** * SMB_FindClose */ s32 SMB_FindClose(SMBDIRENTRY *sdir,SMBCONN smbhndl) { u8 *ptr; s32 pos; s32 ret; SMBHANDLE *handle; handle = __smb_handle_open(smbhndl); if(!handle) return SMB_ERROR; if(sdir->sid==0) return SMB_ERROR; MakeSMBHeader(SMB_FIND_CLOSE2,CIFS_FLAGS1,handle->unicode?CIFS_FLAGS2_UNICODE:CIFS_FLAGS2,handle); pos = SMB_HEADER_SIZE; ptr = handle->message.smb; setUChar(ptr, pos, 1); pos++; /*** Word Count ***/ setUShort(ptr, pos, sdir->sid); pos += 2; pos += 2; /*** Byte Count ***/ handle->message.msg = NBT_SESSISON_MSG; handle->message.length = htons(pos); pos += 4; ret = smb_send(handle->sck_server,(char*)&handle->message,pos); if(ret<0) goto failed; ret = SMBCheck(SMB_FIND_CLOSE2,handle); return ret; failed: handle->conn_valid = false; return ret; }
{ "pile_set_name": "Github" }
################################################################################ # # bustle # ################################################################################ BUSTLE_VERSION = 0.7.5 BUSTLE_SITE = https://www.freedesktop.org/software/bustle/$(BUSTLE_VERSION) BUSTLE_LICENSE = LGPL-2.1+ BUSTLE_LICENSE_FILES = LICENSE BUSTLE_DEPENDENCIES = libglib2 libpcap host-pkgconf BUSTLE_PCAP_FLAGS = "-lpcap" ifeq ($(BR2_STATIC_LIBS),y) BUSTLE_PCAP_FLAGS += `$(STAGING_DIR)/usr/bin/pcap-config --static --additional-libs` endif define BUSTLE_BUILD_CMDS $(TARGET_MAKE_ENV) $(MAKE) $(TARGET_CONFIGURE_OPTS) \ PCAP_FLAGS="$(BUSTLE_PCAP_FLAGS)" -C $(@D) dist/build/bustle-pcap endef define BUSTLE_INSTALL_TARGET_CMDS $(INSTALL) -m 0755 -D $(@D)/dist/build/bustle-pcap \ $(TARGET_DIR)/usr/bin/bustle-pcap endef $(eval $(generic-package))
{ "pile_set_name": "Github" }
version: "build-{branch}-{build}" image: Visual Studio 2015 clone_folder: c:\gopath\src\github.com\hashicorp\hcl environment: GOPATH: c:\gopath init: - git config --global core.autocrlf false install: - cmd: >- echo %Path% go version go env go get -t ./... build_script: - cmd: go test -v ./...
{ "pile_set_name": "Github" }
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDImageIOAnimatedCoder.h" /** This coder is used for HEIC (HEIF with HEVC container codec) image format. Image/IO provide the static HEIC (.heic) support in iOS 11/macOS 10.13/tvOS 11/watchOS 4+. Image/IO provide the animated HEIC (.heics) support in iOS 13/macOS 10.15/tvOS 13/watchOS 6+. See https://nokiatech.github.io/heif/technical.html for the standard. @note This coder is not in the default coder list for now, since HEIC animated image is really rare, and Apple's implementation still contains performance issues. You can enable if you need this. @note If you need to support lower firmware version for HEIF, you can have a try at https://github.com/SDWebImage/SDWebImageHEIFCoder */ API_AVAILABLE(ios(13.0), tvos(13.0), macos(10.15), watchos(6.0)) @interface SDImageHEICCoder : SDImageIOAnimatedCoder <SDProgressiveImageCoder, SDAnimatedImageCoder> @property (nonatomic, class, readonly, nonnull) SDImageHEICCoder *sharedCoder; @end
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 20de11df2f806fa45a43e02aff5fd705 timeCreated: 1512363982 licenseType: Free TextureImporter: fileIDToRecycleName: {} externalObjects: {} serializedVersion: 4 mipmaps: mipMapMode: 0 enableMipMap: 0 sRGBTexture: 1 linearTexture: 0 fadeOut: 0 borderMipMap: 0 mipMapsPreserveCoverage: 0 alphaTestReferenceValue: 0.5 mipMapFadeDistanceStart: 1 mipMapFadeDistanceEnd: 3 bumpmap: convertToNormalMap: 0 externalNormalMap: 0 heightScale: 0.25 normalMapFilter: 0 isReadable: 0 grayScaleToAlpha: 0 generateCubemap: 6 cubemapConvolution: 0 seamlessCubemap: 0 textureFormat: 1 maxTextureSize: 2048 textureSettings: serializedVersion: 2 filterMode: -1 aniso: -1 mipBias: -1 wrapU: 1 wrapV: 1 wrapW: 1 nPOTScale: 0 lightmap: 0 compressionQuality: 50 spriteMode: 1 spriteExtrude: 1 spriteMeshType: 1 alignment: 0 spritePivot: {x: 0.5, y: 0.5} spriteBorder: {x: 0, y: 0, z: 0, w: 0} spritePixelsToUnits: 100 alphaUsage: 1 alphaIsTransparency: 1 spriteTessellationDetail: -1 textureType: 8 textureShape: 1 maxTextureSizeSet: 0 compressionQualitySet: 0 textureFormatSet: 0 platformSettings: - buildTarget: DefaultTexturePlatform maxTextureSize: 2048 resizeAlgorithm: 0 textureFormat: -1 textureCompression: 1 compressionQuality: 50 crunchedCompression: 0 allowsAlphaSplitting: 0 overridden: 0 spriteSheet: serializedVersion: 2 sprites: [] outline: [] physicsShape: [] spritePackingTag: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: fe12bbbb7ae1d7840b13f09ac428fa23 timeCreated: 1494145780 licenseType: Free TextureImporter: fileIDToRecycleName: {} serializedVersion: 2 mipmaps: mipMapMode: 0 enableMipMap: 0 linearTexture: 0 correctGamma: 0 fadeOut: 0 borderMipMap: 0 mipMapFadeDistanceStart: 1 mipMapFadeDistanceEnd: 3 bumpmap: convertToNormalMap: 0 externalNormalMap: 0 heightScale: 0.25 normalMapFilter: 0 isReadable: 0 grayScaleToAlpha: 0 generateCubemap: 0 cubemapConvolution: 0 cubemapConvolutionSteps: 7 cubemapConvolutionExponent: 1.5 seamlessCubemap: 0 textureFormat: -1 maxTextureSize: 2048 textureSettings: filterMode: -1 aniso: 16 mipBias: -1 wrapMode: 1 nPOTScale: 0 lightmap: 0 rGBM: 0 compressionQuality: 50 allowsAlphaSplitting: 0 spriteMode: 1 spriteExtrude: 1 spriteMeshType: 1 alignment: 0 spritePivot: {x: 0.5, y: 0.5} spriteBorder: {x: 0, y: 0, z: 0, w: 0} spritePixelsToUnits: 100 alphaIsTransparency: 1 textureType: 8 buildTargetSettings: [] spriteSheet: serializedVersion: 2 sprites: [] outline: [] spritePackingTag: abc userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
// // PINOperationTypes.h // PINOperation // // Created by Adlai Holler on 1/10/17. // Copyright © 2017 Pinterest. All rights reserved. // #import <Foundation/Foundation.h> typedef NS_ENUM(NSUInteger, PINOperationQueuePriority) { PINOperationQueuePriorityLow, PINOperationQueuePriorityDefault, PINOperationQueuePriorityHigh, };
{ "pile_set_name": "Github" }
/* ### * IP: GHIDRA * * 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 ghidra.file.formats.android.odex; import java.io.IOException; import ghidra.app.util.bin.BinaryReader; import ghidra.app.util.bin.StructConverter; import ghidra.program.model.data.DataType; import ghidra.program.model.data.Structure; import ghidra.program.model.data.StructureDataType; import ghidra.util.exception.DuplicateNameException; public class OdexHeader implements StructConverter { private byte [] magic; private int dexOffset; private int dexLength; private int depsOffset; private int depsLength; private int auxOffset; private int auxLength; private int flags; private int padding; public OdexHeader( BinaryReader reader ) throws IOException { magic = reader.readNextByteArray( OdexConstants.ODEX_MAGIC_LENGTH ); dexOffset = reader.readNextInt(); dexLength = reader.readNextInt(); depsOffset = reader.readNextInt(); depsLength = reader.readNextInt(); auxOffset = reader.readNextInt(); auxLength = reader.readNextInt(); flags = reader.readNextInt(); padding = reader.readNextInt(); } public String getMagic() { return new String( magic ); } /** * Returns byte offset to the optimized DEX file. */ public int getDexOffset() { return dexOffset; } /** * Returns byte length of the optimized DEX file. */ public int getDexLength() { return dexLength; } /** * Return byte offset to the framework dependencies. */ public int getDepsOffset() { return depsOffset; } /** * Return byte length of the framework dependencies. */ public int getDepsLength() { return depsLength; } /** * Return byte offset to the auxiliary data. */ public int getAuxOffset() { return auxOffset; } /** * Return byte length to the auxiliary data. */ public int getAuxLength() { return auxLength; } /** * Return the ODEX flags. */ public int getFlags() { return flags; } public int getPadding() { return padding; } @Override public DataType toDataType() throws DuplicateNameException, IOException { Structure structure = new StructureDataType( "odex_header_item", 0 ); structure.add( UTF8, OdexConstants.ODEX_MAGIC_LENGTH, "magic", null ); structure.add( DWORD, "dex_offset", null ); structure.add( DWORD, "dex_length", null ); structure.add( DWORD, "deps_offset", null ); structure.add( DWORD, "deps_length", null ); structure.add( DWORD, "aux_offset", null ); structure.add( DWORD, "aux_length", null ); structure.add( DWORD, "flags", null ); structure.add( DWORD, "padding", null ); return structure; } }
{ "pile_set_name": "Github" }
import ButtonMutate from 'modules/common/components/ButtonMutate'; import { IButtonMutateProps } from 'modules/common/types'; import React from 'react'; import DashbaordForm from '../components/DashboardForm'; import { mutations } from '../graphql'; import { IDashboard } from '../types'; type Props = { show: boolean; dashboard?: IDashboard; closeModal: () => void; }; class DashboardFormContainer extends React.Component<Props> { renderButton = ({ name, values, isSubmitted, callback, object }: IButtonMutateProps) => { return ( <ButtonMutate mutation={object ? mutations.dashboardEdit : mutations.dashboardAdd} variables={values} callback={callback} refetchQueries={['dashboards', 'dashboardDetails']} isSubmitted={isSubmitted} type="submit" uppercase={false} successMessage={`You successfully ${ object ? 'updated' : 'added' } a ${name}`} /> ); }; render() { const updatedProps = { ...this.props, renderButton: this.renderButton }; return <DashbaordForm {...updatedProps} />; } } export default DashboardFormContainer;
{ "pile_set_name": "Github" }
Version 0.4 January 2006 ======================== - $$ $$ usually accepted for displayed equations (but less robust than \[ \] or displaymath environment) - For commands which are in textcmd list but not in safecmd list (e.g. \footnote and \section commands) the content is now marked up if they are added or deleted. (Thanks to S. Utcke for alerting me to this shortcoming of previous versions). The downside of this change is that deleted section heads are now shown, messing up the section numbering - added RCS and SVN support to latexdiff-vc (previous name latexdiff-cvs) - a fast version (latexdiff-fast) uses the UNIX diff command to speed up the differencing phases. Minor bug fixes: - Improved parsing of textcmd and safecmd lists, some clarification in manual (Thanks to V. Kuhlmann for fix) - All \color commands now \protect'ed (V. Kuhlmann) - Picture environment within floats now is cleared up properly (Thanks to V. Kuhlmann for fix) - non-matching textcommands right before \end{document} are now parsed correctly - updates to textcmd (emph, text..) and safecmd lists (emph) - fixed \par bug. Previously, this bug resulted new paragraphs to be merged with the following paragraph. - better error checking in latexdiff-vc - can specify arbitrary number of files in latexdiff-vc - can choose output directory in latexdiff-vc Version 0.3 August 2005 ========================== - fixed bug where a deleted displayed equation would result in math mode commands being processed in text mode (the "! Missing $ inserted" error). - Improved parsing in math mode: Superscript and subscript and \left,\right are now parsed correctly - shell script for providing CVS support Minor: - fixed a bug in utf8 mode that resulted in many warning messages and failure to parse properly words with national characters - Now works with the latest version of Algorithm::Diff (version 1.19) - new options "--allow-spaces" and "--ignore-warnings" - Better wording and enhanced context for warning messages - '|' character is now recognised as valid math mode character - Fixed a bug whereby \begin{document} and \end{document} in comments are nevertheless treated as real begin and end points - add \protect in front of \nogroupcolor command in DVIPSCOL subtype (old version broke sometimes according to bug reports although I could not replicate the problem) - replace \uline by \uwave in CUNDERLINE style, such that added and deleted text parts look different even in math mode - Markup within DIFnomarkup enviroment is removed by latexdiff. This can be used to protect parts for which latexdiff has trouble creating proper latex code. - new markup type FONTSTRIKE Version 0.2 September 2004 =========================== - introduced subtype DVIPSCOL (coloring changed blocks for dvips converter) - support for utf8 and other encodings Minor: - removed buggy COLOR subtype - Usage information no longer printed automatically after certain syntactic error messages - short options -a, -A, -x, -X now really do what is claimed in the manual - bug in failback splitting of input was fixed - options --exclude-textcmd, --append-textcmd, --exclude-safecmd, and --append-safecmd can now take comma-separated list as well as a file as argument.
{ "pile_set_name": "Github" }
/** * @author Swagatam Mitra */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, document, console, brackets, $, Mustache */ define(function (require, exports, module) { "use strict"; require("borderradiusresizer/TopRightCornerRadiusHandler"); require("borderradiusresizer/BottomRightCornerRadiusHandler"); require("borderradiusresizer/TopLeftCornerRadiusHandler"); require("borderradiusresizer/BottomLeftCornerRadiusHandler"); function _showRadiusEditMode(event){ $("#border-outline").show(); $("#selection-outline").addClass('multiSelectStyle'); $(".dragResizer").hide(); $("#element-Settings").hide(); $("#position-tooltip-display").hide(); event.preventDefault(); event.stopPropagation(); } function _hideRadiusEditMode(event){ $("#border-outline").hide(); $("#selection-outline").removeClass('multiSelectStyle'); $(".dragResizer").show(); $("#element-Settings").show(); $("#position-tooltip-display").show(); } $(document).on("border-radius-mode-on","#html-design-editor",_showRadiusEditMode); $(document).on("border-radius-mode-off","#html-design-editor",_hideRadiusEditMode); });
{ "pile_set_name": "Github" }
package main import ( "bytes" "encoding/json" "errors" "io" "net/http" "net/http/httptest" "reflect" "strings" "testing" ) type MockUserService struct { RegisterFunc func(user User) (string, error) UsersRegistered []User } func (m *MockUserService) Register(user User) (insertedID string, err error) { m.UsersRegistered = append(m.UsersRegistered, user) return m.RegisterFunc(user) } func TestRegisterUser(t *testing.T) { t.Run("can register valid users", func(t *testing.T) { user := User{Name: "CJ"} expectedInsertedID := "whatever" service := &MockUserService{ RegisterFunc: func(user User) (string, error) { return expectedInsertedID, nil }, } server := NewUserServer(service) req := httptest.NewRequest(http.MethodGet, "/", userToJSON(user)) res := httptest.NewRecorder() server.RegisterUser(res, req) assertStatus(t, res.Code, http.StatusCreated) if res.Body.String() != expectedInsertedID { t.Errorf("expected body of %q but got %q", res.Body.String(), expectedInsertedID) } if len(service.UsersRegistered) != 1 { t.Fatalf("expected 1 user added but got %d", len(service.UsersRegistered)) } if !reflect.DeepEqual(service.UsersRegistered[0], user) { t.Errorf("the user registered %+v was not what was expected %+v", service.UsersRegistered[0], user) } }) t.Run("returns 400 bad request if body is not valid user JSON", func(t *testing.T) { server := NewUserServer(nil) req := httptest.NewRequest(http.MethodGet, "/", strings.NewReader("trouble will find me")) res := httptest.NewRecorder() server.RegisterUser(res, req) assertStatus(t, res.Code, http.StatusBadRequest) }) t.Run("returns a 500 internal server error if the service fails", func(t *testing.T) { user := User{Name: "CJ"} service := &MockUserService{ RegisterFunc: func(user User) (string, error) { return "", errors.New("couldn't add new user") }, } server := NewUserServer(service) req := httptest.NewRequest(http.MethodGet, "/", userToJSON(user)) res := httptest.NewRecorder() server.RegisterUser(res, req) assertStatus(t, res.Code, http.StatusInternalServerError) }) } func assertStatus(t *testing.T, got, want int) { t.Helper() if got != want { t.Errorf("wanted http status %d but got %d", got, want) } } func userToJSON(user User) io.Reader { stuff, _ := json.Marshal(user) return bytes.NewReader(stuff) }
{ "pile_set_name": "Github" }
package metrics import ( "math" "math/rand" "sort" "sync" "time" ) const rescaleThreshold = time.Hour // Samples maintain a statistically-significant selection of values from // a stream. type Sample interface { Clear() Count() int64 Max() int64 Mean() float64 Min() int64 Percentile(float64) float64 Percentiles([]float64) []float64 Size() int Snapshot() Sample StdDev() float64 Sum() int64 Update(int64) Values() []int64 Variance() float64 } // ExpDecaySample is an exponentially-decaying sample using a forward-decaying // priority reservoir. See Cormode et al's "Forward Decay: A Practical Time // Decay Model for Streaming Systems". // // <http://www.research.att.com/people/Cormode_Graham/library/publications/CormodeShkapenyukSrivastavaXu09.pdf> type ExpDecaySample struct { alpha float64 count int64 mutex sync.Mutex reservoirSize int t0, t1 time.Time values *expDecaySampleHeap } // NewExpDecaySample constructs a new exponentially-decaying sample with the // given reservoir size and alpha. func NewExpDecaySample(reservoirSize int, alpha float64) Sample { if UseNilMetrics { return NilSample{} } s := &ExpDecaySample{ alpha: alpha, reservoirSize: reservoirSize, t0: time.Now(), values: newExpDecaySampleHeap(reservoirSize), } s.t1 = s.t0.Add(rescaleThreshold) return s } // Clear clears all samples. func (s *ExpDecaySample) Clear() { s.mutex.Lock() defer s.mutex.Unlock() s.count = 0 s.t0 = time.Now() s.t1 = s.t0.Add(rescaleThreshold) s.values.Clear() } // Count returns the number of samples recorded, which may exceed the // reservoir size. func (s *ExpDecaySample) Count() int64 { s.mutex.Lock() defer s.mutex.Unlock() return s.count } // Max returns the maximum value in the sample, which may not be the maximum // value ever to be part of the sample. func (s *ExpDecaySample) Max() int64 { return SampleMax(s.Values()) } // Mean returns the mean of the values in the sample. func (s *ExpDecaySample) Mean() float64 { return SampleMean(s.Values()) } // Min returns the minimum value in the sample, which may not be the minimum // value ever to be part of the sample. func (s *ExpDecaySample) Min() int64 { return SampleMin(s.Values()) } // Percentile returns an arbitrary percentile of values in the sample. func (s *ExpDecaySample) Percentile(p float64) float64 { return SamplePercentile(s.Values(), p) } // Percentiles returns a slice of arbitrary percentiles of values in the // sample. func (s *ExpDecaySample) Percentiles(ps []float64) []float64 { return SamplePercentiles(s.Values(), ps) } // Size returns the size of the sample, which is at most the reservoir size. func (s *ExpDecaySample) Size() int { s.mutex.Lock() defer s.mutex.Unlock() return s.values.Size() } // Snapshot returns a read-only copy of the sample. func (s *ExpDecaySample) Snapshot() Sample { s.mutex.Lock() defer s.mutex.Unlock() vals := s.values.Values() values := make([]int64, len(vals)) for i, v := range vals { values[i] = v.v } return &SampleSnapshot{ count: s.count, values: values, } } // StdDev returns the standard deviation of the values in the sample. func (s *ExpDecaySample) StdDev() float64 { return SampleStdDev(s.Values()) } // Sum returns the sum of the values in the sample. func (s *ExpDecaySample) Sum() int64 { return SampleSum(s.Values()) } // Update samples a new value. func (s *ExpDecaySample) Update(v int64) { s.update(time.Now(), v) } // Values returns a copy of the values in the sample. func (s *ExpDecaySample) Values() []int64 { s.mutex.Lock() defer s.mutex.Unlock() vals := s.values.Values() values := make([]int64, len(vals)) for i, v := range vals { values[i] = v.v } return values } // Variance returns the variance of the values in the sample. func (s *ExpDecaySample) Variance() float64 { return SampleVariance(s.Values()) } // update samples a new value at a particular timestamp. This is a method all // its own to facilitate testing. func (s *ExpDecaySample) update(t time.Time, v int64) { s.mutex.Lock() defer s.mutex.Unlock() s.count++ if s.values.Size() == s.reservoirSize { s.values.Pop() } s.values.Push(expDecaySample{ k: math.Exp(t.Sub(s.t0).Seconds()*s.alpha) / rand.Float64(), v: v, }) if t.After(s.t1) { values := s.values.Values() t0 := s.t0 s.values.Clear() s.t0 = t s.t1 = s.t0.Add(rescaleThreshold) for _, v := range values { v.k = v.k * math.Exp(-s.alpha*s.t0.Sub(t0).Seconds()) s.values.Push(v) } } } // NilSample is a no-op Sample. type NilSample struct{} // Clear is a no-op. func (NilSample) Clear() {} // Count is a no-op. func (NilSample) Count() int64 { return 0 } // Max is a no-op. func (NilSample) Max() int64 { return 0 } // Mean is a no-op. func (NilSample) Mean() float64 { return 0.0 } // Min is a no-op. func (NilSample) Min() int64 { return 0 } // Percentile is a no-op. func (NilSample) Percentile(p float64) float64 { return 0.0 } // Percentiles is a no-op. func (NilSample) Percentiles(ps []float64) []float64 { return make([]float64, len(ps)) } // Size is a no-op. func (NilSample) Size() int { return 0 } // Sample is a no-op. func (NilSample) Snapshot() Sample { return NilSample{} } // StdDev is a no-op. func (NilSample) StdDev() float64 { return 0.0 } // Sum is a no-op. func (NilSample) Sum() int64 { return 0 } // Update is a no-op. func (NilSample) Update(v int64) {} // Values is a no-op. func (NilSample) Values() []int64 { return []int64{} } // Variance is a no-op. func (NilSample) Variance() float64 { return 0.0 } // SampleMax returns the maximum value of the slice of int64. func SampleMax(values []int64) int64 { if 0 == len(values) { return 0 } var max int64 = math.MinInt64 for _, v := range values { if max < v { max = v } } return max } // SampleMean returns the mean value of the slice of int64. func SampleMean(values []int64) float64 { if 0 == len(values) { return 0.0 } return float64(SampleSum(values)) / float64(len(values)) } // SampleMin returns the minimum value of the slice of int64. func SampleMin(values []int64) int64 { if 0 == len(values) { return 0 } var min int64 = math.MaxInt64 for _, v := range values { if min > v { min = v } } return min } // SamplePercentiles returns an arbitrary percentile of the slice of int64. func SamplePercentile(values int64Slice, p float64) float64 { return SamplePercentiles(values, []float64{p})[0] } // SamplePercentiles returns a slice of arbitrary percentiles of the slice of // int64. func SamplePercentiles(values int64Slice, ps []float64) []float64 { scores := make([]float64, len(ps)) size := len(values) if size > 0 { sort.Sort(values) for i, p := range ps { pos := p * float64(size+1) if pos < 1.0 { scores[i] = float64(values[0]) } else if pos >= float64(size) { scores[i] = float64(values[size-1]) } else { lower := float64(values[int(pos)-1]) upper := float64(values[int(pos)]) scores[i] = lower + (pos-math.Floor(pos))*(upper-lower) } } } return scores } // SampleSnapshot is a read-only copy of another Sample. type SampleSnapshot struct { count int64 values []int64 } // Clear panics. func (*SampleSnapshot) Clear() { panic("Clear called on a SampleSnapshot") } // Count returns the count of inputs at the time the snapshot was taken. func (s *SampleSnapshot) Count() int64 { return s.count } // Max returns the maximal value at the time the snapshot was taken. func (s *SampleSnapshot) Max() int64 { return SampleMax(s.values) } // Mean returns the mean value at the time the snapshot was taken. func (s *SampleSnapshot) Mean() float64 { return SampleMean(s.values) } // Min returns the minimal value at the time the snapshot was taken. func (s *SampleSnapshot) Min() int64 { return SampleMin(s.values) } // Percentile returns an arbitrary percentile of values at the time the // snapshot was taken. func (s *SampleSnapshot) Percentile(p float64) float64 { return SamplePercentile(s.values, p) } // Percentiles returns a slice of arbitrary percentiles of values at the time // the snapshot was taken. func (s *SampleSnapshot) Percentiles(ps []float64) []float64 { return SamplePercentiles(s.values, ps) } // Size returns the size of the sample at the time the snapshot was taken. func (s *SampleSnapshot) Size() int { return len(s.values) } // Snapshot returns the snapshot. func (s *SampleSnapshot) Snapshot() Sample { return s } // StdDev returns the standard deviation of values at the time the snapshot was // taken. func (s *SampleSnapshot) StdDev() float64 { return SampleStdDev(s.values) } // Sum returns the sum of values at the time the snapshot was taken. func (s *SampleSnapshot) Sum() int64 { return SampleSum(s.values) } // Update panics. func (*SampleSnapshot) Update(int64) { panic("Update called on a SampleSnapshot") } // Values returns a copy of the values in the sample. func (s *SampleSnapshot) Values() []int64 { values := make([]int64, len(s.values)) copy(values, s.values) return values } // Variance returns the variance of values at the time the snapshot was taken. func (s *SampleSnapshot) Variance() float64 { return SampleVariance(s.values) } // SampleStdDev returns the standard deviation of the slice of int64. func SampleStdDev(values []int64) float64 { return math.Sqrt(SampleVariance(values)) } // SampleSum returns the sum of the slice of int64. func SampleSum(values []int64) int64 { var sum int64 for _, v := range values { sum += v } return sum } // SampleVariance returns the variance of the slice of int64. func SampleVariance(values []int64) float64 { if 0 == len(values) { return 0.0 } m := SampleMean(values) var sum float64 for _, v := range values { d := float64(v) - m sum += d * d } return sum / float64(len(values)) } // A uniform sample using Vitter's Algorithm R. // // <http://www.cs.umd.edu/~samir/498/vitter.pdf> type UniformSample struct { count int64 mutex sync.Mutex reservoirSize int values []int64 } // NewUniformSample constructs a new uniform sample with the given reservoir // size. func NewUniformSample(reservoirSize int) Sample { if UseNilMetrics { return NilSample{} } return &UniformSample{ reservoirSize: reservoirSize, values: make([]int64, 0, reservoirSize), } } // Clear clears all samples. func (s *UniformSample) Clear() { s.mutex.Lock() defer s.mutex.Unlock() s.count = 0 s.values = make([]int64, 0, s.reservoirSize) } // Count returns the number of samples recorded, which may exceed the // reservoir size. func (s *UniformSample) Count() int64 { s.mutex.Lock() defer s.mutex.Unlock() return s.count } // Max returns the maximum value in the sample, which may not be the maximum // value ever to be part of the sample. func (s *UniformSample) Max() int64 { s.mutex.Lock() defer s.mutex.Unlock() return SampleMax(s.values) } // Mean returns the mean of the values in the sample. func (s *UniformSample) Mean() float64 { s.mutex.Lock() defer s.mutex.Unlock() return SampleMean(s.values) } // Min returns the minimum value in the sample, which may not be the minimum // value ever to be part of the sample. func (s *UniformSample) Min() int64 { s.mutex.Lock() defer s.mutex.Unlock() return SampleMin(s.values) } // Percentile returns an arbitrary percentile of values in the sample. func (s *UniformSample) Percentile(p float64) float64 { s.mutex.Lock() defer s.mutex.Unlock() return SamplePercentile(s.values, p) } // Percentiles returns a slice of arbitrary percentiles of values in the // sample. func (s *UniformSample) Percentiles(ps []float64) []float64 { s.mutex.Lock() defer s.mutex.Unlock() return SamplePercentiles(s.values, ps) } // Size returns the size of the sample, which is at most the reservoir size. func (s *UniformSample) Size() int { s.mutex.Lock() defer s.mutex.Unlock() return len(s.values) } // Snapshot returns a read-only copy of the sample. func (s *UniformSample) Snapshot() Sample { s.mutex.Lock() defer s.mutex.Unlock() values := make([]int64, len(s.values)) copy(values, s.values) return &SampleSnapshot{ count: s.count, values: values, } } // StdDev returns the standard deviation of the values in the sample. func (s *UniformSample) StdDev() float64 { s.mutex.Lock() defer s.mutex.Unlock() return SampleStdDev(s.values) } // Sum returns the sum of the values in the sample. func (s *UniformSample) Sum() int64 { s.mutex.Lock() defer s.mutex.Unlock() return SampleSum(s.values) } // Update samples a new value. func (s *UniformSample) Update(v int64) { s.mutex.Lock() defer s.mutex.Unlock() s.count++ if len(s.values) < s.reservoirSize { s.values = append(s.values, v) } else { r := rand.Int63n(s.count) if r < int64(len(s.values)) { s.values[int(r)] = v } } } // Values returns a copy of the values in the sample. func (s *UniformSample) Values() []int64 { s.mutex.Lock() defer s.mutex.Unlock() values := make([]int64, len(s.values)) copy(values, s.values) return values } // Variance returns the variance of the values in the sample. func (s *UniformSample) Variance() float64 { s.mutex.Lock() defer s.mutex.Unlock() return SampleVariance(s.values) } // expDecaySample represents an individual sample in a heap. type expDecaySample struct { k float64 v int64 } func newExpDecaySampleHeap(reservoirSize int) *expDecaySampleHeap { return &expDecaySampleHeap{make([]expDecaySample, 0, reservoirSize)} } // expDecaySampleHeap is a min-heap of expDecaySamples. // The internal implementation is copied from the standard library's container/heap type expDecaySampleHeap struct { s []expDecaySample } func (h *expDecaySampleHeap) Clear() { h.s = h.s[:0] } func (h *expDecaySampleHeap) Push(s expDecaySample) { n := len(h.s) h.s = h.s[0 : n+1] h.s[n] = s h.up(n) } func (h *expDecaySampleHeap) Pop() expDecaySample { n := len(h.s) - 1 h.s[0], h.s[n] = h.s[n], h.s[0] h.down(0, n) n = len(h.s) s := h.s[n-1] h.s = h.s[0 : n-1] return s } func (h *expDecaySampleHeap) Size() int { return len(h.s) } func (h *expDecaySampleHeap) Values() []expDecaySample { return h.s } func (h *expDecaySampleHeap) up(j int) { for { i := (j - 1) / 2 // parent if i == j || !(h.s[j].k < h.s[i].k) { break } h.s[i], h.s[j] = h.s[j], h.s[i] j = i } } func (h *expDecaySampleHeap) down(i, n int) { for { j1 := 2*i + 1 if j1 >= n || j1 < 0 { // j1 < 0 after int overflow break } j := j1 // left child if j2 := j1 + 1; j2 < n && !(h.s[j1].k < h.s[j2].k) { j = j2 // = 2*i + 2 // right child } if !(h.s[j].k < h.s[i].k) { break } h.s[i], h.s[j] = h.s[j], h.s[i] i = j } } type int64Slice []int64 func (p int64Slice) Len() int { return len(p) } func (p int64Slice) Less(i, j int) bool { return p[i] < p[j] } func (p int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
{ "pile_set_name": "Github" }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Broadcast } from 'app/model/broadcast.model'; import { Subscription } from 'rxjs'; import { BroadcastStore } from '../../../service/broadcast/broadcast.store'; import { AutoUnsubscribe } from '../../../shared/decorator/autoUnsubscribe'; @Component({ selector: 'app-broadcast-details', templateUrl: './broadcast.details.component.html', styleUrls: ['./broadcast.details.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) @AutoUnsubscribe() export class BroadcastDetailsComponent implements OnDestroy { broadcast: Broadcast; loading = true; _broadcastSub: Subscription; _routeParamsSub: Subscription; constructor(private _broadcastStore: BroadcastStore, private _route: ActivatedRoute, private _cd: ChangeDetectorRef) { this._routeParamsSub = this._route.params.subscribe((params) => { let id = parseInt(params['id'], 10); this._broadcastStore.markAsRead(id) .subscribe(); this.loading = true; this._broadcastSub = this._broadcastStore.getBroadcasts(id) .subscribe((bcs) => { this.broadcast = bcs.get(id); if (this.broadcast) { this.loading = false; } this._cd.markForCheck(); }); }); } ngOnDestroy(): void {} // Should be set to use @AutoUnsubscribe with AOT }
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- $KCODE = "u" unless Object.const_defined? :Encoding $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'rubygems' require 'cgi' require 'enumerator' require 'json' require 'net/https' require 'open-uri' require 'optparse' require 'readline' require 'rubytter' require 'notify' require 'timeout' require 'oauth' module Termtter APP_NAME = 'termtter' require 'termtter/version' require 'termtter/config' require 'termtter/crypt' require 'termtter/default_config' require 'termtter/optparse' require 'termtter/command' require 'termtter/hook' require 'termtter/task' require 'termtter/task_manager' require 'termtter/hookable' require 'termtter/memory_cache' require 'termtter/rubytter_proxy' require 'termtter/client' require 'termtter/api' require 'termtter/system_extensions' require 'termtter/httppool' require 'termtter/event' OptParser.parse!(ARGV) CONF_DIR = File.expand_path('~/.termtter') unless defined? CONF_DIR CONF_FILE = File.join(Termtter::CONF_DIR, 'config') unless defined? CONF_FILE config.token_file = File.join(Termtter::CONF_DIR, config.token_file_name) $:.unshift(CONF_DIR) CONSUMER_KEY = 'eFFLaGJ3M0VMZExvNmtlNHJMVndsQQ==' CONSUMER_SECRET = 'cW8xbW9JT3dyT0NHTmVaMWtGbHpjSk1tN0lReTlJYTl0N0trcW9Fdkhr' end
{ "pile_set_name": "Github" }
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.code_title}</title> <script type="text/javascript" src="../../tiny_mce_popup.js"></script> <script type="text/javascript" src="js/source_editor.js"></script> </head> <body onresize="resizeInputs();" style="display:none; overflow:hidden;" spellcheck="false"> <form name="source" onsubmit="saveContent();return false;" action="#"> <div style="float: left" class="title"><label for="htmlSource">{#advanced_dlg.code_title}</label></div> <div id="wrapline" style="float: right"> <input type="checkbox" name="wraped" id="wraped" onclick="toggleWordWrap(this);" class="wordWrapCode" /><label for="wraped">{#advanced_dlg.code_wordwrap}</label> </div> <br style="clear: both" /> <textarea name="htmlSource" id="htmlSource" rows="15" cols="100" style="width: 100%; height: 100%; font-family: 'Courier New',Courier,monospace; font-size: 12px;" dir="ltr" wrap="off" class="mceFocus"></textarea> <div class="mceActionPanel"> <input type="submit" role="button" name="insert" value="{#update}" id="insert" /> <input type="button" role="button" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" id="cancel" /> </div> </form> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright 2013 LinkedIn, 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 voldemort.routing; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import voldemort.ClusterTestUtils; import voldemort.ServerTestUtils; import voldemort.TestUtils; import voldemort.client.RoutingTier; import voldemort.cluster.Cluster; import voldemort.cluster.Zone; import voldemort.serialization.SerializerDefinition; import voldemort.store.StoreDefinition; import voldemort.store.StoreDefinitionBuilder; import voldemort.store.bdb.BdbStorageConfiguration; import voldemort.store.slop.strategy.HintedHandoffStrategyType; import com.google.common.collect.Lists; // TODO: Break this test into part that tests BaseStoreRoutingPlan and // StoreRoutingPlan. public class StoreRoutingPlanTest { // plan for 2 zones BaseStoreRoutingPlan zzBaseRoutingPlan; BaseStoreRoutingPlan nonZonedBaseRoutingPlan; BaseStoreRoutingPlan z1z3BaseRoutingPlan; // plan for 3 zones BaseStoreRoutingPlan zzzBaseRoutingPlan; BaseStoreRoutingPlan z1z3z5BaseRoutingPlan; // plan for 2 zones StoreRoutingPlan zzStoreRoutingPlan; StoreRoutingPlan nonZonedStoreRoutingPlan; StoreRoutingPlan z1z3StoreRoutingPlan; // plan for 3 zones StoreRoutingPlan zzzStoreRoutingPlan; StoreRoutingPlan z1z3z5StoreRoutingPlan; public StoreRoutingPlanTest() {} @Before public void setup() { Cluster nonZonedCluster = ServerTestUtils.getLocalCluster(3, new int[] { 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000 }, new int[][] { { 0 }, { 1, 3 }, { 2 } }); StoreDefinition nonZoned211StoreDef = new StoreDefinitionBuilder().setName("non-zoned") .setType(BdbStorageConfiguration.TYPE_NAME) .setKeySerializer(new SerializerDefinition("string")) .setValueSerializer(new SerializerDefinition("string")) .setRoutingPolicy(RoutingTier.CLIENT) .setRoutingStrategyType(RoutingStrategyType.CONSISTENT_STRATEGY) .setReplicationFactor(2) .setPreferredReads(1) .setRequiredReads(1) .setPreferredWrites(1) .setRequiredWrites(1) .build(); nonZonedBaseRoutingPlan = new BaseStoreRoutingPlan(nonZonedCluster, nonZoned211StoreDef); nonZonedStoreRoutingPlan = new StoreRoutingPlan(nonZonedCluster, nonZoned211StoreDef); int[] dummyZonedPorts = new int[] { 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000 }; Cluster zzCluster = ServerTestUtils.getLocalZonedCluster(6, 2, new int[] { 0, 0, 0, 1, 1, 1 }, new int[][] { { 0 }, { 1, 6 }, { 2 }, { 3 }, { 4, 7 }, { 5 } }, dummyZonedPorts); HashMap<Integer, Integer> zrfRWStoreWithReplication = new HashMap<Integer, Integer>(); zrfRWStoreWithReplication.put(0, 2); zrfRWStoreWithReplication.put(1, 2); StoreDefinition zz211StoreDef = new StoreDefinitionBuilder().setName("zoned") .setType(BdbStorageConfiguration.TYPE_NAME) .setKeySerializer(new SerializerDefinition("string")) .setValueSerializer(new SerializerDefinition("string")) .setRoutingPolicy(RoutingTier.CLIENT) .setRoutingStrategyType(RoutingStrategyType.ZONE_STRATEGY) .setReplicationFactor(4) .setPreferredReads(1) .setRequiredReads(1) .setPreferredWrites(1) .setRequiredWrites(1) .setZoneCountReads(0) .setZoneCountWrites(0) .setZoneReplicationFactor(zrfRWStoreWithReplication) .setHintedHandoffStrategy(HintedHandoffStrategyType.PROXIMITY_STRATEGY) .build(); zzBaseRoutingPlan = new BaseStoreRoutingPlan(zzCluster, zz211StoreDef); zzStoreRoutingPlan = new StoreRoutingPlan(zzCluster, zz211StoreDef); Cluster zzzCluster = ServerTestUtils.getLocalZonedCluster(9, 3, new int[] { 0, 0, 0, 1, 1, 1, 2, 2, 2 }, new int[][] { { 0 }, { 10 }, { 1, 2 }, { 3 }, { 4 }, { 6 }, { 5, 7 }, { 9 }, { 8 } }, new int[] { 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000, 1000, 2000, 3000 }); HashMap<Integer, Integer> zoneRep211 = new HashMap<Integer, Integer>(); zoneRep211.put(0, 2); zoneRep211.put(1, 2); zoneRep211.put(2, 2); StoreDefinition zzz211StoreDef = new StoreDefinitionBuilder().setName("zzz") .setType(BdbStorageConfiguration.TYPE_NAME) .setKeySerializer(new SerializerDefinition("string")) .setValueSerializer(new SerializerDefinition("string")) .setRoutingPolicy(RoutingTier.CLIENT) .setRoutingStrategyType(RoutingStrategyType.ZONE_STRATEGY) .setReplicationFactor(6) .setPreferredReads(1) .setRequiredReads(1) .setPreferredWrites(1) .setRequiredWrites(1) .setZoneCountReads(0) .setZoneCountWrites(0) .setZoneReplicationFactor(zoneRep211) .setHintedHandoffStrategy(HintedHandoffStrategyType.PROXIMITY_STRATEGY) .build(); zzzBaseRoutingPlan = new BaseStoreRoutingPlan(zzzCluster, zzz211StoreDef); zzzStoreRoutingPlan = new StoreRoutingPlan(zzzCluster, zzz211StoreDef); } @Before public void setupNonContiguous() { Cluster z1z3Current = ClusterTestUtils.getZ1Z3ClusterWithNonContiguousNodeIds(); HashMap<Integer, Integer> zoneRep211 = new HashMap<Integer, Integer>(); zoneRep211.put(1, 2); zoneRep211.put(3, 2); StoreDefinition z1z3211StoreDef = new StoreDefinitionBuilder().setName("z1z3211") .setType(BdbStorageConfiguration.TYPE_NAME) .setKeySerializer(new SerializerDefinition("string")) .setValueSerializer(new SerializerDefinition("string")) .setRoutingPolicy(RoutingTier.CLIENT) .setRoutingStrategyType(RoutingStrategyType.ZONE_STRATEGY) .setReplicationFactor(4) .setPreferredReads(1) .setRequiredReads(1) .setPreferredWrites(1) .setRequiredWrites(1) .setZoneCountReads(0) .setZoneCountWrites(0) .setZoneReplicationFactor(zoneRep211) .setHintedHandoffStrategy(HintedHandoffStrategyType.PROXIMITY_STRATEGY) .build(); z1z3BaseRoutingPlan = new BaseStoreRoutingPlan(z1z3Current, z1z3211StoreDef); z1z3StoreRoutingPlan = new StoreRoutingPlan(z1z3Current, z1z3211StoreDef); // 3 zones Cluster z1z3z5Current = ClusterTestUtils.getZ1Z3Z5ClusterWithNonContiguousNodeIds(); HashMap<Integer, Integer> zoneRep3zones211 = new HashMap<Integer, Integer>(); zoneRep3zones211.put(1, 2); zoneRep3zones211.put(3, 2); zoneRep3zones211.put(5, 2); StoreDefinition z1z3z5211StoreDef = new StoreDefinitionBuilder().setName("z1z3z5211") .setType(BdbStorageConfiguration.TYPE_NAME) .setKeySerializer(new SerializerDefinition("string")) .setValueSerializer(new SerializerDefinition("string")) .setRoutingPolicy(RoutingTier.CLIENT) .setRoutingStrategyType(RoutingStrategyType.ZONE_STRATEGY) .setReplicationFactor(6) .setPreferredReads(1) .setRequiredReads(1) .setPreferredWrites(1) .setRequiredWrites(1) .setZoneCountReads(0) .setZoneCountWrites(0) .setZoneReplicationFactor(zoneRep3zones211) .setHintedHandoffStrategy(HintedHandoffStrategyType.PROXIMITY_STRATEGY) .build(); z1z3z5BaseRoutingPlan = new BaseStoreRoutingPlan(z1z3z5Current, z1z3z5211StoreDef); z1z3z5StoreRoutingPlan = new StoreRoutingPlan(z1z3z5Current, z1z3z5211StoreDef); } @Test public void testZZStoreRoutingPlan() { HashMap<Integer, List<byte[]>> samplePartitionKeysMap = TestUtils.createPartitionsKeys(zzStoreRoutingPlan, 1); assertEquals("Node 1 does not contain p5?", (Integer) 6, zzStoreRoutingPlan.getNodesPartitionIdForKey(1, samplePartitionKeysMap.get(5) .get(0))); assertEquals("Node 4 does not contain p5?", (Integer) 7, zzStoreRoutingPlan.getNodesPartitionIdForKey(4, samplePartitionKeysMap.get(5) .get(0))); assertEquals("Replication list does not match up", Lists.newArrayList(0, 1, 3, 4), zzStoreRoutingPlan.getReplicationNodeList(0)); assertEquals("Zone replica type should be 1", 1, zzBaseRoutingPlan.getZoneNAry(0, 0, samplePartitionKeysMap.get(6).get(0))); assertEquals("Zone replica type should be 0", 0, zzBaseRoutingPlan.getZoneNAry(0, 1, samplePartitionKeysMap.get(6).get(0))); assertEquals("Zone replica type should be 1", 1, zzBaseRoutingPlan.getZoneNAry(1, 3, samplePartitionKeysMap.get(7).get(0))); assertEquals("Zone replica type should be 0", 0, zzBaseRoutingPlan.getZoneNAry(1, 4, samplePartitionKeysMap.get(7).get(0))); assertEquals("Replica owner should be 1", 1, zzBaseRoutingPlan.getNodeIdForZoneNary(0, 1, samplePartitionKeysMap.get(2) .get(0))); assertEquals("Replica owner should be 1", 1, zzBaseRoutingPlan.getNodeIdForZoneNary(0, 0, samplePartitionKeysMap.get(3) .get(0))); assertEquals("Replica owner should be 4", 4, zzBaseRoutingPlan.getNodeIdForZoneNary(1, 1, samplePartitionKeysMap.get(1) .get(0))); assertEquals("Replica owner should be 3", 3, zzBaseRoutingPlan.getNodeIdForZoneNary(1, 0, samplePartitionKeysMap.get(2) .get(0))); assertEquals("Does Zone 1 have a replica", true, zzzStoreRoutingPlan.zoneNAryExists(1, 0, 1)); } @Test public void testZ1Z3StoreRoutingPlan() { HashMap<Integer, List<byte[]>> samplePartitionKeysMap = TestUtils.createPartitionsKeys(z1z3StoreRoutingPlan, 1); assertEquals("Node 3 does not contain p6?", (Integer) 6, z1z3StoreRoutingPlan.getNodesPartitionIdForKey(3, samplePartitionKeysMap.get(6) .get(0))); assertEquals("Node 4 does not contain p10?", (Integer) 10, z1z3StoreRoutingPlan.getNodesPartitionIdForKey(4, samplePartitionKeysMap.get(10) .get(0))); assertEquals("Replication list does not match up", Lists.newArrayList(3, 4, 9, 10), z1z3StoreRoutingPlan.getReplicationNodeList(0)); assertEquals("Zone replica type should be 0", 0, z1z3BaseRoutingPlan.getZoneNAry(1, 3, samplePartitionKeysMap.get(6).get(0))); assertEquals("Zone replica type should be 1", 1, z1z3BaseRoutingPlan.getZoneNAry(1, 5, samplePartitionKeysMap.get(6).get(0))); assertEquals("Zone replica type should be 1", 1, z1z3BaseRoutingPlan.getZoneNAry(1, 3, samplePartitionKeysMap.get(7).get(0))); assertEquals("Zone replica type should be 0", 0, z1z3BaseRoutingPlan.getZoneNAry(1, 5, samplePartitionKeysMap.get(7).get(0))); assertEquals("Replica owner should be 3", 3, z1z3BaseRoutingPlan.getNodeIdForZoneNary(1, 1, samplePartitionKeysMap.get(2) .get(0))); assertEquals("Replica owner should be 9", 5, z1z3BaseRoutingPlan.getNodeIdForZoneNary(1, 1, samplePartitionKeysMap.get(3) .get(0))); assertEquals("Replica owner should be 5", 5, z1z3BaseRoutingPlan.getNodeIdForZoneNary(1, 1, samplePartitionKeysMap.get(1) .get(0))); assertEquals("Replica owner should be 4", 4, zzBaseRoutingPlan.getNodeIdForZoneNary(1, 0, samplePartitionKeysMap.get(2) .get(0))); } @Test public void testZZZStoreRoutingPlan() { HashMap<Integer, List<byte[]>> samplePartitionKeysMap = TestUtils.createPartitionsKeys(zzzStoreRoutingPlan, 1); assertEquals("Node 1 does not contain p8?", (Integer) 10, zzzStoreRoutingPlan.getNodesPartitionIdForKey(1, samplePartitionKeysMap.get(8).get(0))); assertEquals("Node 3 does not contain p1?", (Integer) 3, zzzStoreRoutingPlan.getNodesPartitionIdForKey(3, samplePartitionKeysMap.get(1).get(0))); assertEquals("Replication list does not match up", Lists.newArrayList(0, 2, 3, 4, 6, 8), zzzStoreRoutingPlan.getReplicationNodeList(0)); assertEquals("Replication list does not match up", Lists.newArrayList(3, 4, 6, 8, 1, 0), zzzStoreRoutingPlan.getReplicationNodeList(3)); assertEquals("Zone replica type should be 0", 0, zzzBaseRoutingPlan.getZoneNAry(0, 1, samplePartitionKeysMap.get(6).get(0))); assertEquals("Zone replica type should be 0 in zone 2", 0, zzzBaseRoutingPlan.getZoneNAry(2, 6, samplePartitionKeysMap.get(6).get(0))); assertEquals("Replica owner should be 3", 3, zzzBaseRoutingPlan.getNodeIdForZoneNary(1, 0, samplePartitionKeysMap.get(1) .get(0))); assertEquals("Replica secondary should be 8", 8, zzzBaseRoutingPlan.getNodeIdForZoneNary(2, 1, samplePartitionKeysMap.get(0) .get(0))); assertEquals("Does Zone 2 have a replica", true, zzzStoreRoutingPlan.zoneNAryExists(2, 1, 0)); } @Test public void testZ1Z3Z5StoreRoutingPlan() { HashMap<Integer, List<byte[]>> samplePartitionKeysMap = TestUtils.createPartitionsKeys(z1z3z5StoreRoutingPlan, 1); assertEquals("Node 3 does not contain p8?", (Integer) 9, z1z3z5StoreRoutingPlan.getNodesPartitionIdForKey(3, samplePartitionKeysMap.get(8).get(0))); assertEquals("Node 5 does not contain p1?", (Integer) 2, z1z3z5StoreRoutingPlan.getNodesPartitionIdForKey(5, samplePartitionKeysMap.get(1).get(0))); assertEquals("Replication list does not match up", Lists.newArrayList(3, 4, 9, 10, 15, 16 ), z1z3z5StoreRoutingPlan.getReplicationNodeList(0)); assertEquals("Replication list does not match up", Lists.newArrayList(9, 10, 3, 5, 15, 16), z1z3z5StoreRoutingPlan.getReplicationNodeList(3)); assertEquals("Zone replica type should be 0", 0, z1z3z5BaseRoutingPlan.getZoneNAry(1, 3, samplePartitionKeysMap.get(6).get(0))); assertEquals("Zone replica type should be 1 in zone 1", 1, z1z3z5BaseRoutingPlan.getZoneNAry(1, 5, samplePartitionKeysMap.get(6).get(0))); assertEquals("Replica owner should be 4", 4, z1z3z5BaseRoutingPlan.getNodeIdForZoneNary(1, 0, samplePartitionKeysMap.get(1) .get(0))); assertEquals("Replica secondary should be 10", 10, z1z3z5BaseRoutingPlan.getNodeIdForZoneNary(3, 1, samplePartitionKeysMap.get(0) .get(0))); assertEquals("Does Zone 3 have a replica", true, z1z3z5StoreRoutingPlan.zoneNAryExists(3, 1, 0)); } @Test public void testNonZonedStoreRoutingPlan() { HashMap<Integer, List<byte[]>> samplePartitionKeysMap = TestUtils.createPartitionsKeys(nonZonedStoreRoutingPlan, 1); assertEquals("Node 1 does not contain p2 as secondary?", (Integer) 3, nonZonedStoreRoutingPlan.getNodesPartitionIdForKey(1, samplePartitionKeysMap.get(2) .get(0))); assertEquals("Replication list does not match up", Lists.newArrayList(1, 2), nonZonedStoreRoutingPlan.getReplicationNodeList(1)); assertEquals("Zone replica type should be 1", 1, nonZonedBaseRoutingPlan.getZoneNAry(Zone.DEFAULT_ZONE_ID, 2, samplePartitionKeysMap.get(1).get(0))); assertEquals("Zone replica type should be 0", 0, nonZonedBaseRoutingPlan.getZoneNAry(Zone.DEFAULT_ZONE_ID, 1, samplePartitionKeysMap.get(3).get(0))); assertEquals("Replica owner should be 2", 2, nonZonedBaseRoutingPlan.getNodeIdForZoneNary(Zone.DEFAULT_ZONE_ID, 1, samplePartitionKeysMap.get(1).get(0))); assertEquals("Replica owner should be 1", 1, nonZonedBaseRoutingPlan.getNodeIdForZoneNary(Zone.DEFAULT_ZONE_ID, 0, samplePartitionKeysMap.get(3).get(0))); } @After public void teardown() { } }
{ "pile_set_name": "Github" }
<enum-method-mappings> <!-- This example changes the Java method: android.support.v4.app.Fragment.SavedState.writeToParcel (int flags) to be: android.support.v4.app.Fragment.SavedState.writeToParcel (Android.OS.ParcelableWriteFlags flags) when bound in C#. <mapping jni-class="android/support/v4/app/Fragment.SavedState"> <method jni-name="writeToParcel" parameter="flags" clr-enum-type="Android.OS.ParcelableWriteFlags" /> </mapping> --> </enum-method-mappings>
{ "pile_set_name": "Github" }
// Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. //szv#4 S4163 #include <Interface_IntList.ixx> // Organisation des donnees : // theents vaut : 0 pas de reference // > 0 : une reference, dont voici la valeur; pas de liste // < 0 : une liste de references; on stocke <rank>, elle debute a <rank>+1 // la liste est dans therefs et est ainsi constitue : // liste de valeurs negatives, se terminant pas une valeur positive : // de <rank>+1 a <rank>+nb , <rank>+1 a <rank>+nb-1 sont negatifs et // <rank>+nb est negatif // un zero signifie : place libre // Pre-reservation : <rank> note le nombre courant, en positif strict // Il faut alors l incrementer a chaque ajout // Usage contextuel, il faut demander SetNumber(num < 0) pour exploiter cette // info et Add(ref < 0) pour la gerer. // Si elle n est pas presente, on bascule en mode courant Interface_IntList::Interface_IntList () { thenbe = thenbr = thenum = thecount = therank = 0; } Interface_IntList::Interface_IntList (const Standard_Integer nbe) { Initialize (nbe); } Interface_IntList::Interface_IntList (const Interface_IntList& other, const Standard_Boolean copied) { thenbe = other.NbEntities(); thenum = thecount = therank = 0; //szv#4:S4163:12Mar99 initialization needed other.Internals (thenbr, theents, therefs); if (copied) { Standard_Integer i; Handle(TColStd_HArray1OfInteger) ents = new TColStd_HArray1OfInteger (0,thenbe); ents->Init(0); for (i = 1; i <= thenbe; i ++) ents->SetValue (i,theents->Value(i)); Handle(TColStd_HArray1OfInteger) refs = new TColStd_HArray1OfInteger (0,thenbr); refs->Init(0); for (i = 1; i <= thenbr; i ++) refs->SetValue (i,therefs->Value(i)); theents = ents; therefs = refs; } SetNumber (other.Number()); } void Interface_IntList::Initialize (const Standard_Integer nbe) { thenbe = nbe; thenbr = thenum = thecount = therank = 0; theents = new TColStd_HArray1OfInteger (0,nbe); theents->Init(0); } void Interface_IntList::Internals (Standard_Integer& nbrefs, Handle(TColStd_HArray1OfInteger)& ents, Handle(TColStd_HArray1OfInteger)& refs) const { nbrefs = thenbr; ents = theents; refs = therefs; } Standard_Integer Interface_IntList::NbEntities () const { return thenbe; } void Interface_IntList::SetNbEntities (const Standard_Integer nbe) { if (nbe <= theents->Upper()) return; Standard_Integer i; Handle(TColStd_HArray1OfInteger) ents = new TColStd_HArray1OfInteger (0,nbe); ents->Init(0); for (i = 1; i <= thenbe; i ++) ents->SetValue (i,theents->Value(i)); theents = ents; thenbe = nbe; } void Interface_IntList::SetNumber (const Standard_Integer number) { // Usage en pre-reservation : a demander specifiquement ! -> optimisation // <preres> verifie que la pre-reservation est valide if (number < 0) { if (thenum == -number || number < - thenbe) return; Standard_Boolean preres = Standard_True; thenum = -number; Standard_Integer val = theents->Value (thenum); if (val == 0) { thecount = 0; therank = 0; } else if (val > 0) { thecount = 1; therank = -1; } if (val < -1) { therank = -val; thecount = therefs->Value(therank); if (thecount <= 0) preres = Standard_False; } if (preres) return; } // Usage courant. La suite en usage courant ou si pas de pre-reservation else if (number > 0) { if (thenum == number || number > thenbe) return; thenum = number; } else return; Standard_Integer val = theents->Value(thenum); if (val == 0) { thecount = 0; therank = 0; } else if (val > 0) { thecount = 1; therank = -1; } else if (val < -1) { therank = - val; thecount = 0; if (therefs->Value(therank+1) == 0) thecount = - therefs->Value(therank); else { for (Standard_Integer j = 1; ; j ++) { val = therefs->Value (therank+j); if (val >= 0) break; thecount ++; } if (val > 0) thecount ++; } } else { thecount = 0; therank = -1; } // val == -1 reste } Standard_Integer Interface_IntList::Number () const { return thenum; } Interface_IntList Interface_IntList::List (const Standard_Integer number, const Standard_Boolean copied) const { Interface_IntList alist (*this,copied); alist.SetNumber (number); return alist; } void Interface_IntList::SetRedefined (const Standard_Boolean mode) { if (!NbEntities() || thenum == 0) return; Standard_Integer val = theents->Value(thenum); if (val < -1) return; else if (mode) { if (val == 0) theents->SetValue (thenum,-1); else if (val > 0) { Reservate (2); theents->SetValue (thenum, -thenbr); therefs->SetValue (thenbr+1, val); thenbr ++; } } else if (!mode) { if (val == -1) theents->SetValue (thenum,0); else if (therefs->Value (therank+1) >= 0) { theents->SetValue (thenum, therefs->Value(therank+1)); if (thenbr == therank+1) thenbr --; } } } void Interface_IntList::Reservate (const Standard_Integer count) { // Reservate (-count) = Reservate (count) + allocation sur entite courante + 1 if (count < 0) { Reservate(-count-1); if (thenum == 0) return; thenbr ++; therefs->SetValue (thenbr,0); // contiendra le nombre ... therank = thenbr; theents->SetValue(thenum, -thenbr); thenbr -= count; return; } Standard_Integer up, oldup = 0; if (thenbr == 0) { // c-a-d pas encore allouee ... up = thenbe/2+1; if (up < 2) up = 2; if (up < count) up = count*3/2; therefs = new TColStd_HArray1OfInteger (0,up); therefs->Init(0); thenbr = 2; // on commence apres (commodite d adressage) } oldup = therefs->Upper(); if (thenbr + count < oldup) return; // OK up = oldup*3/2+count; if (up < 2) up = 2; Handle(TColStd_HArray1OfInteger) refs = new TColStd_HArray1OfInteger (0,up); refs->Init(0); for (Standard_Integer i = 1; i <= oldup; i ++) refs->SetValue (i,therefs->Value(i)); therefs = refs; } void Interface_IntList::Add (const Standard_Integer ref) { if (thenum == 0) return; // ref < 0 : pre-reservation if (ref < 0) { Add(-ref); if (therank <= 0) return; if (therefs->Value(therank) >= 0) therefs->SetValue (therank, thecount); return; } if (therank == 0) { theents->SetValue (thenum,ref); thecount = 1; therank = -1; } else if (therank < 0) { Reservate (2); therank = thenbr; Standard_Integer val = theents->Value(thenum); theents->SetValue (thenum, -thenbr); if (thecount == 1) { therefs->SetValue (thenbr+1, -val); thenbr ++; } therefs->SetValue (thenbr+1, ref); thenbr ++; thecount ++; } else if (thenbr == therank+thecount) { // place libre en fin therefs->SetValue (thenbr, -therefs->Value(thenbr)); therefs->SetValue (thenbr+1, ref); thenbr ++; thecount ++; } else if (therefs->Value(therank+thecount+1) == 0) { // place libre apres therefs->SetValue (therank+thecount, -therefs->Value(therank+thecount)); therefs->SetValue (therank+thecount+1, ref); thecount ++; } else { // recopier plus loin ! Reservate (thecount+2); Standard_Integer rank = therank; therank = thenbr; theents->SetValue (thenum,-therank); for (Standard_Integer i = 1; i < thecount; i ++) { therefs->SetValue (therank+i, therefs->Value(rank+i)); therefs->SetValue (rank+i,0); } therefs->SetValue (therank+thecount, -therefs->Value(rank+thecount)); therefs->SetValue (rank+thecount,0); therefs->SetValue (therank+thecount+1,ref); thecount ++; thenbr = therank + thecount + 1; } } Standard_Integer Interface_IntList::Length () const { return thecount; } Standard_Boolean Interface_IntList::IsRedefined (const Standard_Integer num) const { Standard_Integer n = (num == 0 ? thenum : num); if (!NbEntities() || n == 0) return Standard_False; if (theents->Value(n) < 0) return Standard_True; return Standard_False; } Standard_Integer Interface_IntList::Value (const Standard_Integer num) const { if (thenum == 0) return 0; if (num <= 0 || num > thecount) return 0; if (thecount == 0) return 0; if (therank <= 0) return theents->Value(thenum); Standard_Integer val = therefs->Value (therank+num); if (val < 0) return -val; return val; } Standard_Boolean Interface_IntList::Remove (const Standard_Integer) { return Standard_False; // not yet implemented } void Interface_IntList::Clear () { if (thenbr == 0) return; // deja clear Standard_Integer i,low,up; low = theents->Lower(); up = theents->Upper(); for (i = low; i <= up; i ++) theents->SetValue (i,0); thenbr = 0; if (therefs.IsNull()) return; low = therefs->Lower(); up = therefs->Upper(); for (i = low; i <= up; i ++) therefs->SetValue (i,0); } void Interface_IntList::AdjustSize (const Standard_Integer margin) { Standard_Integer i, up = theents->Upper(); if (up > thenbe) { Handle(TColStd_HArray1OfInteger) ents = new TColStd_HArray1OfInteger (0,thenbe); ents->Init(0); for (i = 1; i <= thenbe; i ++) ents->SetValue (i,theents->Value(i)); theents = ents; } if (thenbr == 0) Reservate (margin); else { up = therefs->Upper(); if (up >= thenbr && up <= thenbr + margin) return; Handle(TColStd_HArray1OfInteger) refs = new TColStd_HArray1OfInteger (0,thenbr+margin); refs->Init(0); for (i = 1; i <= thenbr; i ++) refs->SetValue (i,therefs->Value(i)); therefs = refs; } }
{ "pile_set_name": "Github" }
include/group_replication.inc [rpl_server_count=3] Warnings: Note #### Sending passwords in plain text without SSL/TLS is extremely insecure. Note #### Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information. [connection server1] # 1. Bootstrap group on server 1 [connection server1] include/start_and_bootstrap_group_replication.inc # 2. Join server2 to group [connection server_2] include/start_group_replication.inc # 3. Set group_replication_consistency to BEFORE_ON_PRIMARY_FAILOVER on # global scope, so new connections have it SET @@GLOBAL.group_replication_consistency= BEFORE_ON_PRIMARY_FAILOVER; # 4. On server 2 create a slave connection to server 3 CHANGE MASTER TO MASTER_HOST='localhost', MASTER_USER='root', MASTER_PORT=SERVER_3_PORT for channel 'ch3_2'; Warnings: Note 1759 Sending passwords in plain text without SSL/TLS is extremely insecure. Note 1760 Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information. include/start_slave.inc [FOR CHANNEL 'ch3_2'] SET @@GLOBAL.group_replication_consistency= EVENTUAL; # 5. Create table t1 an t2 on server3 and replicate to group [connection server3] CREATE TABLE test.t1 (a int primary key); CREATE TABLE test.t2 (a int primary key); include/sync_slave_sql_with_master.inc include/sync_slave_sql_with_master.inc # 6. Lock tables t1 to hold primary election [connection server_2] LOCK TABLES t1 READ; # 7. Execute transaction on group [connection server1] INSERT INTO t1 VALUES (1); # 8. Server2 will certify transaction but won't apply due lock tables [connection server2] # 9. Execute group_replication_switch_to_single_primary_mode to appoint # server2 as primary on single primary mode group [connection server1] SELECT group_replication_switch_to_single_primary_mode("MEMBER2_UUID"); # 10. Validate that primary election is executing [connection server2] # 11. A read statement to new primary will be put on hold until all # backlog's are applied SET @@SESSION.group_replication_consistency= BEFORE_ON_PRIMARY_FAILOVER; SELECT COUNT(*)=1 FROM t1 WHERE a = 1; # 12. Validate statement is on hold [connection server_2] # 13. Statement executed on server3 [connection server3] INSERT INTO t2 VALUES (1); # 14. Transaction from server3 will be held until backlog is applied [connection server_2_1] # 15. Table t2 will be empty until backlog is applied include/assert.inc ['There are no values in table t2'] # 16. UNLOCK tables to allow backlog to be applied [connection server_2] UNLOCK TABLES; # 17. Reap with success read of last value inserted on group [connection server2] COUNT(*)=1 1 SET @@SESSION.group_replication_consistency= DEFAULT; # 18. Reap with success execution of set as primary server2 [connection server1] group_replication_switch_to_single_primary_mode("MEMBER2_UUID") Mode switched to single-primary successfully. # 19. Server2 applied all backlog, table t2 has the data # 20. Cleanup [connection server3] DROP TABLE t1; DROP TABLE t2; include/sync_slave_sql_with_master.inc [connection server3] include/sync_slave_sql_with_master.inc [connection server2] SET @@GLOBAL.group_replication_consistency= DEFAULT; STOP SLAVE FOR CHANNEL 'ch3_2'; RESET SLAVE ALL FOR CHANNEL 'ch3_2'; [connection server3] RESET MASTER; include/group_replication_end.inc
{ "pile_set_name": "Github" }
framework module BubbleTransition { umbrella header "BubbleTransition-umbrella.h" export * module * { export * } }
{ "pile_set_name": "Github" }
a = "http://www.google.com?search=noprivacy" b = "http://www.google.com?search=noprivacy"
{ "pile_set_name": "Github" }
<section id="box-contact-us" class="box"> <div class="row"> <div class="col-md-6"> <h1><?php echo language::translate('title_contact_us', 'Contact Us'); ?></h1> <?php echo functions::form_draw_form_begin('contact_form', 'post'); ?> <div class="form-group"> <label><?php echo language::translate('title_name', 'Name'); ?></label> <?php echo functions::form_draw_text_field('name', true, 'required="required"'); ?> </div> <div class="form-group"> <label><?php echo language::translate('title_email_address', 'Email Address'); ?></label> <?php echo functions::form_draw_email_field('email', true, 'required="required"'); ?> </div> <div class="form-group"> <label><?php echo language::translate('title_subject', 'Subject'); ?></label> <?php echo functions::form_draw_text_field('subject', true, 'required="required"'); ?> </div> <div class="form-group"> <label><?php echo language::translate('title_message', 'Message'); ?></label> <?php echo functions::form_draw_textarea('message', true, 'required="required" style="height: 250px;"'); ?> </div> <?php if (settings::get('captcha_enabled')) { ?> <div class="row"> <div class="form-group col-md-6"> <label><?php echo language::translate('title_captcha', 'CAPTCHA'); ?></label> <?php echo functions::form_draw_captcha_field('captcha', 'contact_us', 'required="required"'); ?> </div> </div> <?php } ?> <p><?php echo functions::form_draw_button('send', language::translate('title_send', 'Send'), 'submit', 'style="font-weight: bold;"'); ?></p> <?php echo functions::form_draw_form_end(); ?> </div> <div class="col-md-6"> <h2><?php echo language::translate('title_contact_details', 'Contact Details'); ?></h2> <p class="address"><?php echo nl2br(settings::get('store_postal_address')); ?></p> <?php if (settings::get('store_phone')) { ?><p class="phone"><?php echo functions::draw_fonticon('fa-phone'); ?> <a href="tel:<?php echo settings::get('store_phone'); ?>"><?php echo settings::get('store_phone'); ?></a></p><?php } ?> <p class="email"><?php echo functions::draw_fonticon('fa-envelope'); ?> <a href="mailto:<?php echo settings::get('store_email'); ?>"><?php echo settings::get('store_email'); ?></a></p> </div> </div> </section>
{ "pile_set_name": "Github" }
package strava import ( "encoding/json" "errors" "strings" "time" "github.com/markbates/goth" ) // Session stores data during the auth process with Strava. type Session struct { AuthURL string AccessToken string RefreshToken string ExpiresAt time.Time } // GetAuthURL will return the URL set by calling the `BeginAuth` function on the Strava provider. func (s Session) GetAuthURL() (string, error) { if s.AuthURL == "" { return "", errors.New(goth.NoAuthUrlErrorMessage) } return s.AuthURL, nil } // Authorize the session with Strava and return the access token to be stored for future use. func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) { p := provider.(*Provider) token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code")) if err != nil { return "", err } if !token.Valid() { return "", errors.New("Invalid token received from provider") } s.AccessToken = token.AccessToken s.RefreshToken = token.RefreshToken s.ExpiresAt = token.Expiry return token.AccessToken, err } // Marshal the session into a string func (s Session) Marshal() string { b, _ := json.Marshal(s) return string(b) } func (s Session) String() string { return s.Marshal() } // UnmarshalSession will unmarshal a JSON string into a session. func (p *Provider) UnmarshalSession(data string) (goth.Session, error) { s := &Session{} err := json.NewDecoder(strings.NewReader(data)).Decode(s) return s, err }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <ValueSet xmlns="http://hl7.org/fhir"> <meta> <profile value="http://hl7.org/fhir/StructureDefinition/shareablevalueset"/> </meta> <url value="http://hl7.org/fhir/ValueSet/medication-usage-status"/> <name value="MedicationUsage Status Codes"/> <status value="draft"/> <publisher value="FHIR Project team"/> <contact> <telecom> <system value="url"/> <value value="http://hl7.org/fhir"/> </telecom> </contact> <description value="MedicationUsage Status Codes"/> <compose> <include> <system value="http://hl7.org/fhir/CodeSystem/medication-usage-status"/> </include> </compose> </ValueSet>
{ "pile_set_name": "Github" }
#!/usr/bin/env ruby # This is a small script to illustrate how previous results get wiped out by forking # this has implications of forking processes like Resque... # this in the end would cause coverage.array_diff # with previous results to add NEGATIVE code hits to the stored Coverage # which in turn causes all sorts of crazy issues. # # ruby test/benchmarks/coverage_fork.rb # in parent before fork # {"/Users/danmayer/projects/coverband/test/dog.rb"=>[nil, nil, 1, 1, 2, nil, nil]} # in child after fork # {"/Users/danmayer/projects/coverband/test/dog.rb"=>[nil, nil, 0, 0, 0, nil, nil]} # now triggering hits # {"/Users/danmayer/projects/coverband/test/dog.rb"=>[nil, nil, 0, 0, 3, nil, nil]} # # I believe this might be related to CoW and GC... not sure # http://patshaughnessy.net/2012/3/23/why-you-should-be-excited-about-garbage-collection-in-ruby-2-0 # # NOTE: That the child now has 0 hits where previously method definitions had 1 # this causes all sorts of bad things to happen. require 'coverage' Coverage.start load './test/dog.rb' Dog.new.bark Dog.new.bark puts 'in parent before fork' puts Coverage.peek_result fork do puts 'in child after fork' puts Coverage.peek_result puts 'now triggering hits' Dog.new.bark Dog.new.bark Dog.new.bark puts Coverage.peek_result end
{ "pile_set_name": "Github" }
{ "_from": "jsprim@^1.2.2", "_id": "jsprim@1.4.1", "_inBundle": false, "_integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", "_location": "/jsprim", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "jsprim@^1.2.2", "name": "jsprim", "escapedName": "jsprim", "rawSpec": "^1.2.2", "saveSpec": null, "fetchSpec": "^1.2.2" }, "_requiredBy": [ "/http-signature" ], "_resolved": "https://registry.npm.taobao.org/jsprim/download/jsprim-1.4.1.tgz", "_shasum": "313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2", "_spec": "jsprim@^1.2.2", "_where": "E:\\校园二手书新版\\cloudfunctions\\pay\\node_modules\\http-signature", "bugs": { "url": "https://github.com/joyent/node-jsprim/issues" }, "bundleDependencies": false, "dependencies": { "assert-plus": "1.0.0", "extsprintf": "1.3.0", "json-schema": "0.2.3", "verror": "1.10.0" }, "deprecated": false, "description": "utilities for primitive JavaScript types", "engines": [ "node >=0.6.0" ], "homepage": "https://github.com/joyent/node-jsprim#readme", "license": "MIT", "main": "./lib/jsprim.js", "name": "jsprim", "repository": { "type": "git", "url": "git://github.com/joyent/node-jsprim.git" }, "version": "1.4.1" }
{ "pile_set_name": "Github" }
<?php require_once 'common.php'; echo '<?xml version="1.0" encoding="UTF-8" ?>'; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>HTML Purifier Preserve YouTube Smoketest</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>HTML Purifier Preserve YouTube Smoketest</h1> <?php $string = '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/BdU--T8rLns"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/BdU--T8rLns" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object> <object width="416" height="337"><param name="movie" value="http://www.youtube.com/cp/vjVQa1PpcFNbP_fag8PvopkXZyiXyT0J8U47lw7x5Fc="></param><embed src="http://www.youtube.com/cp/vjVQa1PpcFNbP_fag8PvopkXZyiXyT0J8U47lw7x5Fc=" type="application/x-shockwave-flash" width="416" height="337"></embed></object> <object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/uNxBeJNyAqA&hl=en_US&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/uNxBeJNyAqA&hl=en_US&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" height="385" width="480"><param name="width" value="480" /><param name="height" value="385" /><param name="src" value="http://www.youtube.com/p/E37ADDDFCA0FD050&amp;hl=en" /><embed height="385" src="http://www.youtube.com/p/E37ADDDFCA0FD050&amp;hl=en" type="application/x-shockwave-flash" width="480"></embed></object> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="ooyalaPlayer_229z0_gbps1mrs" width="630" height="354" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"><param name="movie" value="http://player.ooyala.com/player.swf?embedCode=FpZnZwMTo1wqBF-ed2__OUBb3V4HR6za&version=2" /><param name="bgcolor" value="#000000" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="flashvars" value="embedType=noscriptObjectTag&embedCode=pteGRrMTpcKMyQ052c8NwYZ5M5FdSV3j" /><embed src="http://player.ooyala.com/player.swf?embedCode=FpZnZwMTo1wqBF-ed2__OUBb3V4HR6za&version=2" bgcolor="#000000" width="630" height="354" name="ooyalaPlayer_229z0_gbps1mrs" align="middle" play="true" loop="false" allowscriptaccess="always" allowfullscreen="true" type="application/x-shockwave-flash" flashvars="&embedCode=FpZnZwMTo1wqBF-ed2__OUBb3V4HR6za" pluginspage="http://www.adobe.com/go/getflashplayer"></embed></object> '; $regular_purifier = new HTMLPurifier(); $safeobject_purifier = new HTMLPurifier(array( 'HTML.SafeObject' => true, 'Output.FlashCompat' => true, )); ?> <h2>Unpurified</h2> <p><a href="?break">Click here to see the unpurified version (breaks validation).</a></p> <div><?php if (isset($_GET['break'])) echo $string; ?></div> <h2>Without YouTube exception</h2> <div><?php echo $regular_purifier->purify($string); ?></div> <h2>With SafeObject exception and flash compatibility</h2> <div><?php echo $safeobject_purifier->purify($string); ?></div> </body> </html> <?php // vim: et sw=4 sts=4
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 # # Cross Platform and Multi Architecture Advanced Binary Emulation Framework # Built on top of Unicorn emulator (www.unicorn-engine.org) STDCALL = 1 CDECL = 2 DWORD = 1 UINT = 1 INT = 1 BOOL = 1 SIZE_T = 1 BYTE = 1 ULONGLONG = 2 HANDLE = 3 POINTER = 3 STRING = 4 WSTRING = 5 GUID = 6 # OS Threading Constants THREAD_EVENT_INIT_VAL = 0 THREAD_EVENT_EXIT_EVENT = 1 THREAD_EVENT_UNEXECPT_EVENT = 2 THREAD_EVENT_EXECVE_EVENT = 3 THREAD_EVENT_CREATE_THREAD = 4 THREAD_EVENT_BLOCKING_EVENT = 5 THREAD_EVENT_EXIT_GROUP_EVENT = 6 THREAD_STATUS_RUNNING = 0 THREAD_STATUS_BLOCKING = 1 THREAD_STATUS_TERMINATED = 2 THREAD_STATUS_TIMEOUT = 3 reptypedict = { "BSTR": "POINTER", "DLGPROC": "POINTER", "DWORDLONG": "ULONGLONG", "DWORD_PTR": "POINTER", "GROUP": "INT", "HDC": "POINTER", "HEAP_INFORMATION_CLASS": "UINT", "HGLOBAL": "POINTER", "HHOOK": "POINTER", "HINSTANCE": "HANDLE", "HINTERNET": "POINTER", "HKEY": "HANDLE", "HLOCAL": "POINTER", "HMODULE": "HANDLE", "HOOKPROC": "POINTER", "HRSRC": "POINTER", "HWND": "HANDLE", "INSTALLSTATE": "POINTER", "INTERNET_PORT": "DWORD", "INT_PTR": "POINTER", "LARGE_INTEGER": "POINTER", "LCID": "POINTER", "LONG": "ULONGLONG", "LPARAM": "POINTER", "LPBOOL": "POINTER", "LPBYTE": "POINTER", "LPCCH": "POINTER", "LPCONTEXT": "POINTER", "LPCPINFO": "POINTER", "LPCRITICAL_SECTION": "POINTER", "LPCSTR": "STRING", "LPCVOID": "POINTER", "LPCWCH": "POINTER", "LPCWSTR": "WSTRING", "LPDWORD": "POINTER", "LPFILETIME": "POINTER", "LPINTERNET_BUFFERSA": "POINT", "LPMESSAGEFILTER": "POINTER", "LPMODULEINFO": "POINTER", "LPNLSVERSIONINFO": "POINTER", "LPOSVERSIONINFOA": "STRING", "LPOSVERSIONINFOEXW": "POINTER", "LPOSVERSIONINFOW": "WSTRING", "LPOVERLAPPED": "POINTER", "LPPOINT": "POINTER", "LPPROCESSENTRY32W": "POINTER", "LPSECURITY_ATTRIBUTES": "POINTER", "LPSTARTUPINFOA": "POINTER", "LPSTARTUPINFOW": "POINTER", "LPSTR": "POINTER", "LPSYSTEMTIME": "POINTER", "LPSYSTEM_INFO": "POINTER", "LPTHREAD_START_ROUTINE": "POINTER", "LPTOP_LEVEL_EXCEPTION_FILTER": "DWORD", "LPUNKNOWN": "POINTER", "LPVOID": "POINTER", "LPWCH": "POINTER", "LPWIN32_FIND_DATAA": "POINTER", "LPWORD": "POINTER", "LPWSADATA": "STRING", "LPWSAPROTOCOL_INFOA": "POINTER", "LPWSTR": "POINTER", "MSIHANDLE": "POINTER", "OBJECT_INFORMATION_CLASS": "INT", "OLECHAR": "WSTRING", "PBOOL": "POINTER", "PCACTCTXW": "POINTER", "PCNZCH": "STRING", "PDWORD": "POINTER", "PFLS_CALLBACK_FUNCTION": "POINTER", "PHKEY": "POINTER", "PMEMORY_BASIC_INFORMATION": "POINTER", "PROCESSINFOCLASS": "INT", "PSECURITY_DESCRIPTOR": "POINTER", "PSID": "HANDLE", "PSID_IDENTIFIER_AUTHORITY": "POINTER", "PSLIST_HEADER": "POINTER", "PSRWLOCK": "POINTER", "PULONG": "POINTER", "PVECTORED_EXCEPTION_HANDLER": "HANDLE", "PVOID": "POINTER", "REFCLSID": "POINTER", "REFIID": "POINTER", "REGSAM": "POINTER", "SHELLEXECUTEINFOA": "POINTER", "SHELLEXECUTEINFOW": "POINTER", "SHFILEINFOW": "POINTER", "SOCKET": "INT", "SOLE_AUTHENTICATION_SERVICE": "POINTER", "TOKEN_INFORMATION_CLASS": "DWORD", "UINT_PTR": "POINTER", "ULONG": "UINT", "ULONG_PTR": "POINTER", "WORD": "DWORD", "WPARAM": "UINT", "_EXCEPTION_POINTERS": "POINTER", "int": "INT", "size_t": "UINT", "sockaddr": "POINTER", "unsigned int": "UINT", "void": "POINTER" }
{ "pile_set_name": "Github" }
'use strict'; exports.index = function* () { const resource = this.helper.asset('main.js'); this.body = resource; };
{ "pile_set_name": "Github" }
// // Dropdown menus // -------------------------------------------------- // Dropdown arrow/caret .caret { display: inline-block; width: 0; height: 0; margin-left: 2px; vertical-align: middle; border-top: @caret-width-base dashed; border-top: @caret-width-base solid ~"\9"; // IE8 border-right: @caret-width-base solid transparent; border-left: @caret-width-base solid transparent; } // The dropdown wrapper (div) .dropup, .dropdown { position: relative; } // Prevent the focus on the dropdown toggle when closing dropdowns .dropdown-toggle:focus { outline: 0; } // The dropdown menu (ul) .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: @zindex-dropdown; display: none; // none by default, but block on "open" of the menu float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; // override default ul font-size: @font-size-base; text-align: left; // Ensures proper alignment if parent has it changed (e.g., modal footer) list-style: none; background-color: @dropdown-bg; background-clip: padding-box; border: 1px solid @dropdown-fallback-border; // IE8 fallback border: 1px solid @dropdown-border; border-radius: @border-radius-base; .box-shadow(0 6px 12px rgba(0, 0, 0, .175)); // Aligns the dropdown menu to right // // Deprecated as of 3.1.0 in favor of `.dropdown-menu-[dir]` &.pull-right { right: 0; left: auto; } // Dividers (basically an hr) within the dropdown .divider { .nav-divider(@dropdown-divider-bg); } // Links within the dropdown menu > li > a { display: block; padding: 3px 20px; clear: both; font-weight: 400; line-height: @line-height-base; color: @dropdown-link-color; white-space: nowrap; // prevent links from randomly breaking onto new lines &:hover, &:focus { color: @dropdown-link-hover-color; text-decoration: none; background-color: @dropdown-link-hover-bg; } } } // Active state .dropdown-menu > .active > a { &, &:hover, &:focus { color: @dropdown-link-active-color; text-decoration: none; background-color: @dropdown-link-active-bg; outline: 0; } } // Disabled state // // Gray out text and ensure the hover/focus state remains gray .dropdown-menu > .disabled > a { &, &:hover, &:focus { color: @dropdown-link-disabled-color; } // Nuke hover/focus effects &:hover, &:focus { text-decoration: none; cursor: @cursor-disabled; background-color: transparent; background-image: none; // Remove CSS gradient .reset-filter(); } } // Open state for the dropdown .open { // Show the menu > .dropdown-menu { display: block; } // Remove the outline when :focus is triggered > a { outline: 0; } } // Menu positioning // // Add extra class to `.dropdown-menu` to flip the alignment of the dropdown // menu with the parent. .dropdown-menu-right { right: 0; left: auto; // Reset the default from `.dropdown-menu` } // With v3, we enabled auto-flipping if you have a dropdown within a right // aligned nav component. To enable the undoing of that, we provide an override // to restore the default dropdown menu alignment. // // This is only for left-aligning a dropdown menu within a `.navbar-right` or // `.pull-right` nav component. .dropdown-menu-left { right: auto; left: 0; } // Dropdown section headers .dropdown-header { display: block; padding: 3px 20px; font-size: @font-size-small; line-height: @line-height-base; color: @dropdown-header-color; white-space: nowrap; // as with > li > a } // Backdrop to catch body clicks on mobile, etc. .dropdown-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: (@zindex-dropdown - 10); } // Right aligned dropdowns .pull-right > .dropdown-menu { right: 0; left: auto; } // Allow for dropdowns to go bottom up (aka, dropup-menu) // // Just add .dropup after the standard .dropdown class and you're set, bro. // TODO: abstract this so that the navbar fixed styles are not placed here? .dropup, .navbar-fixed-bottom .dropdown { // Reverse the caret .caret { content: ""; border-top: 0; border-bottom: @caret-width-base dashed; border-bottom: @caret-width-base solid ~"\9"; // IE8 } // Different positioning for bottom up menu .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 2px; } } // Component alignment // // Reiterate per navbar.less and the modified component alignment there. @media (min-width: @grid-float-breakpoint) { .navbar-right { .dropdown-menu { .dropdown-menu-right(); } // Necessary for overrides of the default right aligned menu. // Will remove come v4 in all likelihood. .dropdown-menu-left { .dropdown-menu-left(); } } }
{ "pile_set_name": "Github" }
call to q call to test succeeded: 1
{ "pile_set_name": "Github" }
;;; ;;;Part of: Nausicaa/Scheme ;;;Contents: tests for builtin labels ;;;Date: Thu Dec 23, 2010 ;;; ;;;Abstract ;;; ;;; ;;; ;;;Copyright (c) 2010-2015 Marco Maggi <marco.maggi-ipsu@poste.it> ;;; ;;;This program is free software: you can redistribute it and/or modify ;;;it under the terms of the GNU General Public License as published by ;;;the Free Software Foundation, either version 3 of the License, or (at ;;;your option) any later version. ;;; ;;;This program is distributed in the hope that it will be useful, but ;;;WITHOUT ANY WARRANTY; without even the implied warranty of ;;;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;General Public License for more details. ;;; ;;;You should have received a copy of the GNU General Public License ;;;along with this program. If not, see <http://www.gnu.org/licenses/>. ;;; #!vicare (import (nausicaa) (rnrs eval) (vicare checks)) (check-set-mode! 'report-failed) (check-display "*** testing Nausicaa: built-in labels\n") (parametrise ((check-test-name 'booleans)) (check ((<boolean> #:predicate) #t) => #t) (check ((<boolean> #:predicate) #f) => #t) #t) (parametrise ((check-test-name 'symbols)) ;;; predicate (check (is-a? 'ciao <symbol>) => #t) (check (is-a? 123 <symbol>) => #f) ;;; -------------------------------------------------------------------- ;;; constructor (check (<symbol> ("ciao")) => 'ciao) (check ((<symbol> ("ciao")) string) => "ciao") ;;; -------------------------------------------------------------------- ;;; fields and methods: string (check (let (({o <symbol>} 'ciao)) (o string)) => "ciao") (check (let (({o <symbol>} 'ciao)) ((o string) length)) => 4) ;;; -------------------------------------------------------------------- ;;; fields and methods: hash (check (let (({S <symbol>} 'ciao)) (fixnum? (S hash))) => #t) ;;; -------------------------------------------------------------------- ;;; fields and methods: value (check (let (({S <symbol>} (gensym))) (S bound?)) => #f) (check (let (({S <symbol>} (gensym))) (unbound-object? (S $value))) => #t) (check (let (({S <symbol>} (gensym))) (set! (S value) 123) (values (S value) (S bound?))) => 123 #t) ;;; -------------------------------------------------------------------- ;;; fields and methods: properties (let (({S <symbol>} 'ciao)) (S putprop 'british 'hello) (S putprop 'spanish 'hola)) (check (let (({S <symbol>} 'ciao)) (S getprop 'british)) => 'hello) (check (let (({S <symbol>} 'ciao)) (S getprop 'spanish)) => 'hola) (check (let (({S <symbol>} 'ciao)) (S property-list)) => '((british . hello) (spanish . hola))) (let (({S <symbol>} 'ciao)) (S remprop 'british)) (check (let (({S <symbol>} 'ciao)) (S getprop 'british)) => #f) (check (let (({S <symbol>} 'ciao)) (S property-list)) => '((spanish . hola))) #t) (parametrise ((check-test-name 'keywords)) (check (is-a? #:ciao <keyword>) => #t) (check (is-a? (<keyword> ('ciao)) <keyword>) => #t) (check (is-a? (<keyword> ("ciao")) <keyword>) => #t) (check (is-a? 123 <keyword>) => #f) (check (let (({o <keyword>} #:ciao)) ((o symbol) string)) => "ciao") (check (let (({o <keyword>} #:ciao)) (((o symbol) string) length)) => 4) (check (let (({o <keyword>} #:ciao)) (o symbol)) => 'ciao) (check (let (({o <keyword>} #:ciao)) (o string)) => "#:ciao") #t) (parametrise ((check-test-name 'pointers)) (check ((<pointer> #:predicate) (<pointer> (123))) => #t) (check (let (({P <pointer>} (<pointer> (123)))) (P integer)) => 123) ;;; -------------------------------------------------------------------- ;;; fields and methods: comparisons (check (let* (({P <pointer>} (<pointer> (123))) ({Q <pointer>} (<pointer> (987)))) (P != Q)) => #t) ;;; -------------------------------------------------------------------- ;;; fields and methods: clone (check (let* (({P <pointer>} (<pointer> (123))) ({Q <pointer>} (P clone))) (P = Q)) => #t) #t) (parametrise ((check-test-name 'pairs)) (check ;maker (let () (<pair> P (<> (1 2))) (vector (P car) (P cdr))) => '#(1 2)) (check ;predicate ((<pair> #:predicate) '(1 . 2)) => #t) (check ;virtual fields safe accessors (let (({P <pair>} '(1 . 2))) (vector (P car) (P cdr))) => '#(1 2)) (check ;virtual fields unsafe accessors (let (({P <pair>} '(1 . 2))) (vector (P $car) (P $cdr))) => '#(1 2)) ;;; -------------------------------------------------------------------- (check ;maker (let () (<mutable-pair> P (<> (1 2))) (vector (P car) (P cdr))) => '#(1 2)) (check ;predicate ((<mutable-pair> #:predicate) '(1 . 2)) => #t) (check ;virtual fields safe accessors (let (({P <mutable-pair>} '(1 . 2))) (vector (P car) (P cdr))) => '#(1 2)) (check ;virtual fields unsafe accessors (let (({P <mutable-pair>} '(1 . 2))) (vector (P $car) (P $cdr))) => '#(1 2)) (check ;virtual fields safe mutators (let (({P <mutable-pair>} (cons 1 2))) (set! (P car) 10) (set! (P cdr) 20) (vector (P car) (P cdr))) => '#(10 20)) (check ;virtual fields unsafe mutators (let (({P <mutable-pair>} (cons 1 2))) (set! (P $car) 10) (set! (P $cdr) 20) (vector (P car) (P cdr))) => '#(10 20)) #t) (parametrise ((check-test-name 'spines)) (check ;maker (let () (<spine> P (<> ())) P) => '()) (check ;maker (let () (<spine> P (<> (1 '()))) (vector (P car) (P cdr))) => '#(1 ())) (check ;maker (let () (<spine> P (<> (1 '(2)))) (vector (P car) (P cdr))) => '#(1 (2))) (check ;predicate ((<spine> #:predicate) '()) => #t) (check ;predicate ((<spine> #:predicate) '(1)) => #t) (check ;predicate ((<spine> #:predicate) '(1 2)) => #t) (check ;predicate ((<spine> #:predicate) '(1 . 2)) => #f) (check ;predicate ((<spine> #:predicate) '(1 2 . 3)) => #t) (check ;predicate ((<spine> #:predicate) '()) => #t) (check ;virtual fields safe accessors (let (({P <spine>} '(1 2))) (vector (P car) (P cdr))) => '#(1 (2))) (check ;virtual fields unsafe accessors (let (({P <spine>} '(1 2))) (vector (P $car) (P $cdr))) => '#(1 (2))) #t) (parametrise ((check-test-name 'lists)) ;;; maker (check (<list> (1 2 3)) => '(1 2 3)) ;;; -------------------------------------------------------------------- ;;; predicate (check (is-a? '(1 2 3) <list>) => #t) (check (is-a? '() <list>) => #t) (check (is-a? 123 <list>) => #f) ;;; -------------------------------------------------------------------- ;;; fields (check (let (({L <list>} '(1 2 3))) (L car)) => 1) (check (let (({L <list>} '(1 2 3))) (L cdr)) => '(2 3)) (check (let (({L <list>} '(1 2 3))) ((L cdr) car)) => 2) (check (let (({L <list>} '(1 2 3))) ((L cdr) cdr)) => '(3)) (check (let (({L <list>} '(1 2 3))) (L cddr)) => '(3)) ;;; -------------------------------------------------------------------- ;;; methods (check (let (({o <list>} '(1 2 3 4 5))) (o map (lambda (n) (+ 1 n)))) => '(2 3 4 5 6)) (check (let (({o <list>} '(1 2 3 4 5)) (r 0)) (o for-each (lambda (n) (set! r (+ r n)))) r) => (+ 1 2 3 4 5)) (check (let (({o <list>} '(1 2 3 4 5))) (o find (lambda (n) (= 3 n)))) => 3) (check (let (({o <list>} '(1 2 3 4 5))) (o for-all (lambda (n) (< 0 n)))) => #t) (check (let (({o <list>} '(1 2 3 4 5))) (o exists (lambda (n) (if (= 3 n) n #f)))) => 3) #t) (parametrise ((check-test-name 'nonempty-lists)) (check (<nonempty-list> (1 2 3)) => '(1 2 3)) ;;; -------------------------------------------------------------------- ;;; predicate (check (is-a? '(1 2 3) <nonempty-list>) => #t) (check (is-a? '() <nonempty-list>) => #f) (check (is-a? 123 <nonempty-list>) => #f) #t) (parametrise ((check-test-name 'chars)) (check ((<char> #:predicate) #\a) => #t) (check ((<char> #:predicate) 123) => #f) ;;; -------------------------------------------------------------------- (check (let (({C <char>} #\a)) (C upcase)) => #\A) (check (let (({C <char>} #\A)) (C downcase)) => #\a) (check (let (({C <char>} #\a)) (C titlecase)) => #\A) (check (let (({C <char>} #\a)) (C foldcase)) => #\a) ;;; -------------------------------------------------------------------- (check (let (({C <char>} #\a)) (C alphabetic?)) => #t) (check (let (({C <char>} #\1)) (C numeric?)) => #t) (check (let (({C <char>} #\newline)) (C whitespace?)) => #t) (check (let (({C <char>} #\A)) (C upper-case?)) => #t) (check (let (({C <char>} #\A)) (C lower-case?)) => #f) (check (let (({C <char>} #\x01c5)) (C title-case?)) => #t) ;;; -------------------------------------------------------------------- (check (let (({C <char>} #\xA)) (C general-category)) => 'Cc) (check (let (({C <char>} #\xA)) ((C general-category) string)) => "Cc") #t) (parametrise ((check-test-name 'strings)) ;;; predicate (check (is-a? "ciao" <string>) => #t) (check (is-a? 123 <string>) => #f) ;;; -------------------------------------------------------------------- ;;; fields (check (let (({o <string>} (string-copy "ciao"))) (o length)) => 4) (check (let (({o <string>} (string-copy "ciao"))) (o empty?)) => #f) (check (let (({o <string>} "")) (o empty?)) => #t) (check (let (({o <string>} (string-copy "ciao"))) (o upcase)) => "CIAO") (check (let (({o <string>} (string-copy "ciAO"))) (o downcase)) => "ciao") (check (let (({o <string>} (string-copy "ciAO"))) (o titlecase)) => "Ciao") ;;; -------------------------------------------------------------------- ;;; methods (check (let (({o <string>} (string-copy "ciao"))) (o substring 2)) => "ao") (check (let (({o <string>} (string-copy "ciao"))) (o substring 2 3)) => "a") (check (let (({o <string>} (string-copy "ciao"))) (o substring 0 -1)) => "cia") (check (let (({o <string>} (string-copy "ciao"))) (o substring -3 -1)) => "ia") ;;; -------------------------------------------------------------------- (check (let (({o <string>} (string-copy "ciao"))) (o append " mamma")) => "ciao mamma") (check (let (({o <string>} (string-copy "ciao"))) (o list)) => '(#\c #\i #\a #\o)) (check (let (({o <string>} (string-copy "ciao"))) (o copy)) => "ciao") (check (let (({o <string>} (string-copy "ciao")) (result '())) (o for-each (lambda (ch) (set! result (cons ch result)))) result) => (reverse '(#\c #\i #\a #\o))) ;;; -------------------------------------------------------------------- ;;; char ref (check (let (({o <string>} "ciao")) (o ref 0)) => #\c) (check (let (({o <string>} "ciao")) (o ref 1)) => #\i) (check (let (({o <string>} "ciao")) (o ref -1)) => #\o) (check (let (({o <string>} "ciao")) (o ref -2)) => #\a) ;;; -------------------------------------------------------------------- ;;; getter (check (let (({o <string>} "ciao")) (o[0])) => #\c) (check (let (({o <string>} "ciao")) (o[1])) => #\i) (check (let (({o <string>} "ciao")) (o[-1])) => #\o) (check (let (({o <string>} "ciao")) (o[-2])) => #\a) ;;; -------------------------------------------------------------------- ;;; char set (check (let (({o <mutable-string>} (string-copy "ciao"))) (o set! 0 #\K) o) => "Kiao") (check (let (({o <mutable-string>} (string-copy "ciao"))) (o set! 1 #\I) o) => "cIao") (check (let (({o <mutable-string>} (string-copy "ciao"))) (o set! -2 #\U) o) => "ciUo") ;;; -------------------------------------------------------------------- ;;; setter, syntax 1 (check (let (({o <mutable-string>} (string-copy "ciao"))) (set! (o[0]) #\K) o) => "Kiao") (check (let (({o <mutable-string>} (string-copy "ciao"))) (set! (o[1]) #\I) o) => "cIao") (check (let (({o <mutable-string>} (string-copy "ciao"))) (set! (o[-2]) #\U) o) => "ciUo") ;;; -------------------------------------------------------------------- ;;; setter, syntax 2 (check (let (({o <mutable-string>} (string-copy "ciao"))) (set! o[0] #\K) o) => "Kiao") (check (let (({o <mutable-string>} (string-copy "ciao"))) (set! o[1] #\I) o) => "cIao") (check (let (({o <mutable-string>} (string-copy "ciao"))) (set! o[-2] #\U) o) => "ciUo") ;;; -------------------------------------------------------------------- ;;; nested setter and getter invocation (check (let () (define-class <alpha> (fields {str <mutable-string>})) (define-class <beta> (parent <alpha>)) (<beta> B (<> ((string-copy "ciao")))) (set! (B str)[1] #\I) (vector ((B str)[0]) ((B str)[1]))) => '#(#\c #\I)) (check (let () (define-class <alpha> (fields {str <mutable-string>})) (define-class <beta> (fields {a <alpha>})) (<beta> B (<> ((<alpha> ((string-copy "ciao")))))) (set! (((B a) str)[1]) #\I) (vector (((B a) str)[0]) (((B a) str)[1]))) => '#(#\c #\I)) ;;; -------------------------------------------------------------------- (check (let (({O <string>} "ciao")) (O ascii)) => '#ve(ascii "ciao")) (check (let (({O <string>} "ciao")) (O latin1)) => '#ve(latin1 "ciao")) (check (let (({O <string>} "ciao")) (O utf8)) => '#ve(utf8 "ciao")) (check (let (({O <string>} "ciao")) (O utf16le)) => '#ve(utf16le "ciao")) (check (let (({O <string>} "ciao")) (O utf16be)) => '#ve(utf16be "ciao")) (check (let (({O <string>} "ciao")) (O utf16n)) => '#ve(utf16n "ciao")) (check (let (({O <string>} "ciao")) (O utf16)) => '#ve(utf16be "ciao")) (check (let (({O <string>} "ci?a=o")) (O percent-encoding)) => '#ve(ascii "ci%3Fa%3Do")) #t) (parametrise ((check-test-name 'ascii-strings)) (check (let* (({A <ascii-string>} "ciao") ({B <ascii-string>} (A copy))) (B[1])) => #\i) #f) (parametrise ((check-test-name 'latin1-strings)) (check (let* (({A <latin1-string>} "ciao") ({B <latin1-string>} (A copy))) (B[1])) => #\i) #f) (parametrise ((check-test-name 'vectors)) ;;; predicate (check (is-a? '#(1 2 3) <vector>) => #t) (check (is-a? '#() <vector>) => #t) (check (is-a? 123 <vector>) => #f) ;;; -------------------------------------------------------------------- ;;; fields (check (let (({o <vector>} '#(1 2 3 4 5))) (o empty?)) => #f) (check (let (({o <vector>} '#())) (o empty?)) => #t) (check (let (({o <vector>} '#(1 2 3 4 5))) (o $empty?)) => #f) (check (let (({o <vector>} '#())) (o $empty?)) => #t) (check (let (({o <vector>} '#(1 2 3 4 5))) (o length)) => 5) (check (let (({o <vector>} '#())) (o $length)) => 0) ;;; -------------------------------------------------------------------- ;;; methods (check (let (({o <vector>} '#(1 2 3 4 5))) (o map (lambda (n) (+ 1 n)))) => '#(2 3 4 5 6)) (check (let (({o <vector>} '#(1 2 3 4 5)) (r 0)) (o for-each (lambda (n) (set! r (+ r n)))) r) => (+ 1 2 3 4 5)) (check (let (({o <vector>} (list->vector '(1 2 3 4 5)))) (o fill! 1) o) => '#(1 1 1 1 1)) ;;; -------------------------------------------------------------------- (check (let (({o <vector>} '#())) (o for-all even?)) => #t) (check (let (({o <vector>} '#(3 1 4 1 5 9))) (o for-all even?)) => #f) (check (let (({o <vector>} '#(2 4 14))) (o for-all even?)) => #t) (check (let (({o <vector>} '#(2 4 14))) (o for-all (lambda (n) (and (even? n) n)))) => 14) (check (let (({o <vector>} '#(1 2 3))) (o for-all < '#(2 3 4))) => #t) (check (let (({o <vector>} '#(1 2 4))) (o for-all < '#(2 3 4))) => #f) ;;; -------------------------------------------------------------------- (check (let (({o <vector>} '#(3 1 4 1 5 9))) (o exists even?)) => #t) (check (let (({o <vector>} '#(3 1 1 5 9))) (o exists even?)) => #f) (check (let (({o <vector>} '#())) (o exists even?)) => #f) (check (let (({o <vector>} '#(2 1 4 14))) (o exists (lambda (n) (and (even? n) n)))) => 2) (check (let (({o <vector>} '#(1 2 4))) (o exists < '#(2 3 4))) => #t) (check (let (({o <vector>} '#(1 2 3))) (o exists > '#(2 3 4))) => #f) ;;; -------------------------------------------------------------------- ;;; item ref (check (let (({o <vector>} '#(1 2 3 4))) (o ref 0)) => 1) (check (let (({o <vector>} '#(1 2 3 4))) (o ref 1)) => 2) (check (let (({o <vector>} '#(1 2 3 4))) (o ref -1)) => 4) (check (let (({o <vector>} '#(1 2 3 4))) (o ref -2)) => 3) ;;; -------------------------------------------------------------------- ;;; getter (check (let (({o <vector>} '#(1 2 3 4))) (o[0])) => 1) (check (let (({o <vector>} '#(1 2 3 4))) (o[1])) => 2) (check (let (({o <vector>} '#(1 2 3 4))) (o[-1])) => 4) (check (let (({o <vector>} '#(1 2 3 4))) (o[-2])) => 3) ;;; -------------------------------------------------------------------- ;;; item set (check (receive-and-return ({o <vector>}) (vector 1 2 3 4) (o set! 0 9)) => '#(9 2 3 4)) (check (receive-and-return ({o <vector>}) (vector 1 2 3 4) (o set! 1 9)) => '#(1 9 3 4)) (check (receive-and-return ({o <vector>}) (vector 1 2 3 4) (o set! -1 9)) => '#(1 2 3 9)) (check (receive-and-return ({o <vector>}) (vector 1 2 3 4) (o set! -2 9)) => '#(1 2 9 4)) ;;; -------------------------------------------------------------------- ;;; setter, syntax 2 (check (receive-and-return ({o <vector>}) (vector 1 2 3 4) (set! o[0] 9)) => '#(9 2 3 4)) (check (receive-and-return ({o <vector>}) (vector 1 2 3 4) (set! o[1] 9)) => '#(1 9 3 4)) (check (receive-and-return ({o <vector>}) (vector 1 2 3 4) (set! o[-1] 9)) => '#(1 2 3 9)) (check (receive-and-return ({o <vector>}) (vector 1 2 3 4) (set! o[-2] 9)) => '#(1 2 9 4)) #t) (parametrise ((check-test-name 'bytevectors)) (check ((<bytevector> #:predicate) '#vu8(1 2)) => #t) (check ((<bytevector> #:predicate) '#vu8()) => #t) (check ((<bytevector> #:predicate) '(1 2)) => #f) (check (let (({O <bytevector>} '#ve(ascii "ci?a=o"))) (O percent-encoded)) => '#ve(ascii "ci%3Fa%3Do")) (check (let (({O <bytevector>} '#ve(ascii "ci%3Fa%3Do"))) (O percent-decoded)) => '#ve(ascii "ci?a=o")) (check (let (({O <bytevector>} '#ve(ascii "ci%3Fa%3Do"))) (O percent-encoded?)) => #t) (check (let (({O <bytevector>} '#ve(ascii "ci?a=o"))) (O percent-encoded?)) => #f) (check (let (({O <bytevector>} '#ve(ascii "c%3"))) (O percent-encoded?)) => #f) ;;; -------------------------------------------------------------------- (check (let (({bv <bytevector>} '#vu8(1 2))) (bv copy)) => '#vu8(1 2)) (check (let (({bv <bytevector>} '#vu8(1 2))) (bv $copy)) => '#vu8(1 2)) ;;; -------------------------------------------------------------------- (check (let (({bv <nonempty-bytevector>} '#vu8(1 2))) (bv copy)) => '#vu8(1 2)) #f) (parametrise ((check-test-name 'bytevectors-u8)) (check (let* (({A <bytevector-u8>} '#vu8(10 20 30 40 50 60 70 80)) ({B <bytevector-u8>} (A copy))) (B[1])) => 20) (check (let* (({A <bytevector-u8>} '#vu8(10 20 30 40 50 60 70 80)) ({B <bytevector-u8>} (A copy))) (set! B[1] 29) (B[1])) => 29) #f) (parametrise ((check-test-name 'bytevectors-s8)) (check (let* (({A <bytevector-s8>} '#vs8(10 20 30 40 50 60 70 80)) ({B <bytevector-s8>} (A copy))) (B[1])) => 20) (check (let* (({A <bytevector-s8>} '#vs8(10 20 30 40 50 60 70 80)) ({B <bytevector-s8>} (A copy))) (set! B[1] -29) (B[1])) => -29) #t) (parametrise ((check-test-name 'ascii-bytevectors)) (check (let* (({A <ascii-bytevector>} '#vu8(10 20 30 40 50 60 70 80)) ({B <ascii-bytevector>} (A copy))) (B[1])) => 20) (check (let* (({A <ascii-bytevector>} '#vu8(10 20 30 40 50 60 70 80)) ({B <ascii-bytevector>} (A copy))) (set! B[1] 29) (B[1])) => 29) #f) (parametrise ((check-test-name 'latin1-bytevectors)) (check (let* (({A <latin1-bytevector>} '#ve(latin1 "ciao")) ({B <latin1-bytevector>} (A copy))) (B[1])) => 105) (check (let* (({A <latin1-bytevector>} '#ve(latin1 "ciao")) ({B <latin1-bytevector>} (A copy))) (set! B[1] 29) (B[1])) => 29) #f) (parametrise ((check-test-name 'percent-encoded-bytevectors)) (check ((<percent-encoded-bytevector> #:predicate) '#vu8()) => #t) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "ciao")) => #t) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "cia%3do")) => #t) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "cia%3Do")) => #t) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "ci%3fa%3do")) => #t) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "ci%3Fa%3Do")) => #t) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "%7Eciao")) => #t) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "ci%5Fao")) => #t) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "ci%5")) => #f) (check ((<percent-encoded-bytevector> #:predicate) (string->ascii "ci%5Zao")) => #f) #t) (parametrise ((check-test-name 'bytevectors-u16)) (check (let* (({A <bytevector-u16n>} '#vu16n(10 20 30 40 50 60 70 80)) ({B <bytevector-u16n>} (A copy))) (B[1])) => 20) (check (let* (({A <bytevector-u16n>} '#vu16n(10 20 30 40 50 60 70 80)) ({B <bytevector-u16n>} (A copy))) (set! B[1] 29) (B[1])) => 29) #f) (parametrise ((check-test-name 'bytevectors-s16)) (check (let* (({A <bytevector-s16n>} '#vs16n(10 20 30 40 50 60 70 80)) ({B <bytevector-s16n>} (A copy))) (B[1])) => 20) (check (let* (({A <bytevector-s16n>} '#vs16n(10 20 30 40 50 60 70 80)) ({B <bytevector-s16n>} (A copy))) (set! B[1] -29) (B[1])) => -29) #t) (parametrise ((check-test-name 'bytevectors-u32)) (check (let* (({A <bytevector-u32n>} '#vu32n(10 20 30 40 50 60 70 80)) ({B <bytevector-u32n>} (A copy))) (B[1])) => 20) (check (let* (({A <bytevector-u32n>} '#vu32n(10 20 30 40 50 60 70 80)) ({B <bytevector-u32n>} (A copy))) (set! B[1] 29) (B[1])) => 29) #f) (parametrise ((check-test-name 'bytevectors-s32)) (check (let* (({A <bytevector-s32n>} '#vs32n(10 20 30 40 50 60 70 80)) ({B <bytevector-s32n>} (A copy))) (B[1])) => 20) (check (let* (({A <bytevector-s32n>} '#vs32n(10 20 30 40 50 60 70 80)) ({B <bytevector-s32n>} (A copy))) (set! B[1] -29) (B[1])) => -29) #t) (parametrise ((check-test-name 'bytevectors-u64)) (check (let* (({A <bytevector-u64n>} '#vu64n(10 20 30 40 50 60 70 80)) ({B <bytevector-u64n>} (A copy))) (B[1])) => 20) (check (let* (({A <bytevector-u64n>} '#vu64n(10 20 30 40 50 60 70 80)) ({B <bytevector-u64n>} (A copy))) (set! B[1] 29) (B[1])) => 29) #f) (parametrise ((check-test-name 'bytevectors-s64)) (check (let* (({A <bytevector-s64n>} '#vs64n(10 20 30 40 50 60 70 80)) ({B <bytevector-s64n>} (A copy))) (B[1])) => 20) (check (let* (({A <bytevector-s64n>} '#vs64n(10 20 30 40 50 60 70 80)) ({B <bytevector-s64n>} (A copy))) (set! B[1] -29) (B[1])) => -29) #t) (parametrise ((check-test-name 'bytevectors-single)) (check (let* (({A <bytevector-singlen>} '#vf4n(10. 20. 30. 40. 50. 60. 70. 80.)) ({B <bytevector-singlen>} (A copy))) (B[1])) => 20.) (check (let* (({A <bytevector-singlen>} '#vf4n(10. 20. 30. 40. 50. 60. 70. 80.)) ({B <bytevector-singlen>} (A copy))) (set! B[1] 29.) (B[1])) => 29.) #f) (parametrise ((check-test-name 'bytevectors-single)) (check (let* (({A <bytevector-singlen>} '#vf4n(10. 20. 30. 40. 50. 60. 70. 80.)) ({B <bytevector-singlen>} (A copy))) (B[1])) => 20.) (check (let* (({A <bytevector-singlen>} '#vf4n(10. 20. 30. 40. 50. 60. 70. 80.)) ({B <bytevector-singlen>} (A copy))) (set! B[1] -29.) (B[1])) => -29.) #t) (parametrise ((check-test-name 'bytevectors-double)) (check (let* (({A <bytevector-doublen>} '#vf8n(10. 20. 30. 40. 50. 60. 70. 80.)) ({B <bytevector-doublen>} (A copy))) (B[1])) => 20.) (check (let* (({A <bytevector-doublen>} '#vf8n(10. 20. 30. 40. 50. 60. 70. 80.)) ({B <bytevector-doublen>} (A copy))) (set! B[1] 29.) (B[1])) => 29.) #f) (parametrise ((check-test-name 'bytevectors-double)) (check (let* (({A <bytevector-doublen>} '#vf8n(10. 20. 30. 40. 50. 60. 70. 80.)) ({B <bytevector-doublen>} (A copy))) (B[1])) => 20.) (check (let* (({A <bytevector-doublen>} '#vf8n(10. 20. 30. 40. 50. 60. 70. 80.)) ({B <bytevector-doublen>} (A copy))) (set! B[1] -29.) (B[1])) => -29.) #t) (parametrise ((check-test-name 'hashtables)) (check (let (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b))))) ((<hashtable> #:predicate) T)) => #t) (check (let (({T <hashtable>} (<hashtable-eqv> ((1 #\a) (2 #\b))))) ((<hashtable> #:predicate) T)) => #t) (check (let (({T <hashtable>} (<string-hashtable> (("1" #\a) ("2" #\b))))) ((<hashtable> #:predicate) T)) => #t) (check (let (({T <hashtable>} (<string-ci-hashtable> (("1" #\a) ("2" #\b))))) ((<hashtable> #:predicate) T)) => #t) (check (let (({T <hashtable>} (<symbol-hashtable> (('a #\a) ('b #\b))))) ((<hashtable> #:predicate) T)) => #t) ;;; -------------------------------------------------------------------- ;;; fields (check (let (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b))))) (T size)) => 2) ;;; -------------------------------------------------------------------- ;;; setter, getter (check (let (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b))))) (set! (T[1]) #\C) (T [1])) => #\C) (check (let (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b))))) (T [3])) => (void)) (check (let (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b))))) (T [3] (#f))) => #f) ;;; -------------------------------------------------------------------- ;;; methods (check ;delete! (let (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b))))) (T delete! 1) (T [1])) => (void)) (check ;clear! (let (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b))))) (T clear!) (T size)) => 0) (check ;contains? (let (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b))))) (T contains? 1)) => #t) (check ;copy (let* (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b)))) ({R <hashtable>} (T copy))) (T[1])) => #\a) (check ;copy (let* (({T <hashtable>} (<hashtable-eq> ((1 #\a) (2 #\b)))) ({R <hashtable>} (T copy #t))) (T mutable?)) => #t) #t) (parametrise ((check-test-name 'rtd)) (define-record-type <alpha> (fields (mutable a) (immutable b))) ;;; -------------------------------------------------------------------- (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) ((<record-type-descriptor> #:predicate) T)) => #t) ;;; -------------------------------------------------------------------- ;;; fields (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (T name)) => '<alpha>) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (T parent)) => #f) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (gensym? (T uid))) => #t) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (T generative?)) => #t) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (T sealed?)) => #f) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (T opaque?)) => #f) ;;; -------------------------------------------------------------------- ;;; methods (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (define R (make-<alpha> 1 2)) ((T predicate) R)) => #t) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (define R (make-<alpha> 1 2)) ((T accessor 0) R)) => 1) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (define R (make-<alpha> 1 2)) ((T mutator 0) R 99) ((T accessor 0) R)) => 99) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (T field-mutable? 0)) => #t) (check (let (({T <record-type-descriptor>} (record-type-descriptor <alpha>))) (T field-mutable? 1)) => #f) #t) (parametrise ((check-test-name 'record)) (define-record-type <alpha> (fields (mutable a) (immutable b))) ;;; -------------------------------------------------------------------- (check (let (({R <record>} (make-<alpha> 1 2))) (R rtd)) => (record-type-descriptor <alpha>)) #t) (parametrise ((check-test-name 'conditions)) (define-condition-type &ciao &condition make-ciao ciao?) ;;; -------------------------------------------------------------------- (check ((<condition> #:predicate) (make-ciao)) => #t) (check (let (({C <condition>} (<condition> ((make-ciao))))) (for-all ciao? (C simple))) => #t) (check (let (({C <condition>} (<condition> ((make-ciao) (make-ciao))))) (for-all ciao? (C simple))) => #t) #t) (parametrise ((check-test-name 'transcoders)) (check ((<transcoder> #:predicate) (native-transcoder)) => #t) (check (let (({T <transcoder>} (native-transcoder))) (T codec)) => (transcoder-codec (native-transcoder))) (check (let (({T <transcoder>} (native-transcoder))) (T eol-style)) => (transcoder-eol-style (native-transcoder))) (check (let (({T <transcoder>} (native-transcoder))) (T error-handling-mode)) => (transcoder-error-handling-mode (native-transcoder))) #t) (parametrise ((check-test-name 'ports)) (define (make-binary-input-port) (open-bytevector-input-port '#vu8())) (define (make-binary-output-port) (receive (port getter) (open-bytevector-output-port) port)) (define (make-textual-input-port) (open-string-input-port "")) (define (make-textual-output-port) (receive (port getter) (open-string-output-port) port)) ;;; -------------------------------------------------------------------- ;;; predicates (check ((<port> #:predicate) stdin) => #t) (check ((<input-port> #:predicate) stdin) => #t) (check ((<output-port> #:predicate) stdin) => #f) (check ((<input/output-port> #:predicate) stdin) => #f) (check ((<textual-port> #:predicate) stdin) => #t) (check ((<binary-port> #:predicate) stdin) => #f) (check ((<textual-input-port> #:predicate) stdin) => #t) (check ((<textual-output-port> #:predicate) stdout) => #t) (check ((<binary-input-port> #:predicate) (make-binary-input-port)) => #t) (check ((<binary-output-port> #:predicate) (make-binary-output-port)) => #t) (check ((<textual-input-port> #:predicate) (make-textual-input-port)) => #t) (check ((<textual-output-port> #:predicate) (make-textual-output-port)) => #t) ;;; -------------------------------------------------------------------- ;;; virtual fields (check (let (({P <port>} stdin)) ((<transcoder> #:predicate) (P transcoder))) => #t) (check (let (({P <port>} stdin)) (P textual?)) => #t) (check (let (({P <port>} stdin)) (P input?)) => #t) (check (let (({P <port>} stdout)) (P output?)) => #t) (check (let (({P <port>} stdout)) (P binary?)) => #f) (check (let (({P <port>} stdout)) (P closed?)) => #f) (check (let (({P <port>} stdout)) (P fd)) => 1) (check (let (({P <binary-input-port>} (make-binary-input-port))) (P eof?)) => #t) (check (let (({P <port>} stdin)) (P id)) => "*stdin*") (check (let (({P <port>} stdin)) (symbol? (P uid))) => #t) (check (let (({P <port>} stdin)) (integer? (P hash))) => #t) (check (let (({P <output-port>} stderr)) (P buffer-mode)) => 'line) #t) (parametrise ((check-test-name 'numbers)) (check (let (({o <real>} -123)) (o abs)) => 123) (check (let (({o <real>} 123)) (o abs)) => 123) (check (let (({o <real>} 123)) (o string)) => "123") (check (let (({o <real>} 123)) (o string-radix)) => "123") ;;; -------------------------------------------------------------------- (check (let (({o <real>} -123)) (o positive?)) => #f) (check (let (({o <real>} -123)) (o negative?)) => #t) (check (let (({o <real>} -123)) (o non-positive?)) => #t) (check (let (({o <real>} -123)) (o non-negative?)) => #f) ;;; -------------------------------------------------------------------- (check (let (({o <real>} -123)) (o sign)) => -1) (check (let (({o <real>} 123)) (o sign)) => 1) ;;; -------------------------------------------------------------------- ;;; methods (check (let (({N <number>} 1.2)) ((<number> #:predicate) (N sin))) => #t) (check (let (({N <number>} 1)) (N + 2)) => 3) (check (let (({N <number>} 1)) (N - 2)) => -1) (check (let (({N <number>} 3)) (N -)) => -3) (check (let (({N <number>} 3)) (N * 2)) => 6) (check (let (({N <number>} 1)) (N / 2)) => 1/2) ;;; -------------------------------------------------------------------- ;;; fixnums (check (let (({N <fixnum>} 123)) (N string)) => "123") (check (let (({N <fixnum>} 123)) (N $string)) => "123") (check (let (({N <fixnum>} 123)) (N flonum)) => 123.0) (check (let (({N <fixnum>} 123)) (N $flonum)) => 123.0) #t) ;;;; done (check-report) ;;; end of file ;; Local Variables: ;; coding: utf-8-unix ;; End:
{ "pile_set_name": "Github" }
/* * Copyright 2018-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.mongodb.repository.support; import com.querydsl.core.types.Operator; /** * Spring Data specific {@link Operator operators} for usage with Querydsl and MongoDB. * * @author Christoph Strobl * @since 2.1 */ enum QuerydslMongoOps implements Operator { /** * {@link Operator} always evaluating to {@literal false}. */ NO_MATCH(Boolean.class); private final Class<?> type; QuerydslMongoOps(Class<?> type) { this.type = type; } @Override public Class<?> getType() { return type; } }
{ "pile_set_name": "Github" }
// // TestingCoreTests.swift // TestingCoreTests // // Created by Taykalo on 5/3/18. // Copyright © 2018 Recursive. All rights reserved. // import XCTest @testable import TestingCore class TestingCoreTests: XCTestCase { }
{ "pile_set_name": "Github" }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/Arvados.R \name{pipeline_templates.list} \alias{pipeline_templates.list} \title{pipeline_templates.list} \usage{ arv$pipeline_templates.list(filters = NULL, where = NULL, order = NULL, select = NULL, distinct = NULL, limit = "100", offset = "0", count = "exact") } \arguments{ \item{filters}{} \item{where}{} \item{order}{} \item{select}{} \item{distinct}{} \item{limit}{} \item{offset}{} \item{count}{} } \value{ PipelineTemplateList object. } \description{ pipeline_templates.list is a method defined in Arvados class. }
{ "pile_set_name": "Github" }
// DuckDoerDlg.h : Declaration of the CDuckDoerDlg // // This is a part of the Active Template Library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Active Template Library Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Active Template Library product. #ifndef __DUCKDOERDLG_H_ #define __DUCKDOERDLG_H_ #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CDuckDoerDlg class CDuckDoer; class CDuckDoerDlg : public CDialogImpl<CDuckDoerDlg> { public: CDuckDoerDlg(); ~CDuckDoerDlg(); enum { IDD = IDD_DUCKDOERDLG }; BEGIN_MSG_MAP(CDuckDoerDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnOK) COMMAND_ID_HANDLER(IDCANCEL, OnCancel) COMMAND_ID_HANDLER(IDC_QUACK, OnQuack) COMMAND_ID_HANDLER(IDC_FLAP, OnFlap) COMMAND_ID_HANDLER(IDC_WALK, OnWalk) COMMAND_ID_HANDLER(IDC_PADDLE, OnPaddle) END_MSG_MAP() LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnWalk(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnQuack(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnPaddle(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnFlap(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); public: void SetOwner(CDuckDoer* pObject){m_pObject = pObject;} void RecalcListboxExtent(LPCTSTR lpszEntry, BOOL bAdded = TRUE); protected: CDuckDoer* m_pObject; int m_xListboxExtentMax; public: }; #endif //__DUCKDOERDLG_H_
{ "pile_set_name": "Github" }
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @extends {WebInspector.View} * @constructor * @param {!WebInspector.ContentProvider} contentProvider */ WebInspector.SourceFrame = function(contentProvider) { WebInspector.View.call(this); this.element.classList.add("script-view"); this.element.classList.add("fill"); this._url = contentProvider.contentURL(); this._contentProvider = contentProvider; var textEditorDelegate = new WebInspector.TextEditorDelegateForSourceFrame(this); loadScript("CodeMirrorTextEditor.js"); this._textEditor = new WebInspector.CodeMirrorTextEditor(this._url, textEditorDelegate); this._currentSearchResultIndex = -1; this._searchResults = []; this._messages = []; this._rowMessages = {}; this._messageBubbles = {}; this._textEditor.setReadOnly(!this.canEditSource()); this._shortcuts = {}; this.addShortcut(WebInspector.KeyboardShortcut.makeKey("s", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta), this._commitEditing.bind(this)); this.element.addEventListener("keydown", this._handleKeyDown.bind(this), false); this._sourcePosition = new WebInspector.StatusBarText("", "source-frame-cursor-position"); } /** * @param {string} query * @param {string=} modifiers * @return {!RegExp} */ WebInspector.SourceFrame.createSearchRegex = function(query, modifiers) { var regex; modifiers = modifiers || ""; // First try creating regex if user knows the / / hint. try { if (/^\/.+\/$/.test(query)) { regex = new RegExp(query.substring(1, query.length - 1), modifiers); regex.__fromRegExpQuery = true; } } catch (e) { // Silent catch. } // Otherwise just do case-insensitive search. if (!regex) regex = createPlainTextSearchRegex(query, "i" + modifiers); return regex; } WebInspector.SourceFrame.Events = { ScrollChanged: "ScrollChanged", SelectionChanged: "SelectionChanged" } WebInspector.SourceFrame.prototype = { /** * @param {number} key * @param {function()} handler */ addShortcut: function(key, handler) { this._shortcuts[key] = handler; }, wasShown: function() { this._ensureContentLoaded(); this._textEditor.show(this.element); this._editorAttached = true; this._wasShownOrLoaded(); }, /** * @return {boolean} */ _isEditorShowing: function() { return this.isShowing() && this._editorAttached; }, willHide: function() { WebInspector.View.prototype.willHide.call(this); this._clearPositionHighlight(); this._clearLineToReveal(); }, /** * @return {?Element} */ statusBarText: function() { return this._sourcePosition.element; }, /** * @return {!Array.<!Element>} */ statusBarItems: function() { return []; }, defaultFocusedElement: function() { return this._textEditor.defaultFocusedElement(); }, get loaded() { return this._loaded; }, hasContent: function() { return true; }, get textEditor() { return this._textEditor; }, _ensureContentLoaded: function() { if (!this._contentRequested) { this._contentRequested = true; this._contentProvider.requestContent(this.setContent.bind(this)); } }, addMessage: function(msg) { this._messages.push(msg); if (this.loaded) this.addMessageToSource(msg.line - 1, msg); }, clearMessages: function() { for (var line in this._messageBubbles) { var bubble = this._messageBubbles[line]; var lineNumber = parseInt(line, 10); this._textEditor.removeDecoration(lineNumber, bubble); } this._messages = []; this._rowMessages = {}; this._messageBubbles = {}; }, /** * @override */ canHighlightPosition: function() { return true; }, /** * @override */ highlightPosition: function(line, column) { this._clearLineToReveal(); this._clearLineToScrollTo(); this._clearSelectionToSet(); this._positionToHighlight = { line: line, column: column }; this._innerHighlightPositionIfNeeded(); }, _innerHighlightPositionIfNeeded: function() { if (!this._positionToHighlight) return; if (!this.loaded || !this._isEditorShowing()) return; this._textEditor.highlightPosition(this._positionToHighlight.line, this._positionToHighlight.column); delete this._positionToHighlight; }, _clearPositionHighlight: function() { this._textEditor.clearPositionHighlight(); delete this._positionToHighlight; }, /** * @param {number} line */ revealLine: function(line) { this._clearPositionHighlight(); this._clearLineToScrollTo(); this._clearSelectionToSet(); this._lineToReveal = line; this._innerRevealLineIfNeeded(); }, _innerRevealLineIfNeeded: function() { if (typeof this._lineToReveal === "number") { if (this.loaded && this._isEditorShowing()) { this._textEditor.revealLine(this._lineToReveal); delete this._lineToReveal; } } }, _clearLineToReveal: function() { delete this._lineToReveal; }, /** * @param {number} line */ scrollToLine: function(line) { this._clearPositionHighlight(); this._clearLineToReveal(); this._lineToScrollTo = line; this._innerScrollToLineIfNeeded(); }, _innerScrollToLineIfNeeded: function() { if (typeof this._lineToScrollTo === "number") { if (this.loaded && this._isEditorShowing()) { this._textEditor.scrollToLine(this._lineToScrollTo); delete this._lineToScrollTo; } } }, _clearLineToScrollTo: function() { delete this._lineToScrollTo; }, /** * @param {!WebInspector.TextRange} textRange */ setSelection: function(textRange) { this._selectionToSet = textRange; this._innerSetSelectionIfNeeded(); }, _innerSetSelectionIfNeeded: function() { if (this._selectionToSet && this.loaded && this._isEditorShowing()) { this._textEditor.setSelection(this._selectionToSet); delete this._selectionToSet; } }, _clearSelectionToSet: function() { delete this._selectionToSet; }, _wasShownOrLoaded: function() { this._innerHighlightPositionIfNeeded(); this._innerRevealLineIfNeeded(); this._innerSetSelectionIfNeeded(); this._innerScrollToLineIfNeeded(); }, onTextChanged: function(oldRange, newRange) { if (this._searchResultsChangedCallback && !this._isReplacing) this._searchResultsChangedCallback(); this.clearMessages(); }, _simplifyMimeType: function(content, mimeType) { if (!mimeType) return ""; if (mimeType.indexOf("javascript") >= 0 || mimeType.indexOf("jscript") >= 0 || mimeType.indexOf("ecmascript") >= 0) return "text/javascript"; // A hack around the fact that files with "php" extension might be either standalone or html embedded php scripts. if (mimeType === "text/x-php" && content.match(/\<\?.*\?\>/g)) return "application/x-httpd-php"; return mimeType; }, /** * @param {string} highlighterType */ setHighlighterType: function(highlighterType) { this._highlighterType = highlighterType; this._updateHighlighterType(""); }, /** * @param {string} content */ _updateHighlighterType: function(content) { this._textEditor.setMimeType(this._simplifyMimeType(content, this._highlighterType)); }, /** * @param {?string} content */ setContent: function(content) { if (!this._loaded) { this._loaded = true; this._textEditor.setText(content || ""); this._textEditor.markClean(); } else { var firstLine = this._textEditor.firstVisibleLine(); var selection = this._textEditor.selection(); this._textEditor.setText(content || ""); this._textEditor.scrollToLine(firstLine); this._textEditor.setSelection(selection); } this._updateHighlighterType(content || ""); this._textEditor.beginUpdates(); this._setTextEditorDecorations(); this._wasShownOrLoaded(); if (this._delayedFindSearchMatches) { this._delayedFindSearchMatches(); delete this._delayedFindSearchMatches; } this.onTextEditorContentLoaded(); this._textEditor.endUpdates(); }, onTextEditorContentLoaded: function() {}, _setTextEditorDecorations: function() { this._rowMessages = {}; this._messageBubbles = {}; this._textEditor.beginUpdates(); this._addExistingMessagesToSource(); this._textEditor.endUpdates(); }, /** * @param {string} query * @param {boolean} shouldJump * @param {function(!WebInspector.View, number)} callback * @param {function(number)} currentMatchChangedCallback * @param {function()} searchResultsChangedCallback */ performSearch: function(query, shouldJump, callback, currentMatchChangedCallback, searchResultsChangedCallback) { /** * @param {string} query * @this {WebInspector.SourceFrame} */ function doFindSearchMatches(query) { this._currentSearchResultIndex = -1; this._searchResults = []; var regex = WebInspector.SourceFrame.createSearchRegex(query); this._searchRegex = regex; this._searchResults = this._collectRegexMatches(regex); if (!this._searchResults.length) this._textEditor.cancelSearchResultsHighlight(); else if (shouldJump) this.jumpToNextSearchResult(); else this._textEditor.highlightSearchResults(regex, null); callback(this, this._searchResults.length); } this._resetSearch(); this._currentSearchMatchChangedCallback = currentMatchChangedCallback; this._searchResultsChangedCallback = searchResultsChangedCallback; if (this.loaded) doFindSearchMatches.call(this, query); else this._delayedFindSearchMatches = doFindSearchMatches.bind(this, query); this._ensureContentLoaded(); }, _editorFocused: function() { if (!this._searchResults.length) return; this._currentSearchResultIndex = -1; if (this._currentSearchMatchChangedCallback) this._currentSearchMatchChangedCallback(this._currentSearchResultIndex); this._textEditor.highlightSearchResults(this._searchRegex, null); }, _searchResultAfterSelectionIndex: function(selection) { if (!selection) return 0; for (var i = 0; i < this._searchResults.length; ++i) { if (this._searchResults[i].compareTo(selection) >= 0) return i; } return 0; }, _resetSearch: function() { delete this._delayedFindSearchMatches; delete this._currentSearchMatchChangedCallback; delete this._searchResultsChangedCallback; this._currentSearchResultIndex = -1; this._searchResults = []; delete this._searchRegex; }, searchCanceled: function() { var range = this._currentSearchResultIndex !== -1 ? this._searchResults[this._currentSearchResultIndex] : null; this._resetSearch(); if (!this.loaded) return; this._textEditor.cancelSearchResultsHighlight(); if (range) this._textEditor.setSelection(range); }, hasSearchResults: function() { return this._searchResults.length > 0; }, jumpToFirstSearchResult: function() { this.jumpToSearchResult(0); }, jumpToLastSearchResult: function() { this.jumpToSearchResult(this._searchResults.length - 1); }, jumpToNextSearchResult: function() { var currentIndex = this._searchResultAfterSelectionIndex(this._textEditor.selection()); var nextIndex = this._currentSearchResultIndex === -1 ? currentIndex : currentIndex + 1; this.jumpToSearchResult(nextIndex); }, jumpToPreviousSearchResult: function() { var currentIndex = this._searchResultAfterSelectionIndex(this._textEditor.selection()); this.jumpToSearchResult(currentIndex - 1); }, showingFirstSearchResult: function() { return this._searchResults.length && this._currentSearchResultIndex === 0; }, showingLastSearchResult: function() { return this._searchResults.length && this._currentSearchResultIndex === (this._searchResults.length - 1); }, get currentSearchResultIndex() { return this._currentSearchResultIndex; }, jumpToSearchResult: function(index) { if (!this.loaded || !this._searchResults.length) return; this._currentSearchResultIndex = (index + this._searchResults.length) % this._searchResults.length; if (this._currentSearchMatchChangedCallback) this._currentSearchMatchChangedCallback(this._currentSearchResultIndex); this._textEditor.highlightSearchResults(this._searchRegex, this._searchResults[this._currentSearchResultIndex]); }, /** * @param {string} text */ replaceSearchMatchWith: function(text) { var range = this._searchResults[this._currentSearchResultIndex]; if (!range) return; this._textEditor.highlightSearchResults(this._searchRegex, null); this._isReplacing = true; var newRange = this._textEditor.editRange(range, text); delete this._isReplacing; this._textEditor.setSelection(newRange.collapseToEnd()); }, /** * @param {string} query * @param {string} replacement */ replaceAllWith: function(query, replacement) { this._textEditor.highlightSearchResults(this._searchRegex, null); var text = this._textEditor.text(); var range = this._textEditor.range(); var regex = WebInspector.SourceFrame.createSearchRegex(query, "g"); if (regex.__fromRegExpQuery) text = text.replace(regex, replacement); else text = text.replace(regex, function() { return replacement; }); this._isReplacing = true; this._textEditor.editRange(range, text); delete this._isReplacing; }, _collectRegexMatches: function(regexObject) { var ranges = []; for (var i = 0; i < this._textEditor.linesCount; ++i) { var line = this._textEditor.line(i); var offset = 0; do { var match = regexObject.exec(line); if (match) { if (match[0].length) ranges.push(new WebInspector.TextRange(i, offset + match.index, i, offset + match.index + match[0].length)); offset += match.index + 1; line = line.substring(match.index + 1); } } while (match && line); } return ranges; }, _addExistingMessagesToSource: function() { var length = this._messages.length; for (var i = 0; i < length; ++i) this.addMessageToSource(this._messages[i].line - 1, this._messages[i]); }, /** * @param {number} lineNumber * @param {!WebInspector.ConsoleMessage} msg */ addMessageToSource: function(lineNumber, msg) { if (lineNumber >= this._textEditor.linesCount) lineNumber = this._textEditor.linesCount - 1; if (lineNumber < 0) lineNumber = 0; var rowMessages = this._rowMessages[lineNumber]; if (!rowMessages) { rowMessages = []; this._rowMessages[lineNumber] = rowMessages; } for (var i = 0; i < rowMessages.length; ++i) { if (rowMessages[i].consoleMessage.isEqual(msg)) { rowMessages[i].repeatCount = msg.totalRepeatCount; this._updateMessageRepeatCount(rowMessages[i]); return; } } var rowMessage = { consoleMessage: msg }; rowMessages.push(rowMessage); this._textEditor.beginUpdates(); var messageBubbleElement = this._messageBubbles[lineNumber]; if (!messageBubbleElement) { messageBubbleElement = document.createElement("div"); messageBubbleElement.className = "webkit-html-message-bubble"; this._messageBubbles[lineNumber] = messageBubbleElement; this._textEditor.addDecoration(lineNumber, messageBubbleElement); } var imageElement = document.createElement("div"); switch (msg.level) { case WebInspector.ConsoleMessage.MessageLevel.Error: messageBubbleElement.classList.add("webkit-html-error-message"); imageElement.className = "error-icon-small"; break; case WebInspector.ConsoleMessage.MessageLevel.Warning: messageBubbleElement.classList.add("webkit-html-warning-message"); imageElement.className = "warning-icon-small"; break; } var messageLineElement = document.createElement("div"); messageLineElement.className = "webkit-html-message-line"; messageBubbleElement.appendChild(messageLineElement); // Create the image element in the Inspector's document so we can use relative image URLs. messageLineElement.appendChild(imageElement); messageLineElement.appendChild(document.createTextNode(msg.message)); rowMessage.element = messageLineElement; rowMessage.repeatCount = msg.totalRepeatCount; this._updateMessageRepeatCount(rowMessage); this._textEditor.endUpdates(); }, _updateMessageRepeatCount: function(rowMessage) { if (rowMessage.repeatCount < 2) return; if (!rowMessage.repeatCountElement) { var repeatCountElement = document.createElement("span"); rowMessage.element.appendChild(repeatCountElement); rowMessage.repeatCountElement = repeatCountElement; } rowMessage.repeatCountElement.textContent = WebInspector.UIString(" (repeated %d times)", rowMessage.repeatCount); }, /** * @param {number} lineNumber * @param {!WebInspector.ConsoleMessage} msg */ removeMessageFromSource: function(lineNumber, msg) { if (lineNumber >= this._textEditor.linesCount) lineNumber = this._textEditor.linesCount - 1; if (lineNumber < 0) lineNumber = 0; var rowMessages = this._rowMessages[lineNumber]; for (var i = 0; rowMessages && i < rowMessages.length; ++i) { var rowMessage = rowMessages[i]; if (rowMessage.consoleMessage !== msg) continue; var messageLineElement = rowMessage.element; var messageBubbleElement = messageLineElement.parentElement; messageBubbleElement.removeChild(messageLineElement); rowMessages.remove(rowMessage); if (!rowMessages.length) delete this._rowMessages[lineNumber]; if (!messageBubbleElement.childElementCount) { this._textEditor.removeDecoration(lineNumber, messageBubbleElement); delete this._messageBubbles[lineNumber]; } break; } }, populateLineGutterContextMenu: function(contextMenu, lineNumber) { }, populateTextAreaContextMenu: function(contextMenu, lineNumber) { }, inheritScrollPositions: function(sourceFrame) { this._textEditor.inheritScrollPositions(sourceFrame._textEditor); }, /** * @return {boolean} */ canEditSource: function() { return false; }, /** * @param {string} text */ commitEditing: function(text) { }, /** * @param {!WebInspector.TextRange} textRange */ selectionChanged: function(textRange) { this._updateSourcePosition(textRange); this.dispatchEventToListeners(WebInspector.SourceFrame.Events.SelectionChanged, textRange); WebInspector.notifications.dispatchEventToListeners(WebInspector.SourceFrame.Events.SelectionChanged, textRange); }, /** * @param {!WebInspector.TextRange} textRange */ _updateSourcePosition: function(textRange) { if (!textRange) return; if (textRange.isEmpty()) { this._sourcePosition.setText(WebInspector.UIString("Line %d, Column %d", textRange.endLine + 1, textRange.endColumn + 1)); return; } textRange = textRange.normalize(); var selectedText = this._textEditor.copyRange(textRange); if (textRange.startLine === textRange.endLine) this._sourcePosition.setText(WebInspector.UIString("%d characters selected", selectedText.length)); else this._sourcePosition.setText(WebInspector.UIString("%d lines, %d characters selected", textRange.endLine - textRange.startLine + 1, selectedText.length)); }, /** * @param {number} lineNumber */ scrollChanged: function(lineNumber) { this.dispatchEventToListeners(WebInspector.SourceFrame.Events.ScrollChanged, lineNumber); }, _handleKeyDown: function(e) { var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent(e); var handler = this._shortcuts[shortcutKey]; if (handler && handler()) e.consume(true); }, _commitEditing: function() { if (this._textEditor.readOnly()) return false; var content = this._textEditor.text(); this.commitEditing(content); return true; }, __proto__: WebInspector.View.prototype } /** * @implements {WebInspector.TextEditorDelegate} * @constructor */ WebInspector.TextEditorDelegateForSourceFrame = function(sourceFrame) { this._sourceFrame = sourceFrame; } WebInspector.TextEditorDelegateForSourceFrame.prototype = { onTextChanged: function(oldRange, newRange) { this._sourceFrame.onTextChanged(oldRange, newRange); }, /** * @param {!WebInspector.TextRange} textRange */ selectionChanged: function(textRange) { this._sourceFrame.selectionChanged(textRange); }, /** * @param {number} lineNumber */ scrollChanged: function(lineNumber) { this._sourceFrame.scrollChanged(lineNumber); }, editorFocused: function() { this._sourceFrame._editorFocused(); }, populateLineGutterContextMenu: function(contextMenu, lineNumber) { this._sourceFrame.populateLineGutterContextMenu(contextMenu, lineNumber); }, populateTextAreaContextMenu: function(contextMenu, lineNumber) { this._sourceFrame.populateTextAreaContextMenu(contextMenu, lineNumber); }, /** * @param {string} hrefValue * @param {boolean} isExternal * @return {!Element} */ createLink: function(hrefValue, isExternal) { var targetLocation = WebInspector.ParsedURL.completeURL(this._sourceFrame._url, hrefValue); return WebInspector.linkifyURLAsNode(targetLocation || hrefValue, hrefValue, undefined, isExternal); }, __proto__: WebInspector.TextEditorDelegate.prototype }
{ "pile_set_name": "Github" }
/* * xxhsum - Command line interface for xxhash algorithms * Copyright (C) 2013-2020 Yann Collet * * GPL v2 License * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * You can contact the author at: * - xxHash homepage: https://www.xxhash.com * - xxHash source repository: https://github.com/Cyan4973/xxHash */ /* * Checks for predefined macros by the compiler to try and get both the arch * and the compiler version. */ #ifndef XSUM_ARCH_H #define XSUM_ARCH_H #include "xsum_config.h" #define XSUM_LIB_VERSION XXH_VERSION_MAJOR.XXH_VERSION_MINOR.XXH_VERSION_RELEASE #define XSUM_QUOTE(str) #str #define XSUM_EXPAND_AND_QUOTE(str) XSUM_QUOTE(str) #define XSUM_PROGRAM_VERSION XSUM_EXPAND_AND_QUOTE(XSUM_LIB_VERSION) /* Show compiler versions in WELCOME_MESSAGE. XSUM_CC_VERSION_FMT will return the printf specifiers, * and VERSION will contain the comma separated list of arguments to the XSUM_CC_VERSION_FMT string. */ #if defined(__clang_version__) /* Clang does its own thing. */ # ifdef __apple_build_version__ # define XSUM_CC_VERSION_FMT "Apple Clang %s" # else # define XSUM_CC_VERSION_FMT "Clang %s" # endif # define XSUM_CC_VERSION __clang_version__ #elif defined(__VERSION__) /* GCC and ICC */ # define XSUM_CC_VERSION_FMT "%s" # ifdef __INTEL_COMPILER /* icc adds its prefix */ # define XSUM_CC_VERSION __VERSION__ # else /* assume GCC */ # define XSUM_CC_VERSION "GCC " __VERSION__ # endif #elif defined(_MSC_FULL_VER) && defined(_MSC_BUILD) /* * MSVC * "For example, if the version number of the Visual C++ compiler is * 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706." * * https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=vs-2017 */ # define XSUM_CC_VERSION_FMT "MSVC %02i.%02i.%05i.%02i" # define XSUM_CC_VERSION _MSC_FULL_VER / 10000000 % 100, _MSC_FULL_VER / 100000 % 100, _MSC_FULL_VER % 100000, _MSC_BUILD #elif defined(_MSC_VER) /* old MSVC */ # define XSUM_CC_VERSION_FMT "MSVC %02i.%02i" # define XSUM_CC_VERSION _MSC_VER / 100, _MSC_VER % 100 #elif defined(__TINYC__) /* tcc stores its version in the __TINYC__ macro. */ # define XSUM_CC_VERSION_FMT "tcc %i.%i.%i" # define XSUM_CC_VERSION __TINYC__ / 10000 % 100, __TINYC__ / 100 % 100, __TINYC__ % 100 #else # define XSUM_CC_VERSION_FMT "%s" # define XSUM_CC_VERSION "unknown compiler" #endif /* makes the next part easier */ #if defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64) # define XSUM_ARCH_X64 1 # define XSUM_ARCH_X86 "x86_64" #elif defined(__i386__) || defined(_M_IX86) || defined(_M_IX86_FP) # define XSUM_ARCH_X86 "i386" #endif /* Try to detect the architecture. */ #if defined(ARCH_X86) # if defined(XXHSUM_DISPATCH) # define XSUM_ARCH XSUM_ARCH_X86 " autoVec" # elif defined(__AVX512F__) # define XSUM_ARCH XSUM_ARCH_X86 " + AVX512" # elif defined(__AVX2__) # define XSUM_ARCH XSUM_ARCH_X86 " + AVX2" # elif defined(__AVX__) # define XSUM_ARCH XSUM_ARCH_X86 " + AVX" # elif defined(_M_X64) || defined(_M_AMD64) || defined(__x86_64__) \ || defined(__SSE2__) || (defined(_M_IX86_FP) && _M_IX86_FP == 2) # define XSUM_ARCH XSUM_ARCH_X86 " + SSE2" # else # define XSUM_ARCH XSUM_ARCH_X86 # endif #elif defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64) # define XSUM_ARCH "aarch64 + NEON" #elif defined(__arm__) || defined(__thumb__) || defined(__thumb2__) || defined(_M_ARM) /* ARM has a lot of different features that can change xxHash significantly. */ # if defined(__thumb2__) || (defined(__thumb__) && (__thumb__ == 2 || __ARM_ARCH >= 7)) # define XSUM_ARCH_THUMB " Thumb-2" # elif defined(__thumb__) # define XSUM_ARCH_THUMB " Thumb-1" # else # define XSUM_ARCH_THUMB "" # endif /* ARMv7 has unaligned by default */ # if defined(__ARM_FEATURE_UNALIGNED) || __ARM_ARCH >= 7 || defined(_M_ARMV7VE) # define XSUM_ARCH_UNALIGNED " + unaligned" # else # define XSUM_ARCH_UNALIGNED "" # endif # if defined(__ARM_NEON) || defined(__ARM_NEON__) # define XSUM_ARCH_NEON " + NEON" # else # define XSUM_ARCH_NEON "" # endif # define XSUM_ARCH "ARMv" XSUM_EXPAND_AND_QUOTE(__ARM_ARCH) XSUM_ARCH_THUMB XSUM_ARCH_NEON XSUM_ARCH_UNALIGNED #elif defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) # if defined(__GNUC__) && defined(__POWER9_VECTOR__) # define XSUM_ARCH "ppc64 + POWER9 vector" # elif defined(__GNUC__) && defined(__POWER8_VECTOR__) # define XSUM_ARCH "ppc64 + POWER8 vector" # else # define XSUM_ARCH "ppc64" # endif #elif defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) # define XSUM_ARCH "ppc" #elif defined(__AVR) # define XSUM_ARCH "AVR" #elif defined(__mips64) # define XSUM_ARCH "mips64" #elif defined(__mips) # define XSUM_ARCH "mips" #elif defined(__s390x__) # define XSUM_ARCH "s390x" #elif defined(__s390__) # define XSUM_ARCH "s390" #else # define XSUM_ARCH "unknown" #endif #endif /* XSUM_ARCH_H */
{ "pile_set_name": "Github" }
"""Implementation of JSONDecoder """ import binascii import re import sys import struct from json import scanner try: from _json import scanstring as c_scanstring except ImportError: c_scanstring = None __all__ = ['JSONDecoder'] FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL def _floatconstants(): _BYTES = binascii.unhexlify(b'7FF80000000000007FF0000000000000') if sys.byteorder != 'big': _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] nan, inf = struct.unpack('dd', _BYTES) return nan, inf, -inf NaN, PosInf, NegInf = _floatconstants() def linecol(doc, pos): if isinstance(doc, bytes): newline = b'\n' else: newline = '\n' lineno = doc.count(newline, 0, pos) + 1 if lineno == 1: colno = pos + 1 else: colno = pos - doc.rindex(newline, 0, pos) return lineno, colno def errmsg(msg, doc, pos, end=None): # Note that this function is called from _json lineno, colno = linecol(doc, pos) if end is None: fmt = '{0}: line {1} column {2} (char {3})' return fmt.format(msg, lineno, colno, pos) #fmt = '%s: line %d column %d (char %d)' #return fmt % (msg, lineno, colno, pos) endlineno, endcolno = linecol(doc, end) fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})' return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end) #fmt = '%s: line %d column %d - line %d column %d (char %d - %d)' #return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end) _CONSTANTS = { '-Infinity': NegInf, 'Infinity': PosInf, 'NaN': NaN, } STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) BACKSLASH = { '"': '"', '\\': '\\', '/': '/', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', } def py_scanstring(s, end, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): """Scan the string s for a JSON string. End is the index of the character in s after the quote that started the JSON string. Unescapes all valid JSON string escape sequences and raises ValueError on attempt to decode an invalid string. If strict is False then literal control characters are allowed in the string. Returns a tuple of the decoded string and the index of the character in s after the end quote.""" chunks = [] _append = chunks.append begin = end - 1 while 1: chunk = _m(s, end) if chunk is None: raise ValueError( errmsg("Unterminated string starting at", s, begin)) end = chunk.end() content, terminator = chunk.groups() # Content is contains zero or more unescaped string characters if content: _append(content) # Terminator is the end of string, a literal control character, # or a backslash denoting that an escape sequence follows if terminator == '"': break elif terminator != '\\': if strict: #msg = "Invalid control character %r at" % (terminator,) msg = "Invalid control character {0!r} at".format(terminator) raise ValueError(errmsg(msg, s, end)) else: _append(terminator) continue try: esc = s[end] except IndexError: raise ValueError( errmsg("Unterminated string starting at", s, begin)) # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: char = _b[esc] except KeyError: msg = "Invalid \\escape: {0!r}".format(esc) raise ValueError(errmsg(msg, s, end)) end += 1 else: esc = s[end + 1:end + 5] next_end = end + 5 if len(esc) != 4: msg = "Invalid \\uXXXX escape" raise ValueError(errmsg(msg, s, end)) uni = int(esc, 16) # Check for surrogate pair on UCS-4 systems if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: msg = "Invalid \\uXXXX\\uXXXX surrogate pair" if not s[end + 5:end + 7] == '\\u': raise ValueError(errmsg(msg, s, end)) esc2 = s[end + 7:end + 11] if len(esc2) != 4: raise ValueError(errmsg(msg, s, end)) uni2 = int(esc2, 16) uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) next_end += 6 char = chr(uni) end = next_end _append(char) return ''.join(chunks), end # Use speedup if available scanstring = c_scanstring or py_scanstring WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) WHITESPACE_STR = ' \t\n\r' def JSONObject(s_and_end, strict, scan_once, object_hook, object_pairs_hook, memo=None, _w=WHITESPACE.match, _ws=WHITESPACE_STR): s, end = s_and_end pairs = [] pairs_append = pairs.append # Backwards compatibility if memo is None: memo = {} memo_get = memo.setdefault # Use a slice to prevent IndexError from being raised, the following # check will raise a more specific ValueError if the string is empty nextchar = s[end:end + 1] # Normally we expect nextchar == '"' if nextchar != '"': if nextchar in _ws: end = _w(s, end).end() nextchar = s[end:end + 1] # Trivial empty object if nextchar == '}': if object_pairs_hook is not None: result = object_pairs_hook(pairs) return result, end + 1 pairs = {} if object_hook is not None: pairs = object_hook(pairs) return pairs, end + 1 elif nextchar != '"': raise ValueError(errmsg( "Expecting property name enclosed in double quotes", s, end)) end += 1 while True: key, end = scanstring(s, end, strict) key = memo_get(key, key) # To skip some function call overhead we optimize the fast paths where # the JSON key separator is ": " or just ":". if s[end:end + 1] != ':': end = _w(s, end).end() if s[end:end + 1] != ':': raise ValueError(errmsg("Expecting ':' delimiter", s, end)) end += 1 try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) pairs_append((key, value)) try: nextchar = s[end] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end] except IndexError: nextchar = '' end += 1 if nextchar == '}': break elif nextchar != ',': raise ValueError(errmsg("Expecting ',' delimiter", s, end - 1)) end = _w(s, end).end() nextchar = s[end:end + 1] end += 1 if nextchar != '"': raise ValueError(errmsg( "Expecting property name enclosed in double quotes", s, end - 1)) if object_pairs_hook is not None: result = object_pairs_hook(pairs) return result, end pairs = dict(pairs) if object_hook is not None: pairs = object_hook(pairs) return pairs, end def JSONArray(s_and_end, scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR): s, end = s_and_end values = [] nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] # Look-ahead for trivial empty array if nextchar == ']': return values, end + 1 _append = values.append while True: try: value, end = scan_once(s, end) except StopIteration: raise ValueError(errmsg("Expecting object", s, end)) _append(value) nextchar = s[end:end + 1] if nextchar in _ws: end = _w(s, end + 1).end() nextchar = s[end:end + 1] end += 1 if nextchar == ']': break elif nextchar != ',': raise ValueError(errmsg("Expecting ',' delimiter", s, end)) try: if s[end] in _ws: end += 1 if s[end] in _ws: end = _w(s, end + 1).end() except IndexError: pass return values, end class JSONDecoder(object): """Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | str | +---------------+-------------------+ | number (int) | int | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """ def __init__(self, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None): """``object_hook``, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given ``dict``. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). ``object_pairs_hook``, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict will remember the order of insertion). If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. If ``strict`` is false (true is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``. """ self.object_hook = object_hook self.parse_float = parse_float or float self.parse_int = parse_int or int self.parse_constant = parse_constant or _CONSTANTS.__getitem__ self.strict = strict self.object_pairs_hook = object_pairs_hook self.parse_object = JSONObject self.parse_array = JSONArray self.parse_string = scanstring self.memo = {} self.scan_once = scanner.make_scanner(self) def decode(self, s, _w=WHITESPACE.match): """Return the Python representation of ``s`` (a ``str`` instance containing a JSON document). """ obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise ValueError(errmsg("Extra data", s, end, len(s))) return obj def raw_decode(self, s, idx=0): """Decode a JSON document from ``s`` (a ``str`` beginning with a JSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a JSON document from a string that may have extraneous data at the end. """ try: obj, end = self.scan_once(s, idx) except StopIteration: raise ValueError("No JSON object could be decoded") return obj, end
{ "pile_set_name": "Github" }
<?php global $wgScriptPath, $wgStylePath, $wgBlankImgUrl; ?> <div class="CustomizePlatinum"> <!-- new platinum badge form --> <form id="createPlatinumForm" class="clearfix" action="<?= $wgScriptPath ?>/index.php?action=ajax&amp;rs=AchAjax&amp;method=addPlatinumBadge" method="POST" onsubmit="return SpecialCustomizePlatinum.addSubmit(this)" enctype="multipart/form-data"> <fieldset class="customize-platinum-badge new editable"> <legend> <input name="badge_name" type="text" class="dark_text_2" /> </legend> <div class="column description-fields"> <label><?=wfMsg('achievements-community-platinum-awarded-for');?></label><span class="input-suggestion">&nbsp;(<?=wfMsg('achievements-community-platinum-awarded-for-example');?>)</span> <textarea name="awarded_for"></textarea> <label><?=wfMsg('achievements-community-platinum-how-to-earn');?></label><span class="input-suggestion">&nbsp;(<?=wfMsg('achievements-community-platinum-how-to-earn-example');?>)</span> <textarea name="how_to"></textarea> </div> <div class="column"> <label><?=wfMsg('achievements-community-platinum-badge-image');?></label> <img src="<?= $wgBlankImgUrl ?>" class="badge-preview neutral" /> <input type="file" name="wpUploadFile" /> </div> <div class="clearfix"></div> <div class="sponsored-fields"> <div class="clearfix sponsored-fields-1"> <input type="checkbox" name="is_sponsored" value="1"/> <label><?=wfMsg('achievements-community-platinum-sponsored-label');?></label> </div> <div class="sponsored-fields-3" style="display:none;"> <label for="hover_content"><?=wfMsg('achievements-community-platinum-sponsored-hover-content-label');?></label> <input type="file" name="hover_content"/> <label for="hover_impression_pixel_url"><?=wfMsg('achievements-community-platinum-sponsored-hover-impression-pixel-url-label');?></label> <input type="text" name="hover_impression_pixel_url"/> <label for="badge_impression_pixel_url"><?=wfMsg('achievements-community-platinum-sponsored-badge-impression-pixel-url-label');?></label> <input type="text" name="badge_impression_pixel_url"/> <label for="badge_redirect_url"><?=wfMsg('achievements-community-platinum-sponsored-badge-click-url-label');?></label> <input type="text" name="badge_redirect_url"/> </div> </div> <div class="commands accent"> <input type="submit" value="<?=wfMsg('achievements-community-platinum-create-badge');?>"/> </div> </fieldset> </form> <h2><?=wfMsg('achievements-community-platinum-current-badges');?></h2> <?php foreach($badges as $badge) { echo AchPlatinumService::getPlatinumForm($badge); } ?> </div>
{ "pile_set_name": "Github" }
# -*- test-case-name: twisted.news.test.test_nntp -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ NNTP protocol support. Maintainer: Jp Calderone The following protocol commands are currently understood:: LIST LISTGROUP XOVER XHDR POST GROUP ARTICLE STAT HEAD BODY NEXT MODE STREAM MODE READER SLAVE LAST QUIT HELP IHAVE XPATH XINDEX XROVER TAKETHIS CHECK The following protocol commands require implementation:: NEWNEWS XGTITLE XPAT XTHREAD AUTHINFO NEWGROUPS Other desired features: - A real backend - More robust client input handling - A control protocol """ import time import types try: import cStringIO as StringIO except: import StringIO from twisted.protocols import basic from twisted.python import log def parseRange(text): articles = text.split('-') if len(articles) == 1: try: a = int(articles[0]) return a, a except ValueError, e: return None, None elif len(articles) == 2: try: if len(articles[0]): l = int(articles[0]) else: l = None if len(articles[1]): h = int(articles[1]) else: h = None except ValueError, e: return None, None return l, h def extractCode(line): line = line.split(' ', 1) if len(line) != 2: return None try: return int(line[0]), line[1] except ValueError: return None class NNTPError(Exception): def __init__(self, string): self.string = string def __str__(self): return 'NNTPError: %s' % self.string class NNTPClient(basic.LineReceiver): MAX_COMMAND_LENGTH = 510 def __init__(self): self.currentGroup = None self._state = [] self._error = [] self._inputBuffers = [] self._responseCodes = [] self._responseHandlers = [] self._postText = [] self._newState(self._statePassive, None, self._headerInitial) def gotAllGroups(self, groups): "Override for notification when fetchGroups() action is completed" def getAllGroupsFailed(self, error): "Override for notification when fetchGroups() action fails" def gotOverview(self, overview): "Override for notification when fetchOverview() action is completed" def getOverviewFailed(self, error): "Override for notification when fetchOverview() action fails" def gotSubscriptions(self, subscriptions): "Override for notification when fetchSubscriptions() action is completed" def getSubscriptionsFailed(self, error): "Override for notification when fetchSubscriptions() action fails" def gotGroup(self, group): "Override for notification when fetchGroup() action is completed" def getGroupFailed(self, error): "Override for notification when fetchGroup() action fails" def gotArticle(self, article): "Override for notification when fetchArticle() action is completed" def getArticleFailed(self, error): "Override for notification when fetchArticle() action fails" def gotHead(self, head): "Override for notification when fetchHead() action is completed" def getHeadFailed(self, error): "Override for notification when fetchHead() action fails" def gotBody(self, info): "Override for notification when fetchBody() action is completed" def getBodyFailed(self, body): "Override for notification when fetchBody() action fails" def postedOk(self): "Override for notification when postArticle() action is successful" def postFailed(self, error): "Override for notification when postArticle() action fails" def gotXHeader(self, headers): "Override for notification when getXHeader() action is successful" def getXHeaderFailed(self, error): "Override for notification when getXHeader() action fails" def gotNewNews(self, news): "Override for notification when getNewNews() action is successful" def getNewNewsFailed(self, error): "Override for notification when getNewNews() action fails" def gotNewGroups(self, groups): "Override for notification when getNewGroups() action is successful" def getNewGroupsFailed(self, error): "Override for notification when getNewGroups() action fails" def setStreamSuccess(self): "Override for notification when setStream() action is successful" def setStreamFailed(self, error): "Override for notification when setStream() action fails" def fetchGroups(self): """ Request a list of all news groups from the server. gotAllGroups() is called on success, getGroupsFailed() on failure """ self.sendLine('LIST') self._newState(self._stateList, self.getAllGroupsFailed) def fetchOverview(self): """ Request the overview format from the server. gotOverview() is called on success, getOverviewFailed() on failure """ self.sendLine('LIST OVERVIEW.FMT') self._newState(self._stateOverview, self.getOverviewFailed) def fetchSubscriptions(self): """ Request a list of the groups it is recommended a new user subscribe to. gotSubscriptions() is called on success, getSubscriptionsFailed() on failure """ self.sendLine('LIST SUBSCRIPTIONS') self._newState(self._stateSubscriptions, self.getSubscriptionsFailed) def fetchGroup(self, group): """ Get group information for the specified group from the server. gotGroup() is called on success, getGroupFailed() on failure. """ self.sendLine('GROUP %s' % (group,)) self._newState(None, self.getGroupFailed, self._headerGroup) def fetchHead(self, index = ''): """ Get the header for the specified article (or the currently selected article if index is '') from the server. gotHead() is called on success, getHeadFailed() on failure """ self.sendLine('HEAD %s' % (index,)) self._newState(self._stateHead, self.getHeadFailed) def fetchBody(self, index = ''): """ Get the body for the specified article (or the currently selected article if index is '') from the server. gotBody() is called on success, getBodyFailed() on failure """ self.sendLine('BODY %s' % (index,)) self._newState(self._stateBody, self.getBodyFailed) def fetchArticle(self, index = ''): """ Get the complete article with the specified index (or the currently selected article if index is '') or Message-ID from the server. gotArticle() is called on success, getArticleFailed() on failure. """ self.sendLine('ARTICLE %s' % (index,)) self._newState(self._stateArticle, self.getArticleFailed) def postArticle(self, text): """ Attempt to post an article with the specified text to the server. 'text' must consist of both head and body data, as specified by RFC 850. If the article is posted successfully, postedOk() is called, otherwise postFailed() is called. """ self.sendLine('POST') self._newState(None, self.postFailed, self._headerPost) self._postText.append(text) def fetchNewNews(self, groups, date, distributions = ''): """ Get the Message-IDs for all new news posted to any of the given groups since the specified date - in seconds since the epoch, GMT - optionally restricted to the given distributions. gotNewNews() is called on success, getNewNewsFailed() on failure. One invocation of this function may result in multiple invocations of gotNewNews()/getNewNewsFailed(). """ date, timeStr = time.strftime('%y%m%d %H%M%S', time.gmtime(date)).split() line = 'NEWNEWS %%s %s %s %s' % (date, timeStr, distributions) groupPart = '' while len(groups) and len(line) + len(groupPart) + len(groups[-1]) + 1 < NNTPClient.MAX_COMMAND_LENGTH: group = groups.pop() groupPart = groupPart + ',' + group self.sendLine(line % (groupPart,)) self._newState(self._stateNewNews, self.getNewNewsFailed) if len(groups): self.fetchNewNews(groups, date, distributions) def fetchNewGroups(self, date, distributions): """ Get the names of all new groups created/added to the server since the specified date - in seconds since the ecpoh, GMT - optionally restricted to the given distributions. gotNewGroups() is called on success, getNewGroupsFailed() on failure. """ date, timeStr = time.strftime('%y%m%d %H%M%S', time.gmtime(date)).split() self.sendLine('NEWGROUPS %s %s %s' % (date, timeStr, distributions)) self._newState(self._stateNewGroups, self.getNewGroupsFailed) def fetchXHeader(self, header, low = None, high = None, id = None): """ Request a specific header from the server for an article or range of articles. If 'id' is not None, a header for only the article with that Message-ID will be requested. If both low and high are None, a header for the currently selected article will be selected; If both low and high are zero-length strings, headers for all articles in the currently selected group will be requested; Otherwise, high and low will be used as bounds - if one is None the first or last article index will be substituted, as appropriate. """ if id is not None: r = header + ' <%s>' % (id,) elif low is high is None: r = header elif high is None: r = header + ' %d-' % (low,) elif low is None: r = header + ' -%d' % (high,) else: r = header + ' %d-%d' % (low, high) self.sendLine('XHDR ' + r) self._newState(self._stateXHDR, self.getXHeaderFailed) def setStream(self): """ Set the mode to STREAM, suspending the normal "lock-step" mode of communications. setStreamSuccess() is called on success, setStreamFailed() on failure. """ self.sendLine('MODE STREAM') self._newState(None, self.setStreamFailed, self._headerMode) def quit(self): self.sendLine('QUIT') self.transport.loseConnection() def _newState(self, method, error, responseHandler = None): self._inputBuffers.append([]) self._responseCodes.append(None) self._state.append(method) self._error.append(error) self._responseHandlers.append(responseHandler) def _endState(self): buf = self._inputBuffers[0] del self._responseCodes[0] del self._inputBuffers[0] del self._state[0] del self._error[0] del self._responseHandlers[0] return buf def _newLine(self, line, check = 1): if check and line and line[0] == '.': line = line[1:] self._inputBuffers[0].append(line) def _setResponseCode(self, code): self._responseCodes[0] = code def _getResponseCode(self): return self._responseCodes[0] def lineReceived(self, line): if not len(self._state): self._statePassive(line) elif self._getResponseCode() is None: code = extractCode(line) if code is None or not (200 <= code[0] < 400): # An error! self._error[0](line) self._endState() else: self._setResponseCode(code) if self._responseHandlers[0]: self._responseHandlers[0](code) else: self._state[0](line) def _statePassive(self, line): log.msg('Server said: %s' % line) def _passiveError(self, error): log.err('Passive Error: %s' % (error,)) def _headerInitial(self, (code, message)): if code == 200: self.canPost = 1 else: self.canPost = 0 self._endState() def _stateList(self, line): if line != '.': data = filter(None, line.strip().split()) self._newLine((data[0], int(data[1]), int(data[2]), data[3]), 0) else: self.gotAllGroups(self._endState()) def _stateOverview(self, line): if line != '.': self._newLine(filter(None, line.strip().split()), 0) else: self.gotOverview(self._endState()) def _stateSubscriptions(self, line): if line != '.': self._newLine(line.strip(), 0) else: self.gotSubscriptions(self._endState()) def _headerGroup(self, (code, line)): self.gotGroup(tuple(line.split())) self._endState() def _stateArticle(self, line): if line != '.': if line.startswith('.'): line = line[1:] self._newLine(line, 0) else: self.gotArticle('\n'.join(self._endState())+'\n') def _stateHead(self, line): if line != '.': self._newLine(line, 0) else: self.gotHead('\n'.join(self._endState())) def _stateBody(self, line): if line != '.': if line.startswith('.'): line = line[1:] self._newLine(line, 0) else: self.gotBody('\n'.join(self._endState())+'\n') def _headerPost(self, (code, message)): if code == 340: self.transport.write(self._postText[0].replace('\n', '\r\n').replace('\r\n.', '\r\n..')) if self._postText[0][-1:] != '\n': self.sendLine('') self.sendLine('.') del self._postText[0] self._newState(None, self.postFailed, self._headerPosted) else: self.postFailed('%d %s' % (code, message)) self._endState() def _headerPosted(self, (code, message)): if code == 240: self.postedOk() else: self.postFailed('%d %s' % (code, message)) self._endState() def _stateXHDR(self, line): if line != '.': self._newLine(line.split(), 0) else: self._gotXHeader(self._endState()) def _stateNewNews(self, line): if line != '.': self._newLine(line, 0) else: self.gotNewNews(self._endState()) def _stateNewGroups(self, line): if line != '.': self._newLine(line, 0) else: self.gotNewGroups(self._endState()) def _headerMode(self, (code, message)): if code == 203: self.setStreamSuccess() else: self.setStreamFailed((code, message)) self._endState() class NNTPServer(basic.LineReceiver): COMMANDS = [ 'LIST', 'GROUP', 'ARTICLE', 'STAT', 'MODE', 'LISTGROUP', 'XOVER', 'XHDR', 'HEAD', 'BODY', 'NEXT', 'LAST', 'POST', 'QUIT', 'IHAVE', 'HELP', 'SLAVE', 'XPATH', 'XINDEX', 'XROVER', 'TAKETHIS', 'CHECK' ] def __init__(self): self.servingSlave = 0 def connectionMade(self): self.inputHandler = None self.currentGroup = None self.currentIndex = None self.sendLine('200 server ready - posting allowed') def lineReceived(self, line): if self.inputHandler is not None: self.inputHandler(line) else: parts = line.strip().split() if len(parts): cmd, parts = parts[0].upper(), parts[1:] if cmd in NNTPServer.COMMANDS: func = getattr(self, 'do_%s' % cmd) try: func(*parts) except TypeError: self.sendLine('501 command syntax error') log.msg("501 command syntax error") log.msg("command was", line) log.deferr() except: self.sendLine('503 program fault - command not performed') log.msg("503 program fault") log.msg("command was", line) log.deferr() else: self.sendLine('500 command not recognized') def do_LIST(self, subcmd = '', *dummy): subcmd = subcmd.strip().lower() if subcmd == 'newsgroups': # XXX - this could use a real implementation, eh? self.sendLine('215 Descriptions in form "group description"') self.sendLine('.') elif subcmd == 'overview.fmt': defer = self.factory.backend.overviewRequest() defer.addCallbacks(self._gotOverview, self._errOverview) log.msg('overview') elif subcmd == 'subscriptions': defer = self.factory.backend.subscriptionRequest() defer.addCallbacks(self._gotSubscription, self._errSubscription) log.msg('subscriptions') elif subcmd == '': defer = self.factory.backend.listRequest() defer.addCallbacks(self._gotList, self._errList) else: self.sendLine('500 command not recognized') def _gotList(self, list): self.sendLine('215 newsgroups in form "group high low flags"') for i in list: self.sendLine('%s %d %d %s' % tuple(i)) self.sendLine('.') def _errList(self, failure): print 'LIST failed: ', failure self.sendLine('503 program fault - command not performed') def _gotSubscription(self, parts): self.sendLine('215 information follows') for i in parts: self.sendLine(i) self.sendLine('.') def _errSubscription(self, failure): print 'SUBSCRIPTIONS failed: ', failure self.sendLine('503 program fault - comand not performed') def _gotOverview(self, parts): self.sendLine('215 Order of fields in overview database.') for i in parts: self.sendLine(i + ':') self.sendLine('.') def _errOverview(self, failure): print 'LIST OVERVIEW.FMT failed: ', failure self.sendLine('503 program fault - command not performed') def do_LISTGROUP(self, group = None): group = group or self.currentGroup if group is None: self.sendLine('412 Not currently in newsgroup') else: defer = self.factory.backend.listGroupRequest(group) defer.addCallbacks(self._gotListGroup, self._errListGroup) def _gotListGroup(self, (group, articles)): self.currentGroup = group if len(articles): self.currentIndex = int(articles[0]) else: self.currentIndex = None self.sendLine('211 list of article numbers follow') for i in articles: self.sendLine(str(i)) self.sendLine('.') def _errListGroup(self, failure): print 'LISTGROUP failed: ', failure self.sendLine('502 no permission') def do_XOVER(self, range): if self.currentGroup is None: self.sendLine('412 No news group currently selected') else: l, h = parseRange(range) defer = self.factory.backend.xoverRequest(self.currentGroup, l, h) defer.addCallbacks(self._gotXOver, self._errXOver) def _gotXOver(self, parts): self.sendLine('224 Overview information follows') for i in parts: self.sendLine('\t'.join(map(str, i))) self.sendLine('.') def _errXOver(self, failure): print 'XOVER failed: ', failure self.sendLine('420 No article(s) selected') def xhdrWork(self, header, range): if self.currentGroup is None: self.sendLine('412 No news group currently selected') else: if range is None: if self.currentIndex is None: self.sendLine('420 No current article selected') return else: l = h = self.currentIndex else: # FIXME: articles may be a message-id l, h = parseRange(range) if l is h is None: self.sendLine('430 no such article') else: return self.factory.backend.xhdrRequest(self.currentGroup, l, h, header) def do_XHDR(self, header, range = None): d = self.xhdrWork(header, range) if d: d.addCallbacks(self._gotXHDR, self._errXHDR) def _gotXHDR(self, parts): self.sendLine('221 Header follows') for i in parts: self.sendLine('%d %s' % i) self.sendLine('.') def _errXHDR(self, failure): print 'XHDR failed: ', failure self.sendLine('502 no permission') def do_XROVER(self, header, range = None): d = self.xhdrWork(header, range) if d: d.addCallbacks(self._gotXROVER, self._errXROVER) def _gotXROVER(self, parts): self.sendLine('224 Overview information follows') for i in parts: self.sendLine('%d %s' % i) self.sendLine('.') def _errXROVER(self, failure): print 'XROVER failed: ', self._errXHDR(failure) def do_POST(self): self.inputHandler = self._doingPost self.message = '' self.sendLine('340 send article to be posted. End with <CR-LF>.<CR-LF>') def _doingPost(self, line): if line == '.': self.inputHandler = None group, article = self.currentGroup, self.message self.message = '' defer = self.factory.backend.postRequest(article) defer.addCallbacks(self._gotPost, self._errPost) else: self.message = self.message + line + '\r\n' def _gotPost(self, parts): self.sendLine('240 article posted ok') def _errPost(self, failure): print 'POST failed: ', failure self.sendLine('441 posting failed') def do_CHECK(self, id): d = self.factory.backend.articleExistsRequest(id) d.addCallbacks(self._gotCheck, self._errCheck) def _gotCheck(self, result): if result: self.sendLine("438 already have it, please don't send it to me") else: self.sendLine('238 no such article found, please send it to me') def _errCheck(self, failure): print 'CHECK failed: ', failure self.sendLine('431 try sending it again later') def do_TAKETHIS(self, id): self.inputHandler = self._doingTakeThis self.message = '' def _doingTakeThis(self, line): if line == '.': self.inputHandler = None article = self.message self.message = '' d = self.factory.backend.postRequest(article) d.addCallbacks(self._didTakeThis, self._errTakeThis) else: self.message = self.message + line + '\r\n' def _didTakeThis(self, result): self.sendLine('239 article transferred ok') def _errTakeThis(self, failure): print 'TAKETHIS failed: ', failure self.sendLine('439 article transfer failed') def do_GROUP(self, group): defer = self.factory.backend.groupRequest(group) defer.addCallbacks(self._gotGroup, self._errGroup) def _gotGroup(self, (name, num, high, low, flags)): self.currentGroup = name self.currentIndex = low self.sendLine('211 %d %d %d %s group selected' % (num, low, high, name)) def _errGroup(self, failure): print 'GROUP failed: ', failure self.sendLine('411 no such group') def articleWork(self, article, cmd, func): if self.currentGroup is None: self.sendLine('412 no newsgroup has been selected') else: if not article: if self.currentIndex is None: self.sendLine('420 no current article has been selected') else: article = self.currentIndex else: if article[0] == '<': return func(self.currentGroup, index = None, id = article) else: try: article = int(article) return func(self.currentGroup, article) except ValueError, e: self.sendLine('501 command syntax error') def do_ARTICLE(self, article = None): defer = self.articleWork(article, 'ARTICLE', self.factory.backend.articleRequest) if defer: defer.addCallbacks(self._gotArticle, self._errArticle) def _gotArticle(self, (index, id, article)): if isinstance(article, types.StringType): import warnings warnings.warn( "Returning the article as a string from `articleRequest' " "is deprecated. Return a file-like object instead." ) article = StringIO.StringIO(article) self.currentIndex = index self.sendLine('220 %d %s article' % (index, id)) s = basic.FileSender() d = s.beginFileTransfer(article, self.transport) d.addCallback(self.finishedFileTransfer) ## ## Helper for FileSender ## def finishedFileTransfer(self, lastsent): if lastsent != '\n': line = '\r\n.' else: line = '.' self.sendLine(line) ## def _errArticle(self, failure): print 'ARTICLE failed: ', failure self.sendLine('423 bad article number') def do_STAT(self, article = None): defer = self.articleWork(article, 'STAT', self.factory.backend.articleRequest) if defer: defer.addCallbacks(self._gotStat, self._errStat) def _gotStat(self, (index, id, article)): self.currentIndex = index self.sendLine('223 %d %s article retreived - request text separately' % (index, id)) def _errStat(self, failure): print 'STAT failed: ', failure self.sendLine('423 bad article number') def do_HEAD(self, article = None): defer = self.articleWork(article, 'HEAD', self.factory.backend.headRequest) if defer: defer.addCallbacks(self._gotHead, self._errHead) def _gotHead(self, (index, id, head)): self.currentIndex = index self.sendLine('221 %d %s article retrieved' % (index, id)) self.transport.write(head + '\r\n') self.sendLine('.') def _errHead(self, failure): print 'HEAD failed: ', failure self.sendLine('423 no such article number in this group') def do_BODY(self, article): defer = self.articleWork(article, 'BODY', self.factory.backend.bodyRequest) if defer: defer.addCallbacks(self._gotBody, self._errBody) def _gotBody(self, (index, id, body)): if isinstance(body, types.StringType): import warnings warnings.warn( "Returning the article as a string from `articleRequest' " "is deprecated. Return a file-like object instead." ) body = StringIO.StringIO(body) self.currentIndex = index self.sendLine('221 %d %s article retrieved' % (index, id)) self.lastsent = '' s = basic.FileSender() d = s.beginFileTransfer(body, self.transport) d.addCallback(self.finishedFileTransfer) def _errBody(self, failure): print 'BODY failed: ', failure self.sendLine('423 no such article number in this group') # NEXT and LAST are just STATs that increment currentIndex first. # Accordingly, use the STAT callbacks. def do_NEXT(self): i = self.currentIndex + 1 defer = self.factory.backend.articleRequest(self.currentGroup, i) defer.addCallbacks(self._gotStat, self._errStat) def do_LAST(self): i = self.currentIndex - 1 defer = self.factory.backend.articleRequest(self.currentGroup, i) defer.addCallbacks(self._gotStat, self._errStat) def do_MODE(self, cmd): cmd = cmd.strip().upper() if cmd == 'READER': self.servingSlave = 0 self.sendLine('200 Hello, you can post') elif cmd == 'STREAM': self.sendLine('500 Command not understood') else: # This is not a mistake self.sendLine('500 Command not understood') def do_QUIT(self): self.sendLine('205 goodbye') self.transport.loseConnection() def do_HELP(self): self.sendLine('100 help text follows') self.sendLine('Read the RFC.') self.sendLine('.') def do_SLAVE(self): self.sendLine('202 slave status noted') self.servingeSlave = 1 def do_XPATH(self, article): # XPATH is a silly thing to have. No client has the right to ask # for this piece of information from me, and so that is what I'll # tell them. self.sendLine('502 access restriction or permission denied') def do_XINDEX(self, article): # XINDEX is another silly command. The RFC suggests it be relegated # to the history books, and who am I to disagree? self.sendLine('502 access restriction or permission denied') def do_XROVER(self, range = None): self.do_XHDR(self, 'References', range) def do_IHAVE(self, id): self.factory.backend.articleExistsRequest(id).addCallback(self._foundArticle) def _foundArticle(self, result): if result: self.sendLine('437 article rejected - do not try again') else: self.sendLine('335 send article to be transferred. End with <CR-LF>.<CR-LF>') self.inputHandler = self._handleIHAVE self.message = '' def _handleIHAVE(self, line): if line == '.': self.inputHandler = None self.factory.backend.postRequest( self.message ).addCallbacks(self._gotIHAVE, self._errIHAVE) self.message = '' else: self.message = self.message + line + '\r\n' def _gotIHAVE(self, result): self.sendLine('235 article transferred ok') def _errIHAVE(self, failure): print 'IHAVE failed: ', failure self.sendLine('436 transfer failed - try again later') class UsenetClientProtocol(NNTPClient): """ A client that connects to an NNTP server and asks for articles new since a certain time. """ def __init__(self, groups, date, storage): """ Fetch all new articles from the given groups since the given date and dump them into the given storage. groups is a list of group names. date is an integer or floating point representing seconds since the epoch (GMT). storage is any object that implements the NewsStorage interface. """ NNTPClient.__init__(self) self.groups, self.date, self.storage = groups, date, storage def connectionMade(self): NNTPClient.connectionMade(self) log.msg("Initiating update with remote host: " + str(self.transport.getPeer())) self.setStream() self.fetchNewNews(self.groups, self.date, '') def articleExists(self, exists, article): if exists: self.fetchArticle(article) else: self.count = self.count - 1 self.disregard = self.disregard + 1 def gotNewNews(self, news): self.disregard = 0 self.count = len(news) log.msg("Transfering " + str(self.count) + " articles from remote host: " + str(self.transport.getPeer())) for i in news: self.storage.articleExistsRequest(i).addCallback(self.articleExists, i) def getNewNewsFailed(self, reason): log.msg("Updated failed (" + reason + ") with remote host: " + str(self.transport.getPeer())) self.quit() def gotArticle(self, article): self.storage.postRequest(article) self.count = self.count - 1 if not self.count: log.msg("Completed update with remote host: " + str(self.transport.getPeer())) if self.disregard: log.msg("Disregarded %d articles." % (self.disregard,)) self.factory.updateChecks(self.transport.getPeer()) self.quit()
{ "pile_set_name": "Github" }
LEVEL = ../../../../make SWIFT_OBJC_INTEROP := 1 DYLIB_SWIFT_SOURCES := dylib.swift DYLIB_NAME := Dylib SWIFTFLAGS_EXTRAS = -Xcc -DDEBUG=1 -Xcc -D -Xcc SPACE -Xcc -U -Xcc NDEBUG include $(LEVEL)/Makefile.rules
{ "pile_set_name": "Github" }
<html> <head> <title>Mono.DocTest.Generic.Func&lt;TArg,TRet&gt;</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style> a { text-decoration: none } div.SideBar { padding-left: 1em; padding-right: 1em; right: 0; float: right; border: thin solid black; background-color: #f2f2f2; } .CollectionTitle { font-weight: bold } .PageTitle { font-size: 150%; font-weight: bold } .Summary { } .Signature { } .Remarks { } .Members { } .Copyright { } .Section { font-size: 125%; font-weight: bold } p.Summary { margin-left: 1em; } .SectionBox { margin-left: 2em } .NamespaceName { font-size: 105%; font-weight: bold } .NamespaceSumary { } .MemberName { font-size: 115%; font-weight: bold; margin-top: 1em } .Subsection { font-size: 105%; font-weight: bold } .SubsectionBox { margin-left: 2em; margin-bottom: 1em } .CodeExampleTable { background-color: #f5f5dd; border: thin solid black; padding: .25em; } .TypesListing { border-collapse: collapse; } td { vertical-align: top; } th { text-align: left; } .TypesListing td { margin: 0px; padding: .25em; border: solid gray 1px; } .TypesListing th { margin: 0px; padding: .25em; background-color: #f2f2f2; border: solid gray 1px; } div.Footer { border-top: 1px solid gray; margin-top: 1.5em; padding-top: 0.6em; text-align: center; color: gray; } span.NotEntered /* Documentation for this section has not yet been entered */ { font-style: italic; color: red; } div.Header { background: #B0C4DE; border: double; border-color: white; border-width: 7px; padding: 0.5em; } div.Header * { font-size: smaller; } div.Note { } i.ParamRef { } i.subtitle { } ul.TypeMembersIndex { text-align: left; background: #F8F8F8; } ul.TypeMembersIndex li { display: inline; margin: 0.5em; } table.HeaderTable { } table.SignatureTable { } table.Documentation, table.Enumeration, table.TypeDocumentation { border-collapse: collapse; width: 100%; } table.Documentation tr th, table.TypeMembers tr th, table.Enumeration tr th, table.TypeDocumentation tr th { background: whitesmoke; padding: 0.8em; border: 1px solid gray; text-align: left; vertical-align: bottom; } table.Documentation tr td, table.TypeMembers tr td, table.Enumeration tr td, table.TypeDocumentation tr td { padding: 0.5em; border: 1px solid gray; text-align: left; vertical-align: top; } table.TypeMembers { border: 1px solid #C0C0C0; width: 100%; } table.TypeMembers tr td { background: #F8F8F8; border: white; } table.Documentation { } table.TypeMembers { } div.CodeExample { width: 100%; border: 1px solid #DDDDDD; background-color: #F8F8F8; } div.CodeExample p { margin: 0.5em; border-bottom: 1px solid #DDDDDD; } div.CodeExample div { margin: 0.5em; } h4 { margin-bottom: 0; } div.Signature { border: 1px solid #C0C0C0; background: #F2F2F2; padding: 1em; } </style> <script type="text/JavaScript"> function toggle_display (block) { var w = document.getElementById (block); var t = document.getElementById (block + ":toggle"); if (w.style.display == "none") { w.style.display = "block"; t.innerHTML = "⊟"; } else { w.style.display = "none"; t.innerHTML = "⊞"; } } </script> </head> <body> <div class="CollectionTitle"> <a href="../index.html">DocTest</a> : <a href="index.html">Mono.DocTest.Generic Namespace</a></div> <div class="SideBar"> <p> <a href="#T:Mono.DocTest.Generic.Func`2">Overview</a> </p> <p> <a href="#T:Mono.DocTest.Generic.Func`2:Signature">Signature</a> </p> <p> <a href="#T:Mono.DocTest.Generic.Func`2:Docs">Remarks</a> </p> <p> <a href="#Members">Members</a> </p> <p> <a href="#T:Mono.DocTest.Generic.Func`2:Members">Member Details</a> </p> </div> <h1 class="PageTitle" id="T:Mono.DocTest.Generic.Func`2">Func&lt;TArg,TRet&gt; Generic Delegate</h1> <p class="Summary" id="T:Mono.DocTest.Generic.Func`2:Summary"> <span class="NotEntered">Documentation for this section has not yet been entered.</span> </p> <div> <h2>Syntax</h2> <div class="Signature" id="T:Mono.DocTest.Generic.Func`2:Signature">[Mono.DocTest.Doc("method")]<br />[return:Mono.DocTest.Doc("return", Field=false)]<br />public delegate <i title="return type, with attributes!">TRet</i> <b>Func&lt;[Mono.DocTest.Doc("arg!")] TArg, [Mono.DocTest.Doc("ret!")] TRet&gt;</b> ([Mono.DocTest.Doc("arg-actual")] <i title="argument type, with attributes!">TArg</i> a)<br /> where TArg : <a href="http://www.go-mono.com/docs/monodoc.ashx?link=T:System.Exception">Exception</a></div> </div> <div class="Remarks" id="T:Mono.DocTest.Generic.Func`2:Docs"> <h4 class="Subsection">Type Parameters</h4> <blockquote class="SubsectionBox" id="T:Mono.DocTest.Generic.Func`2:Docs:Type Parameters"> <dl> <dt> <i>TArg</i> </dt> <dd>argument type, with attributes!</dd> <dt> <i>TRet</i> </dt> <dd>return type, with attributes!</dd> </dl> </blockquote> <h4 class="Subsection">Parameters</h4> <blockquote class="SubsectionBox" id="T:Mono.DocTest.Generic.Func`2:Docs:Parameters"> <dl> <dt> <i>a</i> </dt> <dd> <span class="NotEntered">Documentation for this section has not yet been entered.</span> </dd> </dl> </blockquote> <h4 class="Subsection">Returns</h4> <blockquote class="SubsectionBox" id="T:Mono.DocTest.Generic.Func`2:Docs:Returns"> <span class="NotEntered">Documentation for this section has not yet been entered.</span> </blockquote> <h2 class="Section">Remarks</h2> <div class="SectionBox" id="T:Mono.DocTest.Generic.Func`2:Docs:Remarks"> <tt>T:Mono.DocTest.Generic.Func`2</tt>.</div> <h2 class="Section">Requirements</h2> <div class="SectionBox" id="T:Mono.DocTest.Generic.Func`2:Docs:Version Information"> <b>Namespace: </b>Mono.DocTest.Generic<br /><b>Assembly: </b>DocTest (in DocTest.dll)<br /><b>Assembly Versions: </b>0.0.0.0</div> </div> <div class="Members" id="T:Mono.DocTest.Generic.Func`2:Members"> </div> <hr size="1" /> <div class="Copyright"> </div> </body> </html>
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _LINUX_NFS_XDR_H #define _LINUX_NFS_XDR_H #include <linux/nfsacl.h> #include <linux/sunrpc/gss_api.h> /* * To change the maximum rsize and wsize supported by the NFS client, adjust * NFS_MAX_FILE_IO_SIZE. 64KB is a typical maximum, but some servers can * support a megabyte or more. The default is left at 4096 bytes, which is * reasonable for NFS over UDP. */ #define NFS_MAX_FILE_IO_SIZE (1048576U) #define NFS_DEF_FILE_IO_SIZE (4096U) #define NFS_MIN_FILE_IO_SIZE (1024U) struct nfs4_string { unsigned int len; char *data; }; struct nfs_fsid { uint64_t major; uint64_t minor; }; /* * Helper for checking equality between 2 fsids. */ static inline int nfs_fsid_equal(const struct nfs_fsid *a, const struct nfs_fsid *b) { return a->major == b->major && a->minor == b->minor; } struct nfs4_threshold { __u32 bm; __u32 l_type; __u64 rd_sz; __u64 wr_sz; __u64 rd_io_sz; __u64 wr_io_sz; }; struct nfs_fattr { unsigned int valid; /* which fields are valid */ umode_t mode; __u32 nlink; kuid_t uid; kgid_t gid; dev_t rdev; __u64 size; union { struct { __u32 blocksize; __u32 blocks; } nfs2; struct { __u64 used; } nfs3; } du; struct nfs_fsid fsid; __u64 fileid; __u64 mounted_on_fileid; struct timespec atime; struct timespec mtime; struct timespec ctime; __u64 change_attr; /* NFSv4 change attribute */ __u64 pre_change_attr;/* pre-op NFSv4 change attribute */ __u64 pre_size; /* pre_op_attr.size */ struct timespec pre_mtime; /* pre_op_attr.mtime */ struct timespec pre_ctime; /* pre_op_attr.ctime */ unsigned long time_start; unsigned long gencount; struct nfs4_string *owner_name; struct nfs4_string *group_name; struct nfs4_threshold *mdsthreshold; /* pNFS threshold hints */ }; #define NFS_ATTR_FATTR_TYPE (1U << 0) #define NFS_ATTR_FATTR_MODE (1U << 1) #define NFS_ATTR_FATTR_NLINK (1U << 2) #define NFS_ATTR_FATTR_OWNER (1U << 3) #define NFS_ATTR_FATTR_GROUP (1U << 4) #define NFS_ATTR_FATTR_RDEV (1U << 5) #define NFS_ATTR_FATTR_SIZE (1U << 6) #define NFS_ATTR_FATTR_PRESIZE (1U << 7) #define NFS_ATTR_FATTR_BLOCKS_USED (1U << 8) #define NFS_ATTR_FATTR_SPACE_USED (1U << 9) #define NFS_ATTR_FATTR_FSID (1U << 10) #define NFS_ATTR_FATTR_FILEID (1U << 11) #define NFS_ATTR_FATTR_ATIME (1U << 12) #define NFS_ATTR_FATTR_MTIME (1U << 13) #define NFS_ATTR_FATTR_CTIME (1U << 14) #define NFS_ATTR_FATTR_PREMTIME (1U << 15) #define NFS_ATTR_FATTR_PRECTIME (1U << 16) #define NFS_ATTR_FATTR_CHANGE (1U << 17) #define NFS_ATTR_FATTR_PRECHANGE (1U << 18) #define NFS_ATTR_FATTR_V4_LOCATIONS (1U << 19) #define NFS_ATTR_FATTR_V4_REFERRAL (1U << 20) #define NFS_ATTR_FATTR_MOUNTPOINT (1U << 21) #define NFS_ATTR_FATTR_MOUNTED_ON_FILEID (1U << 22) #define NFS_ATTR_FATTR_OWNER_NAME (1U << 23) #define NFS_ATTR_FATTR_GROUP_NAME (1U << 24) #define NFS_ATTR_FATTR_V4_SECURITY_LABEL (1U << 25) #define NFS_ATTR_FATTR (NFS_ATTR_FATTR_TYPE \ | NFS_ATTR_FATTR_MODE \ | NFS_ATTR_FATTR_NLINK \ | NFS_ATTR_FATTR_OWNER \ | NFS_ATTR_FATTR_GROUP \ | NFS_ATTR_FATTR_RDEV \ | NFS_ATTR_FATTR_SIZE \ | NFS_ATTR_FATTR_FSID \ | NFS_ATTR_FATTR_FILEID \ | NFS_ATTR_FATTR_ATIME \ | NFS_ATTR_FATTR_MTIME \ | NFS_ATTR_FATTR_CTIME \ | NFS_ATTR_FATTR_CHANGE) #define NFS_ATTR_FATTR_V2 (NFS_ATTR_FATTR \ | NFS_ATTR_FATTR_BLOCKS_USED) #define NFS_ATTR_FATTR_V3 (NFS_ATTR_FATTR \ | NFS_ATTR_FATTR_SPACE_USED) #define NFS_ATTR_FATTR_V4 (NFS_ATTR_FATTR \ | NFS_ATTR_FATTR_SPACE_USED \ | NFS_ATTR_FATTR_V4_SECURITY_LABEL) /* * Maximal number of supported layout drivers. */ #define NFS_MAX_LAYOUT_TYPES 8 /* * Info on the file system */ struct nfs_fsinfo { struct nfs_fattr *fattr; /* Post-op attributes */ __u32 rtmax; /* max. read transfer size */ __u32 rtpref; /* pref. read transfer size */ __u32 rtmult; /* reads should be multiple of this */ __u32 wtmax; /* max. write transfer size */ __u32 wtpref; /* pref. write transfer size */ __u32 wtmult; /* writes should be multiple of this */ __u32 dtpref; /* pref. readdir transfer size */ __u64 maxfilesize; struct timespec time_delta; /* server time granularity */ __u32 lease_time; /* in seconds */ __u32 nlayouttypes; /* number of layouttypes */ __u32 layouttype[NFS_MAX_LAYOUT_TYPES]; /* supported pnfs layout driver */ __u32 blksize; /* preferred pnfs io block size */ __u32 clone_blksize; /* granularity of a CLONE operation */ }; struct nfs_fsstat { struct nfs_fattr *fattr; /* Post-op attributes */ __u64 tbytes; /* total size in bytes */ __u64 fbytes; /* # of free bytes */ __u64 abytes; /* # of bytes available to user */ __u64 tfiles; /* # of files */ __u64 ffiles; /* # of free files */ __u64 afiles; /* # of files available to user */ }; struct nfs2_fsstat { __u32 tsize; /* Server transfer size */ __u32 bsize; /* Filesystem block size */ __u32 blocks; /* No. of "bsize" blocks on filesystem */ __u32 bfree; /* No. of free "bsize" blocks */ __u32 bavail; /* No. of available "bsize" blocks */ }; struct nfs_pathconf { struct nfs_fattr *fattr; /* Post-op attributes */ __u32 max_link; /* max # of hard links */ __u32 max_namelen; /* max name length */ }; struct nfs4_change_info { u32 atomic; u64 before; u64 after; }; struct nfs_seqid; /* nfs41 sessions channel attributes */ struct nfs4_channel_attrs { u32 max_rqst_sz; u32 max_resp_sz; u32 max_resp_sz_cached; u32 max_ops; u32 max_reqs; }; struct nfs4_slot; struct nfs4_sequence_args { struct nfs4_slot *sa_slot; u8 sa_cache_this : 1, sa_privileged : 1; }; struct nfs4_sequence_res { struct nfs4_slot *sr_slot; /* slot used to send request */ unsigned long sr_timestamp; int sr_status; /* sequence operation status */ u32 sr_status_flags; u32 sr_highest_slotid; u32 sr_target_highest_slotid; }; struct nfs4_get_lease_time_args { struct nfs4_sequence_args la_seq_args; }; struct nfs4_get_lease_time_res { struct nfs4_sequence_res lr_seq_res; struct nfs_fsinfo *lr_fsinfo; }; struct xdr_stream; struct nfs4_xdr_opaque_data; struct nfs4_xdr_opaque_ops { void (*encode)(struct xdr_stream *, const void *args, const struct nfs4_xdr_opaque_data *); void (*free)(struct nfs4_xdr_opaque_data *); }; struct nfs4_xdr_opaque_data { const struct nfs4_xdr_opaque_ops *ops; void *data; }; #define PNFS_LAYOUT_MAXSIZE 4096 struct nfs4_layoutdriver_data { struct page **pages; __u32 pglen; __u32 len; }; struct pnfs_layout_range { u32 iomode; u64 offset; u64 length; }; struct nfs4_layoutget_args { struct nfs4_sequence_args seq_args; __u32 type; struct pnfs_layout_range range; __u64 minlength; __u32 maxcount; struct inode *inode; struct nfs_open_context *ctx; nfs4_stateid stateid; struct nfs4_layoutdriver_data layout; }; struct nfs4_layoutget_res { struct nfs4_sequence_res seq_res; __u32 return_on_close; struct pnfs_layout_range range; __u32 type; nfs4_stateid stateid; struct nfs4_layoutdriver_data *layoutp; }; struct nfs4_layoutget { struct nfs4_layoutget_args args; struct nfs4_layoutget_res res; struct rpc_cred *cred; gfp_t gfp_flags; }; struct nfs4_getdeviceinfo_args { struct nfs4_sequence_args seq_args; struct pnfs_device *pdev; __u32 notify_types; }; struct nfs4_getdeviceinfo_res { struct nfs4_sequence_res seq_res; struct pnfs_device *pdev; __u32 notification; }; struct nfs4_layoutcommit_args { struct nfs4_sequence_args seq_args; nfs4_stateid stateid; __u64 lastbytewritten; struct inode *inode; const u32 *bitmask; size_t layoutupdate_len; struct page *layoutupdate_page; struct page **layoutupdate_pages; __be32 *start_p; }; struct nfs4_layoutcommit_res { struct nfs4_sequence_res seq_res; struct nfs_fattr *fattr; const struct nfs_server *server; int status; }; struct nfs4_layoutcommit_data { struct rpc_task task; struct nfs_fattr fattr; struct list_head lseg_list; struct rpc_cred *cred; struct inode *inode; struct nfs4_layoutcommit_args args; struct nfs4_layoutcommit_res res; }; struct nfs4_layoutreturn_args { struct nfs4_sequence_args seq_args; struct pnfs_layout_hdr *layout; struct inode *inode; struct pnfs_layout_range range; nfs4_stateid stateid; __u32 layout_type; struct nfs4_xdr_opaque_data *ld_private; }; struct nfs4_layoutreturn_res { struct nfs4_sequence_res seq_res; u32 lrs_present; nfs4_stateid stateid; }; struct nfs4_layoutreturn { struct nfs4_layoutreturn_args args; struct nfs4_layoutreturn_res res; struct rpc_cred *cred; struct nfs_client *clp; struct inode *inode; int rpc_status; struct nfs4_xdr_opaque_data ld_private; }; #define PNFS_LAYOUTSTATS_MAXSIZE 256 struct nfs42_layoutstat_args; struct nfs42_layoutstat_devinfo; typedef void (*layoutstats_encode_t)(struct xdr_stream *, struct nfs42_layoutstat_args *, struct nfs42_layoutstat_devinfo *); /* Per file per deviceid layoutstats */ struct nfs42_layoutstat_devinfo { struct nfs4_deviceid dev_id; __u64 offset; __u64 length; __u64 read_count; __u64 read_bytes; __u64 write_count; __u64 write_bytes; __u32 layout_type; struct nfs4_xdr_opaque_data ld_private; }; struct nfs42_layoutstat_args { struct nfs4_sequence_args seq_args; struct nfs_fh *fh; struct inode *inode; nfs4_stateid stateid; int num_dev; struct nfs42_layoutstat_devinfo *devinfo; }; struct nfs42_layoutstat_res { struct nfs4_sequence_res seq_res; int num_dev; int rpc_status; }; struct nfs42_layoutstat_data { struct inode *inode; struct nfs42_layoutstat_args args; struct nfs42_layoutstat_res res; }; struct nfs42_clone_args { struct nfs4_sequence_args seq_args; struct nfs_fh *src_fh; struct nfs_fh *dst_fh; nfs4_stateid src_stateid; nfs4_stateid dst_stateid; __u64 src_offset; __u64 dst_offset; __u64 count; const u32 *dst_bitmask; }; struct nfs42_clone_res { struct nfs4_sequence_res seq_res; unsigned int rpc_status; struct nfs_fattr *dst_fattr; const struct nfs_server *server; }; struct stateowner_id { __u64 create_time; __u32 uniquifier; }; /* * Arguments to the open call. */ struct nfs_openargs { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; struct nfs_seqid * seqid; int open_flags; fmode_t fmode; u32 share_access; u32 access; __u64 clientid; struct stateowner_id id; union { struct { struct iattr * attrs; /* UNCHECKED, GUARDED, EXCLUSIVE4_1 */ nfs4_verifier verifier; /* EXCLUSIVE */ }; nfs4_stateid delegation; /* CLAIM_DELEGATE_CUR */ fmode_t delegation_type; /* CLAIM_PREVIOUS */ } u; const struct qstr * name; const struct nfs_server *server; /* Needed for ID mapping */ const u32 * bitmask; const u32 * open_bitmap; enum open_claim_type4 claim; enum createmode4 createmode; const struct nfs4_label *label; umode_t umask; }; struct nfs_openres { struct nfs4_sequence_res seq_res; nfs4_stateid stateid; struct nfs_fh fh; struct nfs4_change_info cinfo; __u32 rflags; struct nfs_fattr * f_attr; struct nfs4_label *f_label; struct nfs_seqid * seqid; const struct nfs_server *server; fmode_t delegation_type; nfs4_stateid delegation; unsigned long pagemod_limit; __u32 do_recall; __u32 attrset[NFS4_BITMAP_SIZE]; struct nfs4_string *owner; struct nfs4_string *group_owner; __u32 access_request; __u32 access_supported; __u32 access_result; }; /* * Arguments to the open_confirm call. */ struct nfs_open_confirmargs { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; nfs4_stateid * stateid; struct nfs_seqid * seqid; }; struct nfs_open_confirmres { struct nfs4_sequence_res seq_res; nfs4_stateid stateid; struct nfs_seqid * seqid; }; /* * Arguments to the close call. */ struct nfs_closeargs { struct nfs4_sequence_args seq_args; struct nfs_fh * fh; nfs4_stateid stateid; struct nfs_seqid * seqid; fmode_t fmode; u32 share_access; const u32 * bitmask; struct nfs4_layoutreturn_args *lr_args; }; struct nfs_closeres { struct nfs4_sequence_res seq_res; nfs4_stateid stateid; struct nfs_fattr * fattr; struct nfs_seqid * seqid; const struct nfs_server *server; struct nfs4_layoutreturn_res *lr_res; int lr_ret; }; /* * * Arguments to the lock,lockt, and locku call. * */ struct nfs_lowner { __u64 clientid; __u64 id; dev_t s_dev; }; struct nfs_lock_args { struct nfs4_sequence_args seq_args; struct nfs_fh * fh; struct file_lock * fl; struct nfs_seqid * lock_seqid; nfs4_stateid lock_stateid; struct nfs_seqid * open_seqid; nfs4_stateid open_stateid; struct nfs_lowner lock_owner; unsigned char block : 1; unsigned char reclaim : 1; unsigned char new_lock : 1; unsigned char new_lock_owner : 1; }; struct nfs_lock_res { struct nfs4_sequence_res seq_res; nfs4_stateid stateid; struct nfs_seqid * lock_seqid; struct nfs_seqid * open_seqid; }; struct nfs_locku_args { struct nfs4_sequence_args seq_args; struct nfs_fh * fh; struct file_lock * fl; struct nfs_seqid * seqid; nfs4_stateid stateid; }; struct nfs_locku_res { struct nfs4_sequence_res seq_res; nfs4_stateid stateid; struct nfs_seqid * seqid; }; struct nfs_lockt_args { struct nfs4_sequence_args seq_args; struct nfs_fh * fh; struct file_lock * fl; struct nfs_lowner lock_owner; }; struct nfs_lockt_res { struct nfs4_sequence_res seq_res; struct file_lock * denied; /* LOCK, LOCKT failed */ }; struct nfs_release_lockowner_args { struct nfs4_sequence_args seq_args; struct nfs_lowner lock_owner; }; struct nfs_release_lockowner_res { struct nfs4_sequence_res seq_res; }; struct nfs4_delegreturnargs { struct nfs4_sequence_args seq_args; const struct nfs_fh *fhandle; const nfs4_stateid *stateid; const u32 * bitmask; struct nfs4_layoutreturn_args *lr_args; }; struct nfs4_delegreturnres { struct nfs4_sequence_res seq_res; struct nfs_fattr * fattr; struct nfs_server *server; struct nfs4_layoutreturn_res *lr_res; int lr_ret; }; /* * Arguments to the write call. */ struct nfs_write_verifier { char data[8]; }; struct nfs_writeverf { struct nfs_write_verifier verifier; enum nfs3_stable_how committed; }; /* * Arguments shared by the read and write call. */ struct nfs_pgio_args { struct nfs4_sequence_args seq_args; struct nfs_fh * fh; struct nfs_open_context *context; struct nfs_lock_context *lock_context; nfs4_stateid stateid; __u64 offset; __u32 count; unsigned int pgbase; struct page ** pages; const u32 * bitmask; /* used by write */ enum nfs3_stable_how stable; /* used by write */ }; struct nfs_pgio_res { struct nfs4_sequence_res seq_res; struct nfs_fattr * fattr; __u32 count; __u32 op_status; int eof; /* used by read */ struct nfs_writeverf * verf; /* used by write */ const struct nfs_server *server; /* used by write */ }; /* * Arguments to the commit call. */ struct nfs_commitargs { struct nfs4_sequence_args seq_args; struct nfs_fh *fh; __u64 offset; __u32 count; const u32 *bitmask; }; struct nfs_commitres { struct nfs4_sequence_res seq_res; __u32 op_status; struct nfs_fattr *fattr; struct nfs_writeverf *verf; const struct nfs_server *server; }; /* * Common arguments to the unlink call */ struct nfs_removeargs { struct nfs4_sequence_args seq_args; const struct nfs_fh *fh; struct qstr name; }; struct nfs_removeres { struct nfs4_sequence_res seq_res; struct nfs_server *server; struct nfs_fattr *dir_attr; struct nfs4_change_info cinfo; }; /* * Common arguments to the rename call */ struct nfs_renameargs { struct nfs4_sequence_args seq_args; const struct nfs_fh *old_dir; const struct nfs_fh *new_dir; const struct qstr *old_name; const struct qstr *new_name; }; struct nfs_renameres { struct nfs4_sequence_res seq_res; struct nfs_server *server; struct nfs4_change_info old_cinfo; struct nfs_fattr *old_fattr; struct nfs4_change_info new_cinfo; struct nfs_fattr *new_fattr; }; /* parsed sec= options */ #define NFS_AUTH_INFO_MAX_FLAVORS 12 /* see fs/nfs/super.c */ struct nfs_auth_info { unsigned int flavor_len; rpc_authflavor_t flavors[NFS_AUTH_INFO_MAX_FLAVORS]; }; /* * Argument struct for decode_entry function */ struct nfs_entry { __u64 ino; __u64 cookie, prev_cookie; const char * name; unsigned int len; int eof; struct nfs_fh * fh; struct nfs_fattr * fattr; struct nfs4_label *label; unsigned char d_type; struct nfs_server * server; }; /* * The following types are for NFSv2 only. */ struct nfs_sattrargs { struct nfs_fh * fh; struct iattr * sattr; }; struct nfs_diropargs { struct nfs_fh * fh; const char * name; unsigned int len; }; struct nfs_createargs { struct nfs_fh * fh; const char * name; unsigned int len; struct iattr * sattr; }; struct nfs_setattrargs { struct nfs4_sequence_args seq_args; struct nfs_fh * fh; nfs4_stateid stateid; struct iattr * iap; const struct nfs_server * server; /* Needed for name mapping */ const u32 * bitmask; const struct nfs4_label *label; }; struct nfs_setaclargs { struct nfs4_sequence_args seq_args; struct nfs_fh * fh; size_t acl_len; struct page ** acl_pages; }; struct nfs_setaclres { struct nfs4_sequence_res seq_res; }; struct nfs_getaclargs { struct nfs4_sequence_args seq_args; struct nfs_fh * fh; size_t acl_len; struct page ** acl_pages; }; /* getxattr ACL interface flags */ #define NFS4_ACL_TRUNC 0x0001 /* ACL was truncated */ struct nfs_getaclres { struct nfs4_sequence_res seq_res; size_t acl_len; size_t acl_data_offset; int acl_flags; struct page * acl_scratch; }; struct nfs_setattrres { struct nfs4_sequence_res seq_res; struct nfs_fattr * fattr; struct nfs4_label *label; const struct nfs_server * server; }; struct nfs_linkargs { struct nfs_fh * fromfh; struct nfs_fh * tofh; const char * toname; unsigned int tolen; }; struct nfs_symlinkargs { struct nfs_fh * fromfh; const char * fromname; unsigned int fromlen; struct page ** pages; unsigned int pathlen; struct iattr * sattr; }; struct nfs_readdirargs { struct nfs_fh * fh; __u32 cookie; unsigned int count; struct page ** pages; }; struct nfs3_getaclargs { struct nfs_fh * fh; int mask; struct page ** pages; }; struct nfs3_setaclargs { struct inode * inode; int mask; struct posix_acl * acl_access; struct posix_acl * acl_default; size_t len; unsigned int npages; struct page ** pages; }; struct nfs_diropok { struct nfs_fh * fh; struct nfs_fattr * fattr; }; struct nfs_readlinkargs { struct nfs_fh * fh; unsigned int pgbase; unsigned int pglen; struct page ** pages; }; struct nfs3_sattrargs { struct nfs_fh * fh; struct iattr * sattr; unsigned int guard; struct timespec guardtime; }; struct nfs3_diropargs { struct nfs_fh * fh; const char * name; unsigned int len; }; struct nfs3_accessargs { struct nfs_fh * fh; __u32 access; }; struct nfs3_createargs { struct nfs_fh * fh; const char * name; unsigned int len; struct iattr * sattr; enum nfs3_createmode createmode; __be32 verifier[2]; }; struct nfs3_mkdirargs { struct nfs_fh * fh; const char * name; unsigned int len; struct iattr * sattr; }; struct nfs3_symlinkargs { struct nfs_fh * fromfh; const char * fromname; unsigned int fromlen; struct page ** pages; unsigned int pathlen; struct iattr * sattr; }; struct nfs3_mknodargs { struct nfs_fh * fh; const char * name; unsigned int len; enum nfs3_ftype type; struct iattr * sattr; dev_t rdev; }; struct nfs3_linkargs { struct nfs_fh * fromfh; struct nfs_fh * tofh; const char * toname; unsigned int tolen; }; struct nfs3_readdirargs { struct nfs_fh * fh; __u64 cookie; __be32 verf[2]; bool plus; unsigned int count; struct page ** pages; }; struct nfs3_diropres { struct nfs_fattr * dir_attr; struct nfs_fh * fh; struct nfs_fattr * fattr; }; struct nfs3_accessres { struct nfs_fattr * fattr; __u32 access; }; struct nfs3_readlinkargs { struct nfs_fh * fh; unsigned int pgbase; unsigned int pglen; struct page ** pages; }; struct nfs3_linkres { struct nfs_fattr * dir_attr; struct nfs_fattr * fattr; }; struct nfs3_readdirres { struct nfs_fattr * dir_attr; __be32 * verf; bool plus; }; struct nfs3_getaclres { struct nfs_fattr * fattr; int mask; unsigned int acl_access_count; unsigned int acl_default_count; struct posix_acl * acl_access; struct posix_acl * acl_default; }; #if IS_ENABLED(CONFIG_NFS_V4) typedef u64 clientid4; struct nfs4_accessargs { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; const u32 * bitmask; u32 access; }; struct nfs4_accessres { struct nfs4_sequence_res seq_res; const struct nfs_server * server; struct nfs_fattr * fattr; u32 supported; u32 access; }; struct nfs4_create_arg { struct nfs4_sequence_args seq_args; u32 ftype; union { struct { struct page ** pages; unsigned int len; } symlink; /* NF4LNK */ struct { u32 specdata1; u32 specdata2; } device; /* NF4BLK, NF4CHR */ } u; const struct qstr * name; const struct nfs_server * server; const struct iattr * attrs; const struct nfs_fh * dir_fh; const u32 * bitmask; const struct nfs4_label *label; umode_t umask; }; struct nfs4_create_res { struct nfs4_sequence_res seq_res; const struct nfs_server * server; struct nfs_fh * fh; struct nfs_fattr * fattr; struct nfs4_label *label; struct nfs4_change_info dir_cinfo; }; struct nfs4_fsinfo_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; const u32 * bitmask; }; struct nfs4_fsinfo_res { struct nfs4_sequence_res seq_res; struct nfs_fsinfo *fsinfo; }; struct nfs4_getattr_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; const u32 * bitmask; }; struct nfs4_getattr_res { struct nfs4_sequence_res seq_res; const struct nfs_server * server; struct nfs_fattr * fattr; struct nfs4_label *label; }; struct nfs4_link_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; const struct nfs_fh * dir_fh; const struct qstr * name; const u32 * bitmask; }; struct nfs4_link_res { struct nfs4_sequence_res seq_res; const struct nfs_server * server; struct nfs_fattr * fattr; struct nfs4_label *label; struct nfs4_change_info cinfo; struct nfs_fattr * dir_attr; }; struct nfs4_lookup_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh * dir_fh; const struct qstr * name; const u32 * bitmask; }; struct nfs4_lookup_res { struct nfs4_sequence_res seq_res; const struct nfs_server * server; struct nfs_fattr * fattr; struct nfs_fh * fh; struct nfs4_label *label; }; struct nfs4_lookupp_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh *fh; const u32 *bitmask; }; struct nfs4_lookupp_res { struct nfs4_sequence_res seq_res; const struct nfs_server *server; struct nfs_fattr *fattr; struct nfs_fh *fh; struct nfs4_label *label; }; struct nfs4_lookup_root_arg { struct nfs4_sequence_args seq_args; const u32 * bitmask; }; struct nfs4_pathconf_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; const u32 * bitmask; }; struct nfs4_pathconf_res { struct nfs4_sequence_res seq_res; struct nfs_pathconf *pathconf; }; struct nfs4_readdir_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; u64 cookie; nfs4_verifier verifier; u32 count; struct page ** pages; /* zero-copy data */ unsigned int pgbase; /* zero-copy data */ const u32 * bitmask; bool plus; }; struct nfs4_readdir_res { struct nfs4_sequence_res seq_res; nfs4_verifier verifier; unsigned int pgbase; }; struct nfs4_readlink { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; unsigned int pgbase; unsigned int pglen; /* zero-copy data */ struct page ** pages; /* zero-copy data */ }; struct nfs4_readlink_res { struct nfs4_sequence_res seq_res; }; struct nfs4_setclientid { const nfs4_verifier * sc_verifier; u32 sc_prog; unsigned int sc_netid_len; char sc_netid[RPCBIND_MAXNETIDLEN + 1]; unsigned int sc_uaddr_len; char sc_uaddr[RPCBIND_MAXUADDRLEN + 1]; struct nfs_client *sc_clnt; struct rpc_cred *sc_cred; }; struct nfs4_setclientid_res { u64 clientid; nfs4_verifier confirm; }; struct nfs4_statfs_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh * fh; const u32 * bitmask; }; struct nfs4_statfs_res { struct nfs4_sequence_res seq_res; struct nfs_fsstat *fsstat; }; struct nfs4_server_caps_arg { struct nfs4_sequence_args seq_args; struct nfs_fh *fhandle; const u32 * bitmask; }; struct nfs4_server_caps_res { struct nfs4_sequence_res seq_res; u32 attr_bitmask[3]; u32 exclcreat_bitmask[3]; u32 acl_bitmask; u32 has_links; u32 has_symlinks; u32 fh_expire_type; }; #define NFS4_PATHNAME_MAXCOMPONENTS 512 struct nfs4_pathname { unsigned int ncomponents; struct nfs4_string components[NFS4_PATHNAME_MAXCOMPONENTS]; }; #define NFS4_FS_LOCATION_MAXSERVERS 10 struct nfs4_fs_location { unsigned int nservers; struct nfs4_string servers[NFS4_FS_LOCATION_MAXSERVERS]; struct nfs4_pathname rootpath; }; #define NFS4_FS_LOCATIONS_MAXENTRIES 10 struct nfs4_fs_locations { struct nfs_fattr fattr; const struct nfs_server *server; struct nfs4_pathname fs_path; int nlocations; struct nfs4_fs_location locations[NFS4_FS_LOCATIONS_MAXENTRIES]; }; struct nfs4_fs_locations_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh *dir_fh; const struct nfs_fh *fh; const struct qstr *name; struct page *page; const u32 *bitmask; clientid4 clientid; unsigned char migration:1, renew:1; }; struct nfs4_fs_locations_res { struct nfs4_sequence_res seq_res; struct nfs4_fs_locations *fs_locations; unsigned char migration:1, renew:1; }; struct nfs4_secinfo4 { u32 flavor; struct rpcsec_gss_info flavor_info; }; struct nfs4_secinfo_flavors { unsigned int num_flavors; struct nfs4_secinfo4 flavors[0]; }; struct nfs4_secinfo_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh *dir_fh; const struct qstr *name; }; struct nfs4_secinfo_res { struct nfs4_sequence_res seq_res; struct nfs4_secinfo_flavors *flavors; }; struct nfs4_fsid_present_arg { struct nfs4_sequence_args seq_args; const struct nfs_fh *fh; clientid4 clientid; unsigned char renew:1; }; struct nfs4_fsid_present_res { struct nfs4_sequence_res seq_res; struct nfs_fh *fh; unsigned char renew:1; }; #endif /* CONFIG_NFS_V4 */ struct nfstime4 { u64 seconds; u32 nseconds; }; #ifdef CONFIG_NFS_V4_1 struct pnfs_commit_bucket { struct list_head written; struct list_head committing; struct pnfs_layout_segment *wlseg; struct pnfs_layout_segment *clseg; struct nfs_writeverf direct_verf; }; struct pnfs_ds_commit_info { int nwritten; int ncommitting; int nbuckets; struct pnfs_commit_bucket *buckets; }; struct nfs41_state_protection { u32 how; struct nfs4_op_map enforce; struct nfs4_op_map allow; }; struct nfs41_exchange_id_args { struct nfs_client *client; nfs4_verifier verifier; u32 flags; struct nfs41_state_protection state_protect; }; struct nfs41_server_owner { uint64_t minor_id; uint32_t major_id_sz; char major_id[NFS4_OPAQUE_LIMIT]; }; struct nfs41_server_scope { uint32_t server_scope_sz; char server_scope[NFS4_OPAQUE_LIMIT]; }; struct nfs41_impl_id { char domain[NFS4_OPAQUE_LIMIT + 1]; char name[NFS4_OPAQUE_LIMIT + 1]; struct nfstime4 date; }; struct nfs41_bind_conn_to_session_args { struct nfs_client *client; struct nfs4_sessionid sessionid; u32 dir; bool use_conn_in_rdma_mode; }; struct nfs41_bind_conn_to_session_res { struct nfs4_sessionid sessionid; u32 dir; bool use_conn_in_rdma_mode; }; struct nfs41_exchange_id_res { u64 clientid; u32 seqid; u32 flags; struct nfs41_server_owner *server_owner; struct nfs41_server_scope *server_scope; struct nfs41_impl_id *impl_id; struct nfs41_state_protection state_protect; }; struct nfs41_create_session_args { struct nfs_client *client; u64 clientid; uint32_t seqid; uint32_t flags; uint32_t cb_program; struct nfs4_channel_attrs fc_attrs; /* Fore Channel */ struct nfs4_channel_attrs bc_attrs; /* Back Channel */ }; struct nfs41_create_session_res { struct nfs4_sessionid sessionid; uint32_t seqid; uint32_t flags; struct nfs4_channel_attrs fc_attrs; /* Fore Channel */ struct nfs4_channel_attrs bc_attrs; /* Back Channel */ }; struct nfs41_reclaim_complete_args { struct nfs4_sequence_args seq_args; /* In the future extend to include curr_fh for use with migration */ unsigned char one_fs:1; }; struct nfs41_reclaim_complete_res { struct nfs4_sequence_res seq_res; }; #define SECINFO_STYLE_CURRENT_FH 0 #define SECINFO_STYLE_PARENT 1 struct nfs41_secinfo_no_name_args { struct nfs4_sequence_args seq_args; int style; }; struct nfs41_test_stateid_args { struct nfs4_sequence_args seq_args; nfs4_stateid *stateid; }; struct nfs41_test_stateid_res { struct nfs4_sequence_res seq_res; unsigned int status; }; struct nfs41_free_stateid_args { struct nfs4_sequence_args seq_args; nfs4_stateid stateid; }; struct nfs41_free_stateid_res { struct nfs4_sequence_res seq_res; unsigned int status; }; static inline void nfs_free_pnfs_ds_cinfo(struct pnfs_ds_commit_info *cinfo) { kfree(cinfo->buckets); } #else struct pnfs_ds_commit_info { }; static inline void nfs_free_pnfs_ds_cinfo(struct pnfs_ds_commit_info *cinfo) { } #endif /* CONFIG_NFS_V4_1 */ #ifdef CONFIG_NFS_V4_2 struct nfs42_falloc_args { struct nfs4_sequence_args seq_args; struct nfs_fh *falloc_fh; nfs4_stateid falloc_stateid; u64 falloc_offset; u64 falloc_length; const u32 *falloc_bitmask; }; struct nfs42_falloc_res { struct nfs4_sequence_res seq_res; unsigned int status; struct nfs_fattr *falloc_fattr; const struct nfs_server *falloc_server; }; struct nfs42_copy_args { struct nfs4_sequence_args seq_args; struct nfs_fh *src_fh; nfs4_stateid src_stateid; u64 src_pos; struct nfs_fh *dst_fh; nfs4_stateid dst_stateid; u64 dst_pos; u64 count; }; struct nfs42_write_res { u64 count; struct nfs_writeverf verifier; }; struct nfs42_copy_res { struct nfs4_sequence_res seq_res; struct nfs42_write_res write_res; bool consecutive; bool synchronous; struct nfs_commitres commit_res; }; struct nfs42_seek_args { struct nfs4_sequence_args seq_args; struct nfs_fh *sa_fh; nfs4_stateid sa_stateid; u64 sa_offset; u32 sa_what; }; struct nfs42_seek_res { struct nfs4_sequence_res seq_res; unsigned int status; u32 sr_eof; u64 sr_offset; }; #endif struct nfs_page; #define NFS_PAGEVEC_SIZE (8U) struct nfs_page_array { struct page **pagevec; unsigned int npages; /* Max length of pagevec */ struct page *page_array[NFS_PAGEVEC_SIZE]; }; /* used as flag bits in nfs_pgio_header */ enum { NFS_IOHDR_ERROR = 0, NFS_IOHDR_EOF, NFS_IOHDR_REDO, NFS_IOHDR_STAT, }; struct nfs_io_completion; struct nfs_pgio_header { struct inode *inode; struct rpc_cred *cred; struct list_head pages; struct nfs_page *req; struct nfs_writeverf verf; /* Used for writes */ fmode_t rw_mode; struct pnfs_layout_segment *lseg; loff_t io_start; const struct rpc_call_ops *mds_ops; void (*release) (struct nfs_pgio_header *hdr); const struct nfs_pgio_completion_ops *completion_ops; const struct nfs_rw_ops *rw_ops; struct nfs_io_completion *io_completion; struct nfs_direct_req *dreq; spinlock_t lock; /* fields protected by lock */ int pnfs_error; int error; /* merge with pnfs_error */ unsigned long good_bytes; /* boundary of good data */ unsigned long flags; /* * rpc data */ struct rpc_task task; struct nfs_fattr fattr; struct nfs_pgio_args args; /* argument struct */ struct nfs_pgio_res res; /* result struct */ unsigned long timestamp; /* For lease renewal */ int (*pgio_done_cb)(struct rpc_task *, struct nfs_pgio_header *); __u64 mds_offset; /* Filelayout dense stripe */ struct nfs_page_array page_array; struct nfs_client *ds_clp; /* pNFS data server */ int ds_commit_idx; /* ds index if ds_clp is set */ int pgio_mirror_idx;/* mirror index in pgio layer */ }; struct nfs_mds_commit_info { atomic_t rpcs_out; atomic_long_t ncommit; struct list_head list; }; struct nfs_commit_info; struct nfs_commit_data; struct nfs_inode; struct nfs_commit_completion_ops { void (*completion) (struct nfs_commit_data *data); void (*resched_write) (struct nfs_commit_info *, struct nfs_page *); }; struct nfs_commit_info { struct inode *inode; /* Needed for inode->i_lock */ struct nfs_mds_commit_info *mds; struct pnfs_ds_commit_info *ds; struct nfs_direct_req *dreq; /* O_DIRECT request */ const struct nfs_commit_completion_ops *completion_ops; }; struct nfs_commit_data { struct rpc_task task; struct inode *inode; struct rpc_cred *cred; struct nfs_fattr fattr; struct nfs_writeverf verf; struct list_head pages; /* Coalesced requests we wish to flush */ struct list_head list; /* lists of struct nfs_write_data */ struct nfs_direct_req *dreq; /* O_DIRECT request */ struct nfs_commitargs args; /* argument struct */ struct nfs_commitres res; /* result struct */ struct nfs_open_context *context; struct pnfs_layout_segment *lseg; struct nfs_client *ds_clp; /* pNFS data server */ int ds_commit_index; loff_t lwb; const struct rpc_call_ops *mds_ops; const struct nfs_commit_completion_ops *completion_ops; int (*commit_done_cb) (struct rpc_task *task, struct nfs_commit_data *data); unsigned long flags; }; struct nfs_pgio_completion_ops { void (*error_cleanup)(struct list_head *head); void (*init_hdr)(struct nfs_pgio_header *hdr); void (*completion)(struct nfs_pgio_header *hdr); void (*reschedule_io)(struct nfs_pgio_header *hdr); }; struct nfs_unlinkdata { struct nfs_removeargs args; struct nfs_removeres res; struct dentry *dentry; wait_queue_head_t wq; struct rpc_cred *cred; struct nfs_fattr dir_attr; long timeout; }; struct nfs_renamedata { struct nfs_renameargs args; struct nfs_renameres res; struct rpc_cred *cred; struct inode *old_dir; struct dentry *old_dentry; struct nfs_fattr old_fattr; struct inode *new_dir; struct dentry *new_dentry; struct nfs_fattr new_fattr; void (*complete)(struct rpc_task *, struct nfs_renamedata *); long timeout; bool cancelled; }; struct nfs_access_entry; struct nfs_client; struct rpc_timeout; struct nfs_subversion; struct nfs_mount_info; struct nfs_client_initdata; struct nfs_pageio_descriptor; /* * RPC procedure vector for NFSv2/NFSv3 demuxing */ struct nfs_rpc_ops { u32 version; /* Protocol version */ const struct dentry_operations *dentry_ops; const struct inode_operations *dir_inode_ops; const struct inode_operations *file_inode_ops; const struct file_operations *file_ops; const struct nlmclnt_operations *nlmclnt_ops; int (*getroot) (struct nfs_server *, struct nfs_fh *, struct nfs_fsinfo *); struct vfsmount *(*submount) (struct nfs_server *, struct dentry *, struct nfs_fh *, struct nfs_fattr *); struct dentry *(*try_mount) (int, const char *, struct nfs_mount_info *, struct nfs_subversion *); int (*getattr) (struct nfs_server *, struct nfs_fh *, struct nfs_fattr *, struct nfs4_label *); int (*setattr) (struct dentry *, struct nfs_fattr *, struct iattr *); int (*lookup) (struct inode *, const struct qstr *, struct nfs_fh *, struct nfs_fattr *, struct nfs4_label *); int (*lookupp) (struct inode *, struct nfs_fh *, struct nfs_fattr *, struct nfs4_label *); int (*access) (struct inode *, struct nfs_access_entry *); int (*readlink)(struct inode *, struct page *, unsigned int, unsigned int); int (*create) (struct inode *, struct dentry *, struct iattr *, int); int (*remove) (struct inode *, const struct qstr *); void (*unlink_setup) (struct rpc_message *, struct inode *dir); void (*unlink_rpc_prepare) (struct rpc_task *, struct nfs_unlinkdata *); int (*unlink_done) (struct rpc_task *, struct inode *); void (*rename_setup) (struct rpc_message *msg, struct inode *dir); void (*rename_rpc_prepare)(struct rpc_task *task, struct nfs_renamedata *); int (*rename_done) (struct rpc_task *task, struct inode *old_dir, struct inode *new_dir); int (*link) (struct inode *, struct inode *, const struct qstr *); int (*symlink) (struct inode *, struct dentry *, struct page *, unsigned int, struct iattr *); int (*mkdir) (struct inode *, struct dentry *, struct iattr *); int (*rmdir) (struct inode *, const struct qstr *); int (*readdir) (struct dentry *, struct rpc_cred *, u64, struct page **, unsigned int, bool); int (*mknod) (struct inode *, struct dentry *, struct iattr *, dev_t); int (*statfs) (struct nfs_server *, struct nfs_fh *, struct nfs_fsstat *); int (*fsinfo) (struct nfs_server *, struct nfs_fh *, struct nfs_fsinfo *); int (*pathconf) (struct nfs_server *, struct nfs_fh *, struct nfs_pathconf *); int (*set_capabilities)(struct nfs_server *, struct nfs_fh *); int (*decode_dirent)(struct xdr_stream *, struct nfs_entry *, bool); int (*pgio_rpc_prepare)(struct rpc_task *, struct nfs_pgio_header *); void (*read_setup)(struct nfs_pgio_header *, struct rpc_message *); int (*read_done)(struct rpc_task *, struct nfs_pgio_header *); void (*write_setup)(struct nfs_pgio_header *, struct rpc_message *); int (*write_done)(struct rpc_task *, struct nfs_pgio_header *); void (*commit_setup) (struct nfs_commit_data *, struct rpc_message *); void (*commit_rpc_prepare)(struct rpc_task *, struct nfs_commit_data *); int (*commit_done) (struct rpc_task *, struct nfs_commit_data *); int (*lock)(struct file *, int, struct file_lock *); int (*lock_check_bounds)(const struct file_lock *); void (*clear_acl_cache)(struct inode *); void (*close_context)(struct nfs_open_context *ctx, int); struct inode * (*open_context) (struct inode *dir, struct nfs_open_context *ctx, int open_flags, struct iattr *iattr, int *); int (*have_delegation)(struct inode *, fmode_t); int (*return_delegation)(struct inode *); struct nfs_client *(*alloc_client) (const struct nfs_client_initdata *); struct nfs_client *(*init_client) (struct nfs_client *, const struct nfs_client_initdata *); void (*free_client) (struct nfs_client *); struct nfs_server *(*create_server)(struct nfs_mount_info *, struct nfs_subversion *); struct nfs_server *(*clone_server)(struct nfs_server *, struct nfs_fh *, struct nfs_fattr *, rpc_authflavor_t); }; /* * NFS_CALL(getattr, inode, (fattr)); * into * NFS_PROTO(inode)->getattr(fattr); */ #define NFS_CALL(op, inode, args) NFS_PROTO(inode)->op args /* * Function vectors etc. for the NFS client */ extern const struct nfs_rpc_ops nfs_v2_clientops; extern const struct nfs_rpc_ops nfs_v3_clientops; extern const struct nfs_rpc_ops nfs_v4_clientops; extern const struct rpc_version nfs_version2; extern const struct rpc_version nfs_version3; extern const struct rpc_version nfs_version4; extern const struct rpc_version nfsacl_version3; extern const struct rpc_program nfsacl_program; #endif
{ "pile_set_name": "Github" }
version: 1 n_points: 4 { 353.146 571.409 353.146 1323.205 1104.942 1323.205 1104.942 571.409 }
{ "pile_set_name": "Github" }
// // RNHorizontalBarChartManager.swift // RCTIOSCharts // // Created by Jose Padilla on 12/24/15. // Copyright © 2015 Facebook. All rights reserved. // import Foundation @objc(RNPieChartSwift) class RNPieChartManager : RCTViewManager { override func view() -> UIView! { return RNPieChart(); } }
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.15"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="pages_0.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ createResults(); /* @license-end */ --></script> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); /* @license-end */ --></script> </div> </body> </html>
{ "pile_set_name": "Github" }
# 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. # ============================================================================== """SinhArcsinh bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.contrib.distributions.python.ops.bijectors.sinh_arcsinh_impl import * # pylint: enable=wildcard-import from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = ["SinhArcsinh"] remove_undocumented(__name__, _allowed_symbols)
{ "pile_set_name": "Github" }
/***************************************************************************/ /* */ /* ftsystem.h */ /* */ /* FreeType low-level system interface definition (specification). */ /* */ /* Copyright 1996-2001, 2002, 2005, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTSYSTEM_H__ #define __FTSYSTEM_H__ #include <ft2build.h> FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* system_interface */ /* */ /* <Title> */ /* System Interface */ /* */ /* <Abstract> */ /* How FreeType manages memory and i/o. */ /* */ /* <Description> */ /* This section contains various definitions related to memory */ /* management and i/o access. You need to understand this */ /* information if you want to use a custom memory manager or you own */ /* i/o streams. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* M E M O R Y M A N A G E M E N T */ /* */ /*************************************************************************/ /************************************************************************* * * @type: * FT_Memory * * @description: * A handle to a given memory manager object, defined with an * @FT_MemoryRec structure. * */ typedef struct FT_MemoryRec_* FT_Memory; /************************************************************************* * * @functype: * FT_Alloc_Func * * @description: * A function used to allocate `size' bytes from `memory'. * * @input: * memory :: * A handle to the source memory manager. * * size :: * The size in bytes to allocate. * * @return: * Address of new memory block. 0~in case of failure. * */ typedef void* (*FT_Alloc_Func)( FT_Memory memory, long size ); /************************************************************************* * * @functype: * FT_Free_Func * * @description: * A function used to release a given block of memory. * * @input: * memory :: * A handle to the source memory manager. * * block :: * The address of the target memory block. * */ typedef void (*FT_Free_Func)( FT_Memory memory, void* block ); /************************************************************************* * * @functype: * FT_Realloc_Func * * @description: * A function used to re-allocate a given block of memory. * * @input: * memory :: * A handle to the source memory manager. * * cur_size :: * The block's current size in bytes. * * new_size :: * The block's requested new size. * * block :: * The block's current address. * * @return: * New block address. 0~in case of memory shortage. * * @note: * In case of error, the old block must still be available. * */ typedef void* (*FT_Realloc_Func)( FT_Memory memory, long cur_size, long new_size, void* block ); /************************************************************************* * * @struct: * FT_MemoryRec * * @description: * A structure used to describe a given memory manager to FreeType~2. * * @fields: * user :: * A generic typeless pointer for user data. * * alloc :: * A pointer type to an allocation function. * * free :: * A pointer type to an memory freeing function. * * realloc :: * A pointer type to a reallocation function. * */ struct FT_MemoryRec_ { void* user; FT_Alloc_Func alloc; FT_Free_Func free; FT_Realloc_Func realloc; }; /*************************************************************************/ /* */ /* I / O M A N A G E M E N T */ /* */ /*************************************************************************/ /************************************************************************* * * @type: * FT_Stream * * @description: * A handle to an input stream. * */ typedef struct FT_StreamRec_* FT_Stream; /************************************************************************* * * @struct: * FT_StreamDesc * * @description: * A union type used to store either a long or a pointer. This is used * to store a file descriptor or a `FILE*' in an input stream. * */ typedef union FT_StreamDesc_ { long value; void* pointer; } FT_StreamDesc; /************************************************************************* * * @functype: * FT_Stream_IoFunc * * @description: * A function used to seek and read data from a given input stream. * * @input: * stream :: * A handle to the source stream. * * offset :: * The offset of read in stream (always from start). * * buffer :: * The address of the read buffer. * * count :: * The number of bytes to read from the stream. * * @return: * The number of bytes effectively read by the stream. * * @note: * This function might be called to perform a seek or skip operation * with a `count' of~0. A non-zero return value then indicates an * error. * */ typedef unsigned long (*FT_Stream_IoFunc)( FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ); /************************************************************************* * * @functype: * FT_Stream_CloseFunc * * @description: * A function used to close a given input stream. * * @input: * stream :: * A handle to the target stream. * */ typedef void (*FT_Stream_CloseFunc)( FT_Stream stream ); /************************************************************************* * * @struct: * FT_StreamRec * * @description: * A structure used to describe an input stream. * * @input: * base :: * For memory-based streams, this is the address of the first stream * byte in memory. This field should always be set to NULL for * disk-based streams. * * size :: * The stream size in bytes. * * pos :: * The current position within the stream. * * descriptor :: * This field is a union that can hold an integer or a pointer. It is * used by stream implementations to store file descriptors or `FILE*' * pointers. * * pathname :: * This field is completely ignored by FreeType. However, it is often * useful during debugging to use it to store the stream's filename * (where available). * * read :: * The stream's input function. * * close :: * The stream's close function. * * memory :: * The memory manager to use to preload frames. This is set * internally by FreeType and shouldn't be touched by stream * implementations. * * cursor :: * This field is set and used internally by FreeType when parsing * frames. * * limit :: * This field is set and used internally by FreeType when parsing * frames. * */ typedef struct FT_StreamRec_ { unsigned char* base; unsigned long size; unsigned long pos; FT_StreamDesc descriptor; FT_StreamDesc pathname; FT_Stream_IoFunc read; FT_Stream_CloseFunc close; FT_Memory memory; unsigned char* cursor; unsigned char* limit; } FT_StreamRec; /* */ FT_END_HEADER #endif /* __FTSYSTEM_H__ */ /* END */
{ "pile_set_name": "Github" }
package algs.blog.multithread.nearestNeighbor.onehelper; /** * This just validates brute force solution is same to kd-tree solution. */ import java.util.Random; import algs.model.FloatingPoint; import algs.model.IMultiPoint; import algs.model.kdtree.KDFactory; import algs.model.kdtree.KDTree; import algs.model.nd.Hyperpoint; import algs.model.tests.common.TrialSuite; /** * Compute crossover effect (when no longer efficient as dimensions increase) * for the multi-threaded nearest neighbor queries. * <p> * In this case, a helper thread is spawned the first time a double-recursion * is needed. * * @author George Heineman * @version 1.0, 6/1/09 */ public class OneHelperKDCrossoverMain { /** random number generator. */ static Random rGen; /** * generate array of n d-dimensional points whose coordinates are * values in the range 0 .. 1 */ public static IMultiPoint[] randomPoints (int n, int d) { IMultiPoint points[] = new IMultiPoint[n]; for (int i = 0; i < n; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < d; j++) { sb.append(rGen.nextDouble()); if (j < d-1) { sb.append (","); } } points[i] = new Hyperpoint(sb.toString()); } return points; } /** * Run the comparison. */ public static void main (String []args) { rGen = new Random(); rGen.setSeed(1); // be consistent across platforms and runs. // dimension for points. int d = 2; int maxD = 25; int n = 4096; int numSearches = 1024; // create set of points. Note that the search will always ensure that no // points are found. TrialSuite []kdSearch = new TrialSuite[maxD]; TrialSuite []pkdSearch = new TrialSuite[maxD]; TrialSuite []waiting = new TrialSuite[maxD]; for (d=2; d < maxD; d++) { System.out.println(d + " ... "); long now, done; kdSearch[d] = new TrialSuite(); pkdSearch[d] = new TrialSuite(); waiting[d] = new TrialSuite(); // create n random points in d dimensions drawn from [0,1] uniformly IMultiPoint[] points = randomPoints (n, d); // Perform a number of searches drawn from same [0,1] uniformly. System.gc(); IMultiPoint[] searchPoints = randomPoints (numSearches, d); // This forms the basis for the kd-tree. These are the points p. Note // that the KDTree generate method will likely shuffle the points. KDTree tree = KDFactory.generate(points); OneHelperKDTree ttree = OneHelperKDFactory.generate(points); IMultiPoint[] resultsKD = new IMultiPoint[numSearches]; IMultiPoint[] resultsPKD = new IMultiPoint[numSearches]; int idx = 0; System.gc(); now = System.currentTimeMillis(); for (IMultiPoint imp : searchPoints) { resultsKD[idx++] = tree.nearest(imp); } done = System.currentTimeMillis(); kdSearch[d].addTrial(d, now, done); idx = 0; System.gc(); now = System.currentTimeMillis(); for (IMultiPoint imp : searchPoints) { resultsPKD[idx++] = ttree.nearest(imp); } done = System.currentTimeMillis(); pkdSearch[d].addTrial(d, now, done); waiting[d].addTrial(d, 0, OneHelperKDNode.waiting); OneHelperKDNode.waiting = 0; // compare results? int numDiff = 0; for (int i = 0; i < searchPoints.length; i++) { if (resultsKD[i] != resultsPKD[i]) { double bf = resultsKD[i].distance(searchPoints[i]); double kd = resultsPKD[i].distance(searchPoints[i]); if (!FloatingPoint.same(bf, kd)) { numDiff++; } } } if (numDiff != 0) { System.out.println(d + " has " + numDiff + " differences!"); } } System.out.println("KD search"); for (d = 2; d < kdSearch.length; d++) { System.out.println(kdSearch[d].computeTable()); } System.out.println("PKD search"); for (d = 2; d < pkdSearch.length; d++) { System.out.println(pkdSearch[d].computeTable()); } System.out.println("Waiting times"); for (d = 2; d < waiting.length; d++) { System.out.println(waiting[d].computeTable()); } } }
{ "pile_set_name": "Github" }