public CustomBinaryInputOutputStream(string id, Callable read, Callable write, object get_pos, object set_pos, object close) { this.id = id; this.read = read; this.write = write; // rest optional this.get_pos = get_pos as Callable; this.set_pos = set_pos as Callable; this.close = close as Callable; }
public virtual object checkSucceeds(Callable callable) { object obj; Exception error; try { obj = callable.call(); } catch (Exception ex) { int num = 0; error = (Exception) ByteCodeHelper.MapException<Exception>(ex, (ByteCodeHelper.MapFlags) num); goto label_3; } return obj; label_3: this.addError(error); return (object) null; }
public BoundFunction(Context cx, Scriptable scope, Callable targetFunction, Scriptable boundThis, object[] boundArgs) { this.targetFunction = targetFunction; this.boundThis = boundThis; this.boundArgs = boundArgs; if (targetFunction is BaseFunction) { length = Math.Max(0, ((BaseFunction)targetFunction).GetLength() - boundArgs.Length); } else { length = 0; } ScriptRuntime.SetFunctionProtoAndParent(this, scope); Function thrower = ScriptRuntime.TypeErrorThrower(); NativeObject throwing = new NativeObject(); throwing.Put("get", throwing, thrower); throwing.Put("set", throwing, thrower); throwing.Put("enumerable", throwing, false); throwing.Put("configurable", throwing, false); throwing.PreventExtensions(); this.DefineOwnProperty(cx, "caller", throwing, false); this.DefineOwnProperty(cx, "arguments", throwing, false); }
public _ContextAction_476(Callable callable, Scriptable scope, Scriptable thisObj, object[] args) { this.callable = callable; this.scope = scope; this.thisObj = thisObj; this.args = args; }
static void HandleFn(Vm vm) { var instruction = vm.CurrentInstruction (); var args = (int[])instruction.Arguments; var callable = new Callable () { ProgramCounter = args[0], Arity = args[1], Environment = vm.currentEnvironment }; if (vm.currentEnvironment != null) { vm.currentEnvironment.IncreaseUses (); } vm.stack.Push (Value.Make (callable)); vm.IncrementCells (5); vm.programCounter++; }
Callable RebuildCallable( object[] objects, int index, Composite composite, Func<int, object> reader) { var result = new Callable (); objects [index] = result; result.UdpName = (string)reader (composite.Elements [0]); result.Prim0Name = (string)reader (composite.Elements [1]); result.Arity = (int?)(long?)reader (composite.Elements [2]); result.ProgramCounter = (int?)(long?)reader (composite.Elements [3]); result.Environment = (VmEnvironment)reader (composite.Elements [4]); return result; }
public virtual Future <V> submit(Callable <V> prm1) { return(default(Future <V>)); }
/// <summary> /// Creates a {@code FutureTask} that will, upon running, execute the /// given {@code Runnable}, and arrange that {@code get} will return the /// given result on successful completion. /// </summary> /// <param name="runnable"> the runnable task </param> /// <param name="result"> the result to return on successful completion. If /// you don't need a particular result, consider using /// constructions of the form: /// {@code Future<?> f = new FutureTask<Void>(runnable, null)} </param> /// <exception cref="NullPointerException"> if the runnable is null </exception> public FutureTask(Runnable runnable, V result) { this.Callable = Executors.Callable(runnable, result); this.State = NEW; // ensure visibility of callable }
/// <summary>Perform function call in reference context.</summary> /// <remarks> /// Perform function call in reference context. Should always /// return value that can be passed to /// <see cref="RefGet(Ref, Context)">RefGet(Ref, Context)</see> /// or /// <see cref="RefSet(Ref, object, Context)">RefSet(Ref, object, Context)</see> /// arbitrary number of times. /// The args array reference should not be stored in any object that is /// can be GC-reachable after this method returns. If this is necessary, /// store args.clone(), not args array itself. /// </remarks> public static Ref CallRef(Callable function, Scriptable thisObj, object[] args, Context cx) { if (function is RefCallable) { RefCallable rfunction = (RefCallable)function; Ref @ref = rfunction.RefCall(cx, thisObj, args); if (@ref == null) { throw new InvalidOperationException(rfunction.GetType().FullName + ".refCall() returned null"); } return @ref; } // No runtime support for now string msg = GetMessage1("msg.no.ref.from.function", ToString(function)); throw ConstructError("ReferenceError", msg); }
/// <exception cref="System.Exception"/> public static T DoAsServer <T>(Callable <T> callable) { return(DoAs(GetServerPrincipal(), callable)); }
public CustomTextWriter(string id, Callable write, object get_pos, object set_pos, object close) { this.id = id; this.write = write; // rest optional this.get_pos = get_pos as Callable; this.set_pos = set_pos as Callable; this.close = close as Callable; }
public _PrivilegedExceptionAction_99(Callable <T> callable) { this.callable = callable; }
/// <exception cref="System.Exception"/> public static T DoAsClient <T>(Callable <T> callable) { return(DoAs(GetClientPrincipal(), callable)); }
private void OnMouseDown() { Callable.Call(MouseDown, this.gameObject); }
static Racr() { "(import (racr core))".Eval(); "(import (racr testing))".Eval(); // bridge nodeDotNetInstance = "node-dot-net-instance".Eval <Callable>(); nodeDotNetInstanceSet = "node-dot-net-instance-set!".Eval <Callable>(); // ast createSpecification = "create-specification".Eval <Callable>(); astRule = "ast-rule".Eval <Callable>(); compileAstSpecifications = "compile-ast-specifications".Eval <Callable>(); compileAgSpecifications = "compile-ag-specifications".Eval <Callable>(); createAst = "create-ast".Eval <Callable>(); createAstList = "create-ast-list".Eval <Callable>(); createAstBud = "create-ast-bud".Eval <Callable>(); astParent = "ast-parent".Eval <Callable>(); astChild = "ast-child".Eval <Callable>(); astSibling = "ast-sibling".Eval <Callable>(); astChildren = "ast-children".Eval <Callable>(); astForEachChild = "ast-for-each-child".Eval <Callable>(); astFindChild = "ast-find-child".Eval <Callable>(); astFindChildA = "ast-find-child*".Eval <Callable>(); astNodeQ = "ast-node?".Eval <Callable>(); astHasParentQ = "ast-has-parent?".Eval <Callable>(); astChildIndex = "ast-child-index".Eval <Callable>(); astHasChildQ = "ast-has-child?".Eval <Callable>(); astNumChildren = "ast-num-children".Eval <Callable>(); astHasSiblingQ = "ast-has-sibling?".Eval <Callable>(); astNodeType = "ast-node-type".Eval <Callable>(); astListNodeQ = "ast-list-node?".Eval <Callable>(); astBudNodeQ = "ast-bud-node?".Eval <Callable>(); astSubtypeQ = "ast-subtype?".Eval <Callable>(); // attribution specifyAttribute = "specify-attribute".Eval <Callable>(); attValue = "att-value".Eval <Callable>(); // rewriting rewriteTerminal = "rewrite-terminal".Eval <Callable>(); rewriteRefine = "rewrite-refine".Eval <Callable>(); rewriteAbstract = "rewrite-abstract".Eval <Callable>(); rewriteSubtree = "rewrite-subtree".Eval <Callable>(); rewriteAdd = "rewrite-add".Eval <Callable>(); rewriteInsert = "rewrite-insert".Eval <Callable>(); rewriteDelete = "rewrite-delete".Eval <Callable>(); // ast annotations astAnnotationSet = "ast-annotation-set!".Eval <Callable>(); astWeaveAnnotations = "ast-weave-annotations".Eval <Callable>(); astAnnotationRemove = "ast-annotation-remove!".Eval <Callable>(); astAnnotationQ = "ast-annotation?".Eval <Callable>(); astAnnotation = "ast-annotation".Eval <Callable>(); // specification query interface specificationFindAstRule = "specification->find-ast-rule".Eval <Callable>(); astRuleProduction = "ast-rule->production".Eval <Callable>(); symbolIsNonTerminal = "symbol->non-terminal?".Eval <Callable>(); // testing printAst = @"(lambda (ast attmap) (let ((port (open-output-string))) (print-ast ast attmap port) (get-output-string port)))" .Eval <Callable>(); }
public Binding(SerializedProperty serializedProperty, Callable value) { propertyPath = propertyToPath(serializedProperty); callable = value; }
public HashComparer(Callable hash, Callable equiv) { this.hash = hash; this.equiv = equiv; }
private static void QSort( Thread thread, Table list, Callable less, int l, int u ) { while( l < u ) { var vl = list[l]; var vu = list[u]; if( thread.Less( vu, vl, less ) ) { //swap var tmp = vl; vl = vu; vu = tmp; list[l] = vl; list[u] = vu; } if( u - l == 1 ) //only had two elements break; var i = (l + u) / 2; var vi = list[i]; if( thread.Less( vi, vl, less ) ) { var tmp = vl; vl = vi; vi = tmp; list[l] = vl; list[i] = vi; } else if( thread.Less( vu, vi, less ) ) { var tmp = vu; vu = vi; vi = tmp; list[u] = vu; list[i] = vi; } if( u - l == 2 ) //only had three elements break; var vp = vi; var j = u - 1; var vj = list[j]; list[j] = vi; list[i] = vj; i = l; for( ; ; ) { while( thread.Less( vi = list[++i], vp, less ) ) { if( i >= u ) throw new ArgumentException( "Invalid sort function." ); } while( thread.Less( vp, vj = list[--j], less ) ) { if( j <= l ) throw new ArgumentException( "Invalid sort function." ); } if( j < i ) break; list[i] = vj; list[j] = vi; } list[u - 1] = list[i]; list[i] = vp; if( i - l < u - i ) { j = l; i--; l = i + 2; } else { j = i + 1; i = u; u = j - 2; } QSort( thread, list, less, j, i ); } }
int CountCellsCallable(Callable callable, HashSet<object> visited) { var sum = 5; visited.Add (callable); sum += CountCellsString (callable.UdpName); sum += CountCellsString (callable.Prim0Name); sum += CountCellsImpl (callable.Environment, visited); return sum; }
public AsyncResult submit(Callable c) { return(new MonoGameAsyncResult(Task.Factory.StartNew(c.call))); }
public static Callable RecordConstructor(object cd) { RecordConstructorDescriptor ci = RequiresNotNull<RecordConstructorDescriptor>(cd); Type tt = ci.type.Finish(); // this is foo.make(params object[] args) calls constructor(s). Callable pp = ci.type.Constructor as Callable; RecordConstructorDescriptor rcd = ci; List<Callable> init = new List<Callable>(); while (rcd != null) { if (rcd.protocol != null) { init.Add(rcd.protocol); } rcd = rcd.parent; } if (init.Count == 0) { CallTargetN np = delegate(object[] args) { if (ci.type.TotalFieldCount != args.Length) { return AssertionViolation(ci.type.Name, string.Format("Incorrect number of arguments, expected {0} got {1}", ci.type.TotalFieldCount, args.Length), args); } return pp.Call(args); }; return Closure.Create(np); } else { init.Reverse(); CallTargetN np = delegate(object[] args) { Callable ppp = pp; List<object> allargs = new List<object>(); int i = init.Count; Callable collector = null; CallTargetN xxx = delegate(object[] margs) { allargs.AddRange(margs); if (i == 0) { if (ci.type.TotalFieldCount != allargs.Count) { return AssertionViolation(ci.type.Name, string.Format("Incorrect number of arguments, expected {0} got {1}", ci.type.TotalFieldCount, allargs.Count), allargs.ToArray()); } return pp.Call(allargs.ToArray()); } else { i--; return collector; } }; ppp = collector = Closure.Create(xxx) as Callable; foreach (Callable ctr in init) { ppp = ctr.Call(ppp) as Callable; } object result = ppp.Call(args); if (result == collector) { result = collector.Call(); } return result; }; return Closure.Create(np); } }
private static object Walk(Context cx, Scriptable scope, Callable reviver, Scriptable holder, object name) { object property; if (name is Number) { property = holder.Get(System.Convert.ToInt32(((Number)name)), holder); } else { property = holder.Get(((string)name), holder); } if (property is Scriptable) { Scriptable val = ((Scriptable)property); if (val is NativeArray) { long len = ((NativeArray)val).GetLength(); for (long i = 0; i < len; i++) { // indices greater than MAX_INT are represented as strings if (i > int.MaxValue) { string id = System.Convert.ToString(i); object newElement = Walk(cx, scope, reviver, val, id); if (newElement == Undefined.instance) { val.Delete(id); } else { val.Put(id, val, newElement); } } else { int idx = (int)i; object newElement = Walk(cx, scope, reviver, val, idx); if (newElement == Undefined.instance) { val.Delete(idx); } else { val.Put(idx, val, newElement); } } } } else { object[] keys = val.GetIds(); foreach (object p in keys) { object newElement = Walk(cx, scope, reviver, val, p); if (newElement == Undefined.instance) { if (p is Number) { val.Delete(System.Convert.ToInt32(((Number)p))); } else { val.Delete((string)p); } } else { if (p is Number) { val.Put(System.Convert.ToInt32(((Number)p)), val, newElement); } else { val.Put((string)p, val, newElement); } } } } } return reviver.Call(cx, scope, holder, new object[] { name, property }); }
public IEnumerator ShakeCoroutine(ShakeManager.Settings shake, float attenuation) { float dist = Vector3.Distance(transform.position, shake.Position); //float intensity = shake.Intensity / Mathf.Pow(dist + 1, attenuation); float intensity = shake.Intensity; Vector3 forceVector = Vector3.Normalize(transform.position - shake.Position) * intensity; if (maxDelay > 0.0f) { yield return(new WaitForSeconds(Random.Range(0.0f, maxDelay))); } if (rigidBodies != null) { foreach (var rb in rigidBodies) { if (rb == null) { continue; } rb.AddForce(forceVector * impulseGain, ForceMode.Impulse); } } if (visualEffects != null) { foreach (var vfx in visualEffects) { if (vfx == null || (playOnlyIfVisible && vfx.culled)) { continue; } if (!eventAttributes.ContainsKey(vfx)) { eventAttributes.Add(vfx, vfx.CreateVFXEventAttribute()); } if (setPositionAttribute) { eventAttributes[vfx].SetVector3(position, shake.Position); } if (setSizeAttribute && eventAttributes[vfx].HasFloat(size)) { eventAttributes[vfx].SetFloat(size, intensity); } if (setVelocityAttribute) { eventAttributes[vfx].SetVector3(velocity, forceVector); } vfx.SendEvent(eventName, eventAttributes[vfx]); } if (visualEffects.Length > 0 && disableAfterDelay > 0.0f) { if (stopVFXCoroutine != null) { StopCoroutine(stopVFXCoroutine); } stopVFXCoroutine = StartCoroutine(StopAfter()); } } Callable.Call(OnShake); }
static void CallPrimitive(Callable callable, Vm vm, int numArgs, bool saveReturnAddress, bool inApply) { bool isRequiredPrimitive = false; if (callable.Prim0Name != null) { isRequiredPrimitive = true; if (callable.RequiredPrimitive == null) { callable.RequiredPrimitive = Vm.Prim0Hash [callable.Prim0Name].RequiredPrimitive; } } else if (callable.UserDefinedPrimitive == null) { callable.UserDefinedPrimitive = GetUdpByName (vm, callable.UdpName).UserDefinedPrimitive; } if (callable.Arity != null && callable.Arity.Value != numArgs) { ArityError (vm, callable.Arity.Value, numArgs, inApply); } Value[] array; int start; if (isRequiredPrimitive) { vm.stack.Pop (); // Remove the callable. vm.stack.GetTopRange (numArgs, out array, out start); FinishPrimitiveCall ( vm, numArgs, saveReturnAddress, callable.RequiredPrimitive (vm.api, array, start, numArgs)); } else { vm.stack.GetTopRange (numArgs + 1, out array, out start); var udpResult = new UdpResult (); Value[] args = new Value[numArgs]; Array.Copy (vm.stack.Storage, start, args, 0, numArgs); try { callable.UserDefinedPrimitive (vm.api, args, udpResult); } catch (Exception ex) { vm.userDefinedPrimitiveError = ex; vm.shouldTakeANap = true; } switch (udpResult.After) { case UdpResult.AfterCall.Continue: vm.stack.Pop (); FinishPrimitiveCall (vm, numArgs, saveReturnAddress, udpResult.Result); break; case UdpResult.AfterCall.Nap: vm.stack.Pop (); FinishPrimitiveCall (vm, numArgs, saveReturnAddress, udpResult.Result); vm.shouldTakeANap = true; break; case UdpResult.AfterCall.NapAndRetryOnWakeUp: vm.shouldTakeANap = true; break; } } }
private void InputAction_performed(InputAction.CallbackContext obj) { Callable.Call(onButtonDown, gameObject); }
public static object DoTopCall(Callable callable, Context cx, Scriptable scope, Scriptable thisObj, object[] args) { if (scope == null) { throw new ArgumentException(); } if (cx.topCallScope != null) { throw new InvalidOperationException(); } object result; cx.topCallScope = ScriptableObject.GetTopLevelScope(scope); cx.useDynamicScope = cx.HasFeature(Context.FEATURE_DYNAMIC_SCOPE); ContextFactory f = cx.GetFactory(); try { result = f.DoTopCall(callable, cx, scope, thisObj, args); } finally { cx.topCallScope = null; // Cleanup cached references cx.cachedXMLLib = null; if (cx.currentActivationCall != null) { // Function should always call exitActivationFunction // if it creates activation record throw new InvalidOperationException(); } } return result; }
void SetMenu(object o) { Callable component = o as Callable; setNextObjectValue = component; }
public IndexBuilder(DynamicMetaObject/*!*/[]/*!*/ types, Callable/*!*/ callable) { _callable = callable; _types = types; }
private void Start() { Callable.Call(OnStart); }
/// <summary> /// Call /// <see cref="Callable.Call(Context, Scriptable, Scriptable, object[])">Callable.Call(Context, Scriptable, Scriptable, object[])</see> /// using the Context instance associated with the current thread. /// If no Context is associated with the thread, then /// <see cref="ContextFactory.MakeContext()">ContextFactory.MakeContext()</see> /// will be called to construct /// new Context instance. The instance will be temporary associated /// with the thread during call to /// <see cref="ContextAction.Run(Context)">ContextAction.Run(Context)</see> /// . /// <p> /// It is allowed but not advisable to use null for <tt>factory</tt> /// argument in which case the global static singleton ContextFactory /// instance will be used to create new context instances. /// </summary> /// <seealso cref="ContextFactory.Call(ContextAction)">ContextFactory.Call(ContextAction)</seealso> public static object Call(ContextFactory factory, Callable callable, Scriptable scope, Scriptable thisObj, object[] args) { if (factory == null) { factory = ContextFactory.GetGlobal(); } return Call(factory, new _ContextAction_476(callable, scope, thisObj, args)); }
public static T ToDelegate <T>(this Callable c) { return(Runtime.Helpers.ConvertToDelegate <T>(c)); }
static void CallFunction(Callable callable, Vm vm, int numArgs, bool saveReturnAddress) { if (saveReturnAddress) { vm.stack.Push (Value.Make (new ReturnAddress () { ProgramCounter = vm.programCounter + 1, Environment = vm.currentEnvironment } ) ); vm.currentEnvironment.IncreaseUsesLocally (); } if (callable.Arity != null && callable.Arity.Value != numArgs) { ArityError (vm, callable.Arity.Value, numArgs); } vm.currentEnvironment = callable.Environment; vm.programCounter = callable.ProgramCounter.Value; }
/// <summary> /// Takes an <seealso cref="ActivityExecution"/> and an <seealso cref="Callable"/> and wraps /// the call to the Callable with the proper error propagation. This method /// also makes sure that exceptions not caught by following activities in the /// process will be thrown and not propagated. /// </summary> /// <param name="execution"> </param> /// <param name="toExecute"> </param> /// <exception cref="Exception"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: protected void executeWithErrorPropagation(org.camunda.bpm.engine.impl.pvm.delegate.ActivityExecution execution, java.util.concurrent.Callable<Void> toExecute) throws Exception protected internal virtual void executeWithErrorPropagation(ActivityExecution execution, Callable <Void> toExecute) { string activityInstanceId = execution.ActivityInstanceId; try { toExecute.call(); } catch (Exception ex) { if (activityInstanceId.Equals(execution.ActivityInstanceId)) { try { BpmnExceptionHandler.propagateException(execution, ex); } catch (ErrorPropagationException) { // exception has been logged by thrower // re-throw the original exception so that it is logged // and set as cause of the failure throw ex; } } else { throw ex; } } }
private void OnDisable() { Callable.Call(OnDisableEvent, gameObject); }
public void Start() { m_CurrentLevel = int.MinValue; Callable.Call(OnGameStart); }
protected override object DoTopCall(Callable callable, Context cx, Scriptable scope, Scriptable thisObj, object[] args) { ObserveInstructionCountTest.MyContext mcx = (ObserveInstructionCountTest.MyContext)cx; mcx.quota = 2000; return base.DoTopCall(callable, cx, scope, thisObj, args); }
/// <summary> /// Get the mapping instance of <seealso cref="ConnectionPool"/> with the specified poolKey, /// or create one if there is none mapping in connTasks. /// </summary> /// <param name="poolKey"> mapping key of <seealso cref="ConnectionPool"/> </param> /// <param name="callable"> the callable task </param> /// <returns> a non-nullable instance of <seealso cref="ConnectionPool"/> </returns> /// <exception cref="RemotingException"> if there is no way to get an available <seealso cref="ConnectionPool"/> </exception> /// <exception cref="ThreadInterruptedException"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private ConnectionPool getConnectionPoolAndCreateIfAbsent(String poolKey, java.util.concurrent.Callable<ConnectionPool> callable) throws exception.RemotingException, ThreadInterruptedException private ConnectionPool getConnectionPoolAndCreateIfAbsent(string poolKey, Callable callable) { RunStateRecordedFutureTask initialTask; ConnectionPool pool = null; int retry = Constants.DEFAULT_RETRY_TIMES; int timesOfResultNull = 0; int timesOfInterrupt = 0; for (int i = 0; (i < retry) && (pool == null); ++i) { connTasks.TryGetValue(poolKey, out initialTask); if (null == initialTask) { RunStateRecordedFutureTask newTask = new RunStateRecordedFutureTask(callable); if (!connTasks.ContainsKey(poolKey)) { connTasks.AddOrUpdate(poolKey, newTask, (_, __) => newTask); initialTask = newTask; } else { connTasks.TryGetValue(poolKey, out initialTask); } initialTask.run(); } try { pool = (ConnectionPool)initialTask.get(); if (null == pool) { if (i + 1 < retry) { timesOfResultNull++; continue; } connTasks.TryRemove(poolKey, out _); string errMsg = "Get future task result null for poolKey [" + poolKey + "] after [" + (timesOfResultNull + 1) + "] times try."; throw new RemotingException(errMsg); } } catch (ThreadInterruptedException e) { if (i + 1 < retry) { timesOfInterrupt++; continue; // retry if interrupted } connTasks.TryRemove(poolKey, out _); logger.LogWarning("Future task of poolKey {} interrupted {} times. ThreadInterruptedException thrown and stop retry.", poolKey, timesOfInterrupt + 1, e); throw; } catch (ExecutionException e) { // DO NOT retry if ExecutionException occurred connTasks.TryRemove(poolKey, out _); System.Exception cause = e.InnerException; if (cause is RemotingException) { throw (RemotingException)cause; } else { FutureTaskUtil.launderThrowable(cause); } } } return(pool); }
public CustomTextReader(string id, Callable read, object get_pos, object set_pos, object close) { this.id = id; this.read = read; // rest optional this.get_pos = get_pos as Callable; this.set_pos = set_pos as Callable; this.close = close as Callable; }
public static void Main(string[] args) { LangDescriptor[] languages = new LangDescriptor[] { Tool.ANTLR4_DESCR }; int MAX_K = 98; // should be odd int OUTLIER_K = 99; IList <int?> ks = new List <int?>(); for (int i = 1; i <= MAX_K; i += 2) { ks.Add(i); } ks.Add(OUTLIER_K); // track medians[language][k] float[][] medians = new float[languages.Length + 1][]; int ncpu = 1; if (FORCE_SINGLE_THREADED) { ncpu = 2; } ExecutorService pool = Executors.newFixedThreadPool(ncpu - 1); IList <Callable <Void> > jobs = new List <Callable <Void> >(); for (int i = 0; i < languages.Length; i++) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.antlr.codebuff.misc.LangDescriptor language = languages[i]; LangDescriptor language = languages[i]; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int langIndex = i; int langIndex = i; Console.WriteLine(language.name); foreach (int k in ks) { medians[langIndex] = new float?[OUTLIER_K + 1]; Callable <Void> job = () => { try { TestK tester = new TestK(language.corpusDir, language, k); IList <float?> errorRates = tester.scoreDocuments(); errorRates.Sort(); int n = errorRates.Count; float median = errorRates[n / 2].Value; // double var = BuffUtils.varianceFloats(errorRates); // String display = String.format("%5.4f, %5.4f, %5.4f, %5.4f, %5.4f", min, quart, median, quart3, max); medians[langIndex][k] = median; } catch (Exception t) { t.printStackTrace(System.err); } return(null); }; jobs.Add(job); } } pool.invokeAll(jobs); pool.shutdown(); bool terminated = pool.awaitTermination(60, TimeUnit.MINUTES); writePython(languages, ks, medians); }
public EncCB(Callable error) { this.error = error; }
private void OnBecameInvisible() { Callable.Call(OnInvisible, this.gameObject); }
static void AddPrim0(Dictionary<string, Callable> result, Callable callable) { result [callable.Prim0Name] = callable; }
/// <summary> /// Use <seealso cref="executeWithinProcessApplication(Callable, ProcessApplicationReference, InvocationContext)"/> /// instead if an <seealso cref="InvocationContext"/> is available. /// </summary> public static T executeWithinProcessApplication <T>(Callable <T> callback, ProcessApplicationReference processApplicationReference) { return(executeWithinProcessApplication(callback, processApplicationReference, null)); }
public static object Parse(Context cx, Scriptable scope, string jtext, Callable reviver) { object unfiltered = Parse(cx, scope, jtext); Scriptable root = cx.NewObject(scope); root.Put(string.Empty, root, unfiltered); return Walk(cx, scope, reviver, root, string.Empty); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public <T> T execute(java.util.concurrent.Callable<T> callable, InvocationContext invocationContext) throws ProcessApplicationExecutionException public virtual T execute <T>(Callable <T> callable, InvocationContext invocationContext) { // allows to hook into the invocation return(execute(callable)); }
internal StringifyState(Context cx, Scriptable scope, string indent, string gap, Callable replacer, IList<object> propertyList, object space) { this.cx = cx; this.scope = scope; this.indent = indent; this.gap = gap; this.replacer = replacer; this.propertyList = propertyList; this.space = space; }
public virtual void waitForJobExecutorOnCondition(long maxMillisToWait, long intervalMillis, Callable <bool> condition) { JobExecutor jobExecutor = processEngineConfiguration.JobExecutor; jobExecutor.start(); try { Timer timer = new Timer(); InteruptTask task = new InteruptTask(Thread.CurrentThread); timer.schedule(task, maxMillisToWait); bool conditionIsViolated = true; try { while (conditionIsViolated) { Thread.Sleep(intervalMillis); conditionIsViolated = !condition.call(); } } catch (InterruptedException) { } catch (Exception e) { throw new ProcessEngineException("Exception while waiting on condition: " + e.Message, e); } finally { timer.cancel(); } if (conditionIsViolated) { throw new ProcessEngineException("time limit of " + maxMillisToWait + " was exceeded"); } } finally { jobExecutor.shutdown(); } }
static void CallFunction(Callable callable, Vm vm, int numArgs, bool saveReturnAddress, bool inApply) { if (callable.Arity != null) { // FIXME: Find out why/when the arity can be null. if (callable.HasCollectParams) { if (callable.Arity.Value <= numArgs) { var extraArgs = numArgs - callable.Arity.Value; var values = new ArrayInstance(); for (int i = 0; i < extraArgs; i++) { values.Add(vm.stack.Storage[i + vm.stack.Count - extraArgs]); } vm.stack.PopMany(extraArgs); vm.stack.Push(Value.Make(values)); } else { ArityError(vm, callable.Arity.Value, numArgs, inApply); } } else if (callable.Arity.Value != numArgs) { ArityError(vm, callable.Arity.Value, numArgs, inApply); } } if (saveReturnAddress) { vm.stack.Push (Value.Make (new ReturnAddress () { ProgramCounter = vm.programCounter + 1, Environment = vm.currentEnvironment })); } vm.currentEnvironment = callable.Environment; vm.programCounter = callable.ProgramCounter.Value; }
public RunStateRecordedFutureTask(Callable callable) : base(callable) { }
static void HandleFn(Vm vm) { var instruction = vm.CurrentInstruction (); var args = (int[])instruction.Arguments; var arity = args[1]; var hasCollectParameters = arity >= Callable.CollectParamsArityModifier; if (hasCollectParameters) { arity -= Callable.CollectParamsArityModifier; } var callable = new Callable () { ProgramCounter = args[0], Arity = arity, HasCollectParams = hasCollectParameters, Environment = vm.currentEnvironment }; vm.stack.Push (Value.Make (callable)); vm.IncrementCells (5); vm.programCounter++; }
private void SingleUpdate() { Callable.Call(OnUpdate, gameObject); }
public static object CallSpecial(Context cx, Callable fun, Scriptable thisObj, object[] args, Scriptable scope, Scriptable callerThis, int callType, string filename, int lineNumber) { if (callType == Node.SPECIALCALL_EVAL) { if (thisObj.GetParentScope() == null && NativeGlobal.IsEvalFunction(fun)) { return EvalSpecial(cx, scope, callerThis, args, filename, lineNumber); } } else { if (callType == Node.SPECIALCALL_WITH) { if (NativeWith.IsWithFunction(fun)) { throw Context.ReportRuntimeError1("msg.only.from.new", "With"); } } else { throw Kit.CodeBug(); } } return fun.Call(cx, scope, thisObj, args); }
public override void Execute(GameObject instigator = null) { int value; switch (ValueSource) { default: case ValueSourceType.Property: value = Value; break; case ValueSourceType.GlobalVariable: if (Globals.HasInt(GlobalVariableName, GlobalScope)) { value = Globals.GetInt(GlobalVariableName, GlobalScope); } else { Debug.LogWarning($"CounterLogic ({name}) : Could not find Global integer {GlobalVariableName}({GlobalScope})"); value = 0; } break; case ValueSourceType.GameSave: var gsm = Manager.Get <GameSaveManager>(); if (gsm.HasInt(GameSaveVariableName, GameSaveLocation)) { value = gsm.GetInt(GameSaveVariableName, GameSaveLocation); } else { Debug.LogWarning($"CounterLogic ({name}) : Could not find Game Save integer {GameSaveVariableName}({GameSaveLocation})"); value = 0; } break; } bool test = false; switch (evaluation) { case Evaluation.Equal: test = Counter.CurrentValue == value; break; case Evaluation.NotEqual: test = Counter.CurrentValue != value; break; case Evaluation.Greater: test = Counter.CurrentValue > value; break; case Evaluation.GreaterOrEqual: test = Counter.CurrentValue >= value; break; case Evaluation.Less: test = Counter.CurrentValue < value; break; case Evaluation.LessOrEqual: test = Counter.CurrentValue <= value; break; default: break; } if (test) { Callable.Call(OnTestSuccess, instigator); } else { Callable.Call(OnTestFail, instigator); } }
internal NoSuchMethodShim(Callable noSuchMethodMethod, string methodName) { this.noSuchMethodMethod = noSuchMethodMethod; this.methodName = methodName; }
public static void AddBuiltins(CodeContext cc, Type builtinstype) { BuiltinMethod.binder = binder; BuiltinMethod.context = cc; Dictionary <string, List <MethodBase> > cpsfree = new Dictionary <string, List <MethodBase> >(); Dictionary <string, bool> foldable = new Dictionary <string, bool>(); foreach (MethodInfo mi in builtinstype.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static)) { foreach (BuiltinAttribute ba in mi.GetCustomAttributes(typeof(BuiltinAttribute), false)) { if (CheckParams(mi)) { string name = ba.Name ?? mi.Name.ToLower(); List <MethodBase> meths; foldable[name] = ba.AllowConstantFold; if (!cpsfree.TryGetValue(name, out meths)) { cpsfree[name] = meths = new List <MethodBase>(); } meths.Add(mi); } else { throw new NotSupportedException("all arguments must be of type object, method: " + mi); } } } foreach (string mn in cpsfree.Keys) { object s = SymbolTable.StringToObject(mn); var targets = cpsfree[mn].ToArray(); var paramcounts = new int[targets.Length]; var fold = foldable[mn]; if (AllIsSimple(targets, paramcounts)) { Callable c = null; if (targets.Length == 1) { var dt = CallTargets.GetTargetType(false, paramcounts[0], false); var d = Delegate.CreateDelegate(dt, targets[0] as MethodInfo); c = Closure.Create(d, paramcounts[0]); } else { var d = new Delegate[targets.Length]; for (int i = 0; i < d.Length; i++) { var dt = CallTargets.GetTargetType(false, paramcounts[i], false); d[i] = Delegate.CreateDelegate(dt, targets[i] as MethodInfo); } c = Closure.CreateCase(d, paramcounts); } c.AllowConstantFold = fold; cc.Scope.SetName((SymbolId)s, c); } else { cc.Scope.SetName((SymbolId)s, new BuiltinMethod(mn, targets, fold)); } } }
int SerializeCallable(Callable callable, object obj) { var composite = new Composite { Kind = ObjectTypes.Callable, Elements = new int[5] }; var result = SerializeOneHashed (composite, obj); composite.Elements [0] = SerializeOneHashed (callable.UdpName); composite.Elements [1] = SerializeOneHashed (callable.Prim0Name); composite.Elements [2] = SerializeOne (callable.Arity); composite.Elements [3] = SerializeOne (callable.ProgramCounter); composite.Elements [4] = Serialize (callable.Environment); return result; }
/// <summary>Call function that may pause execution by capturing a continuation.</summary> /// <remarks> /// Call function that may pause execution by capturing a continuation. /// Caller must be prepared to catch a ContinuationPending exception /// and resume execution by calling /// <see cref="ResumeContinuation(object, Scriptable, object)">ResumeContinuation(object, Scriptable, object)</see> /// . /// </remarks> /// <param name="function"> /// The function to call. The function must have been /// compiled with interpreted mode (optimization level -1) /// </param> /// <param name="scope">The scope to execute the script against</param> /// <param name="args">The arguments for the function</param> /// <exception cref="ContinuationPending"> /// if the script calls a function that results /// in a call to /// <see cref="CaptureContinuation()">CaptureContinuation()</see> /// </exception> /// <since>1.7 Release 2</since> /// <exception cref="Rhino.ContinuationPending"></exception> public virtual object CallFunctionWithContinuations(Callable function, Scriptable scope, object[] args) { if (!(function is InterpretedFunction)) { // Can only be applied to scripts throw new ArgumentException("Function argument was not" + " created by interpreted mode "); } if (ScriptRuntime.HasTopCall(this)) { throw new InvalidOperationException("Cannot have any pending top " + "calls when executing a script with continuations"); } // Annotate so we can check later to ensure no java code in // intervening frames isContinuationsTopCall = true; return ScriptRuntime.DoTopCall(function, this, scope, scope, args); }
public ItemBuilder(DynamicMetaObject/*!*/[]/*!*/ types, Callable/*!*/ callable) : base(types, callable) { }
private void Inject(int beforeRpcNumber, Callable <Void> injectedCode) { injections[beforeRpcNumber] = injectedCode; }