public Thread NewThread (Runnable r) { Thread t = new Thread (r); t.SetDaemon (true); t.Start (); return t; }
//================================================================ //Getter and Setter //================================================================ //================================================================ //Methodes //================================================================ public void post(Runnable run) { if (run != null) { runnables.Add(run); } }
public Sharpen.Thread NewThread(Runnable taskBody) { Sharpen.Thread thr = this.baseFactory.NewThread(taskBody); thr.SetName("JGit-AlarmQueue"); thr.SetDaemon(true); return thr; }
public SharpenThread NewThread (Runnable r) { SharpenThread t = new SharpenThread (r); t.SetDaemon (true); t.Start (); return t; }
private schedule(Runnable task, long delay, TimeUnit unit) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); InternalFutureTask<void> futureTask = new InternalFutureTask<void>(new FutureTask<void>(task, null)); scheduledExecutorService.schedule(futureTask, delay, unit); return futureTask; }
public static Exception tryCatch(Runnable runnable) { try { runnable.run(); return null; } catch (Exception exception) { return exception; } }
private void StartPlayingHandler() { var handler = new Handler(); var runnable = new Runnable(() => { handler.Post(OnPlaying); }); if (!_executorService.IsShutdown) { _scheduledFuture = _executorService.ScheduleAtFixedRate(runnable, 100, 1000, TimeUnit.Milliseconds); } }
public ClassRoadie(RunNotifier notifier, TestClass testClass, Description description, Runnable runnable) { base.\u002Ector(); ClassRoadie classRoadie = this; this.fNotifier = notifier; this.fTestClass = testClass; this.fDescription = description; this.fRunnable = runnable; }
public void RemoveItem(Runnable Item) { for (int i = Item.ExecutionIndex; i < (Count - 1); i++) { Items[i] = Items[i + 1]; Items[i].ExecutionIndex = i; } Count--; }
public void AddItem(Runnable Item) { if ((Items.Length - Count) < 10) IncreaseItemsSize(); var index = ++Count - 1; Items[index] = Item; Items[index].ExecutionIndex = index; Compiler.OutItem(Item, this); }
private scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); //JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET: //ORIGINAL LINE: java.util.concurrent.ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, unit); ScheduledFuture < ? > scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, unit); return new InternalScheduledFutureTask(this, scheduledFuture); }
Thread (Runnable runnable, ThreadGroup grp, string name) { thread = new System.Threading.Thread (new ThreadStart (InternalRun)); this.runnable = runnable ?? this; tgroup = grp ?? defaultGroup; tgroup.Add (this); if (name != null) thread.Name = name; }
public static void enqueueFrame(Runnable frame) { lock(frameQueue){ if (frameQueue.Count > MAX_BUFFER){ frameQueue.Dequeue(); } frameQueue.Enqueue(frame); Debug.Log("largo de la cola de los frames = " + frameQueue.Count); } }
public int Execute() { string[] tokens = configuration.GetItem<Settings>().Runner.Split(','); if (tokens.Length > 1) { configuration.GetItem<ApplicationUnderTest>().AddAssembly(tokens[1]); } Runnable = new BasicProcessor().Create(tokens[0]).GetValue<Runnable>(); ExecuteInApartment(); return result; }
Thread (Runnable runnable, ThreadGroup grp, string name) { cancelTokenSource = new CancellationTokenSource (); task = new Task (InternalRun, cancelTokenSource.Token, TaskCreationOptions.LongRunning); Runnable = runnable ?? this; tgroup = grp ?? defaultGroup; tgroup.Add (this); Name = name ?? "Unknown"; }
// An Executor that can be used to execute tasks in parallel. // An Executor that executes tasks one at a time in serial order. This // serialization is global to a particular process. public virtual void Execute(Runnable r) { lock (this) { mTasks.Offer(new _Runnable_58(this, r)); if (mActive == null) { ScheduleNext(); } } }
private void PostQueue(Runnable runnable) { lock (mQueue) { mQueue.Enqueue(runnable); } if (!IsNotify) { IsNotify = true; Task task = new Task(Run); task.Start(); } }
/** * Submit a runnable task to the executor. */ public void Submit(Runnable task) { Logger.Trace("Submit(task={})", task); // Synchronise on the queue lock... lock(queueLock) { // Sanity check before adding the task if(!shutdownRequested) { // Enqueue the new runnable task queue.Enqueue(task); // Fire a notification to the synchronisation object to notify any waiters Logger.Trace("Notify queue of new task..."); Monitor.Pulse(queueLock); Logger.Trace("...notified queue of new task."); } else { throw new InvalidOperationException("Can not submit a task when the queue has been shut down"); } } }
internal void InternalExecute (Runnable r, bool checkShutdown) { lock (pendingTasks) { if (shutdown && checkShutdown) throw new InvalidOperationException (); if (runningThreads < corePoolSize) { StartPoolThread (); } else if (freeThreads > 0) { freeThreads--; } else if (runningThreads < maxPoolSize) { StartPoolThread (); } pendingTasks.Enqueue (r); ST.Monitor.PulseAll (pendingTasks); } }
protected static void CheckException(Runnable callbk, string name, string msg) { try { callbk(); LogMessage(msg + ": CheckException failure: no exception detected"); Environment.Exit(1); } catch(Exception e) { if(!e.GetType().Name.Equals(name)) { LogMessage(msg + ": CheckException failure: wrong exception type"); LogMessage("Expected: " + name); LogMessage("Actual: " + e.GetType().Name); Environment.Exit(1); } } }
protected static void Benchmark(Runnable callbk, string name, int iterations) { // java System.currentTimeMillis() (returning long) for timing int start = Environment.TickCount; // millis since system was started for(int i = 0; i < iterations; ++i) { callbk(); } int end = Environment.TickCount; double time = (end - start)/1000.0; Console.Error.WriteLine( "Benchmark: {0}, {1} iterations ran in {2} seconds", name, iterations, time.ToString("0.000") ); }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); m_ConfigurationJsonPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/Discovery/exampleConfigurationData.json"; m_FilePathToIngest = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; m_DocumentFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; #region Get Environments and Add Environment // Get Environments Log.Debug("ExampleDiscoveryV1", "Attempting to get environments"); if (!m_Discovery.GetEnvironments((GetEnvironmentsResponse resp, string data) => { if (resp != null) { foreach (Environment environment in resp.environments) { Log.Debug("ExampleDiscoveryV1", "environment_id: {0}", environment.environment_id); } } else { Log.Debug("ExampleDiscoveryV1", "Discovery.GetEnvironments(); resp is null"); } Test(resp.environments != null); m_GetEnvironmentsTested = true; })) { Log.Debug("ExampleDiscoveryV1", "Failed to get environments"); } while (!m_GetEnvironmentsTested) { yield return(null); } // Add Environment Log.Debug("ExampleDiscoveryV1", "Attempting to add environment"); if (!m_Discovery.AddEnvironment((Environment resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Added {0}", resp.environment_id); m_CreatedEnvironmentID = resp.environment_id; } else { Log.Debug("ExampleDiscoveryV1", "Discovery.AddEnvironment(); resp is null, {0}", data); } Test(!string.IsNullOrEmpty(resp.environment_id)); m_AddEnvironmentsTested = true; }, m_CreatedEnvironmentName, m_CreatedEnvironmentDescription, 0)) { Log.Debug("ExampleDiscoveryV1", "Failed to add environment"); } while (!m_AddEnvironmentsTested) { yield return(null); } // Check for active environment Runnable.Run(CheckEnvironmentStatus()); while (!m_IsEnvironmentActive) { yield return(null); } #endregion #region Get Configurations and add Configuration // Get Configurations Log.Debug("ExampleDiscoveryV1", "Attempting to get configurations"); if (!m_Discovery.GetConfigurations((GetConfigurationsResponse resp, string data) => { if (resp != null) { if (resp.configurations != null && resp.configurations.Length > 0) { foreach (ConfigurationRef configuration in resp.configurations) { Log.Debug("ExampleDiscoveryV1", "Configuration: {0}, {1}", configuration.configuration_id, configuration.name); } } else { Log.Debug("ExampleDiscoveryV1", "There are no configurations for this environment."); } } else { Log.Debug("ExampleDiscoveryV1", "Discovery.GetConfigurations(); resp is null, {0}", data); } Test(resp.configurations != null); m_GetConfigurationsTested = true; }, m_CreatedEnvironmentID)) { Log.Debug("ExampleDiscoveryV1", "Failed to get configurations"); } while (!m_GetConfigurationsTested) { yield return(null); } // Add Configuration Log.Debug("ExampleDiscoveryV1", "Attempting to add configuration"); if (!m_Discovery.AddConfiguration((Configuration resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Configuration: {0}, {1}", resp.configuration_id, resp.name); m_CreatedConfigurationID = resp.configuration_id; } else { Log.Debug("ExampleDiscoveryV1", "Discovery.AddConfiguration(); resp is null, {0}", data); } Test(!string.IsNullOrEmpty(resp.configuration_id)); m_AddConfigurationTested = true; }, m_CreatedEnvironmentID, m_ConfigurationJsonPath)) { Log.Debug("ExampleDiscoveryV1", "Failed to add configuration"); } while (!m_AddConfigurationTested) { yield return(null); } #endregion #region GetCollections and Add Collection // Get Collections Log.Debug("ExampleDiscoveryV1", "Attempting to get collections"); if (!m_Discovery.GetCollections((GetCollectionsResponse resp, string customData) => { if (resp != null) { if (resp.collections != null && resp.collections.Length > 0) { foreach (CollectionRef collection in resp.collections) { Log.Debug("ExampleDiscoveryV1", "Collection: {0}, {1}", collection.collection_id, collection.name); } } else { Log.Debug("ExampleDiscoveryV1", "There are no collections"); } } else { Log.Debug("ExampleDiscoveryV1", "Discovery.GetCollections(); resp is null"); } Test(resp != null); m_GetCollectionsTested = true; }, m_CreatedEnvironmentID)) { Log.Debug("ExampleDiscovery", "Failed to get collections"); } while (!m_GetCollectionsTested) { yield return(null); } // Add Collection Log.Debug("ExampleDiscoveryV1", "Attempting to add collection"); if (!m_Discovery.AddCollection((CollectionRef resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Collection: {0}, {1}", resp.collection_id, resp.name); m_CreatedCollectionID = resp.collection_id; } else { Log.Debug("ExampleDiscoveryV1", "Discovery.AddCollection(); resp is null, {0}", data); } Test(!string.IsNullOrEmpty(resp.collection_id)); m_AddCollectionTested = true; }, m_CreatedEnvironmentID, m_CreatedCollectionName, m_CreatedCollectionDescription, m_CreatedConfigurationID)) { Log.Debug("ExampleDiscovery", "Failed to add collection"); } while (!m_AddCollectionTested) { yield return(null); } #endregion #region Get Fields Log.Debug("ExampleDiscoveryV1", "Attempting to get fields"); if (!m_Discovery.GetFields((GetFieldsResponse resp, string customData) => { if (resp != null) { foreach (Field field in resp.fields) { Log.Debug("ExampleDiscoveryV1", "Field: {0}, type: {1}", field.field, field.type); } } else { Log.Debug("ExampleDiscoveryV1", "Discovery.GetFields(); resp is null"); } Test(resp != null); m_GetFieldsTested = true; }, m_CreatedEnvironmentID, m_CreatedCollectionID)) { Log.Debug("ExampleDiscoveryV1", "Failed to get fields"); } while (!m_GetFieldsTested) { yield return(null); } #endregion #region Add Document // Add Document Log.Debug("ExampleDiscoveryV1", "Attempting to add document"); if (!m_Discovery.AddDocument((DocumentAccepted resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Added Document {0} {1}", resp.document_id, resp.status); m_CreatedDocumentID = resp.document_id; } else { Log.Debug("ExampleDiscoveryV1", "Discovery.AddDocument(); resp is null, {0}", data); } Test(!string.IsNullOrEmpty(resp.document_id)); m_AddDocumentTested = true; }, m_CreatedEnvironmentID, m_CreatedCollectionID, m_DocumentFilePath, m_CreatedConfigurationID, null)) { Log.Debug("ExampleDiscovery", "Failed to add document"); } while (!m_AddDocumentTested) { yield return(null); } #endregion #region Query // Query Log.Debug("ExampleDiscoveryV1", "Attempting to query"); if (!m_Discovery.Query((QueryResponse resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", resp.ToString()); } else { Log.Debug("ExampleDiscoveryV1", "resp is null, {0}", data); } Test(resp != null); m_QueryTested = true; }, m_CreatedEnvironmentID, m_CreatedCollectionID, null, m_Query, null, 10, null, 0)) { Log.Debug("ExampleDiscovery", "Failed to query"); } while (!m_QueryTested) { yield return(null); } #endregion #region Document // Get Document Log.Debug("ExampleDiscoveryV1", "Attempting to get document"); if (!m_Discovery.GetDocument((DocumentStatus resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Got Document {0} {1}", resp.document_id, resp.status); } else { Log.Debug("ExampleDiscoveryV1", "Discovery.GetDocument(); resp is null, {0}", data); } Test(!string.IsNullOrEmpty(resp.status)); m_GetDocumentTested = true; }, m_CreatedEnvironmentID, m_CreatedCollectionID, m_CreatedDocumentID)) { Log.Debug("ExampleDiscovery", "Failed to get document"); } while (!m_GetDocumentTested) { yield return(null); } // Update Document Log.Debug("ExampleDiscoveryV1", "Attempting to update document"); if (!m_Discovery.UpdateDocument((DocumentAccepted resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Updated Document {0} {1}", resp.document_id, resp.status); } else { Log.Debug("ExampleDiscoveryV1", "Discovery.UpdateDocument(); resp is null, {0}", data); } Test(!string.IsNullOrEmpty(resp.status)); m_UpdateDocumentTested = true; }, m_CreatedEnvironmentID, m_CreatedCollectionID, m_CreatedDocumentID, m_DocumentFilePath, m_CreatedConfigurationID, null)) { Log.Debug("ExampleDiscovery", "Failed to update document"); } while (!m_UpdateDocumentTested) { yield return(null); } // Delete Document Runnable.Run(DeleteDocument()); while (!m_DeleteDocumentTested) { yield return(null); } #endregion #region Collection // Get Collection Log.Debug("ExampleDiscoveryV1", "Attempting to get collection"); if (!m_Discovery.GetCollection((Collection resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Collection: {0}, {1}", resp.collection_id, resp.name); } else { Log.Debug("ExampleDiscoveryV1", "Failed to get collections"); } Test(!string.IsNullOrEmpty(resp.name)); m_GetCollectionTested = true; }, m_CreatedEnvironmentID, m_CreatedCollectionID)) { Log.Debug("ExampleDiscovery", "Failed to get collection"); } while (!m_GetCollectionTested) { yield return(null); } // Delete Collection Runnable.Run(DeleteCollection()); while (!m_DeleteCollectionTested) { yield return(null); } #endregion #region Configuration // Get Configuration Log.Debug("ExampleDiscoveryV1", "Attempting to get configuration"); if (!m_Discovery.GetConfiguration((Configuration resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Configuration: {0}, {1}", resp.configuration_id, resp.name); } else { Log.Debug("ExampleDiscoveryV1", "Discovery.GetConfiguration(); resp is null, {0}", data); } Test(!string.IsNullOrEmpty(resp.name)); m_GetConfigurationTested = true; }, m_CreatedEnvironmentID, m_CreatedConfigurationID)) { Log.Debug("ExampleDiscoveryV1", "Failed to get configuration"); } while (!m_GetConfigurationTested) { yield return(null); } // Preview Configuration Log.Debug("ExampleDiscoveryV1", "Attempting to preview configuration"); if (!m_Discovery.PreviewConfiguration((TestDocument resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "Preview succeeded: {0}", resp.status); } else { Log.Debug("ExampleDiscoveryV1", "Discovery.PreviewConfiguration(); resp is null {0}", data); } Test(resp != null); m_PreviewConfigurationTested = true; }, m_CreatedEnvironmentID, m_CreatedConfigurationID, null, m_FilePathToIngest, m_Metadata)) { Log.Debug("ExampleDiscoveryV1", "Failed to preview configuration"); } while (!m_PreviewConfigurationTested) { yield return(null); } // Delete Configuration Runnable.Run(DeleteConfiguration()); while (!m_DeleteConfigurationTested) { yield return(null); } #endregion #region Environment // Get Environment Log.Debug("ExampleDiscoveryV1", "Attempting to get environment"); if (!m_Discovery.GetEnvironment((Environment resp, string data) => { if (resp != null) { Log.Debug("ExampleDiscoveryV1", "environment_name: {0}", resp.name); } else { Log.Debug("ExampleDiscoveryV1", "Discovery.GetEnvironment(); resp is null"); } Test(!string.IsNullOrEmpty(resp.name)); m_GetEnvironmentTested = true; }, m_CreatedEnvironmentID)) { Log.Debug("ExampleDiscoveryV1", "Failed to get environment"); } while (!m_GetEnvironmentTested) { yield return(null); } // Delete Environment Runnable.Run(DeleteEnvironment()); while (!m_DeleteEnvironmentTested) { yield return(null); } #endregion yield break; }
public void DictateTutorial() { Runnable.Run(ExampleSynthesize(textInput.text)); }
void Start() { textToSpeech = new CustomTTS(); LogSystem.InstallDefaultReactors(); Runnable.Run(CreateService()); }
// Start is called before the first frame update void Start() { LogSystem.InstallDefaultReactors(); Runnable.Run(CreateService()); }
// // Marker related listeners. // public bool OnMarkerClick(Marker marker) { // This causes the marker at Perth to bounce into position when it is clicked. if (marker.Equals(mPerth)) { Handler handler = new Handler (); long start = SystemClock.UptimeMillis (); Projection proj = mMap.Projection; Point startPoint = proj.ToScreenLocation(PERTH); startPoint.Offset(0, -100); LatLng startLatLng = proj.FromScreenLocation(startPoint); long duration = 1500; IInterpolator interpolator = new BounceInterpolator(); Runnable run = null; run = new Runnable (delegate { long elapsed = SystemClock.UptimeMillis () - start; float t = interpolator.GetInterpolation ((float) elapsed / duration); double lng = t * PERTH.Longitude + (1 - t) * startLatLng.Longitude; double lat = t * PERTH.Latitude + (1 - t) * startLatLng.Latitude; marker.Position = (new LatLng(lat, lng)); if (t < 1.0) { // Post again 16ms later. handler.PostDelayed(run, 16); } }); handler.Post(run); } // We return false to indicate that we have not consumed the event and that we wish // for the default behavior to occur (which is for the camera to move such that the // marker is centered and for the marker's info window to open, if it has one). return false; }
public Call(Runnable fn) { tmp = new ArrayList(); fun = fn; }
public abstract void Execute(Runnable runable);
void Start() { LogSystem.InstallDefaultReactors(); Runnable.Run(GetCredentials()); }
public void Run(Runnable operation, OperationContext context) { Launch(AsyncBasedBackgroundTasks.PerformRun, context, operation); }
private void lvDebug_BS_ItemActivate(object sender, EventArgs e) { var fs = _ps.FunctionStack; if (lvDebug_FS.SelectedItems.Count > 0) { fs = (FunctionStackFrame)lvDebug_FS.SelectedItems[0].Tag; } if (fs == null) { lvDebug_Runnables.Items.Clear(); lvDebug_Runnables.Tag = null; return; } var bs = fs.BlockStack; if (lvDebug_BS.SelectedItems.Count > 0) { bs = (BlockStackFrame)lvDebug_BS.SelectedItems[0].Tag; } if (bs == null) { lvDebug_Runnables.Items.Clear(); lvDebug_Runnables.Tag = null; return; } //Fill block info dgvDebug_Block.Rows.Add("Success", fs.Success.ToString()); dgvDebug_Block.Rows.Add("Quantifier", string.Format("{0}:{1}", bs.Quantifier, bs.Quantifier.Count)); var s = fs.Result.ToString(); dgvDebug_Block.Rows.Add("Result", string.Format("{0}({1}):{2}", fs.Result.Type.ToString(), s.Length, (s.Length <= 50) ? s : s.Substring(0, 50))); s = bs.Source.ToString(); dgvDebug_Block.Rows.Add("Source", string.Format("({0}):{1}", s.Length, (s.Length <= 50) ? s : s.Substring(0, 50))); s = bs.Source /*NextSource*/.ToString(); dgvDebug_Block.Rows.Add("NextSource", string.Format("({0}):{1}", s.Length, (s.Length <= 50) ? s : s.Substring(0, 50))); s = bs.Skipped.ToString(); dgvDebug_Block.Rows.Add("Skipped", string.Format("{0}:{1}", s.Length, s)); var bl = bs.Block; Runnable rn = null; if ((bs.NextItem >= 0) && (bs.NextItem < bl.Items.Length)) { rn = bl.Items[bs.NextItem].OnFailJumpTo; } if (lvDebug_Runnables.Tag != bl) { lvDebug_Runnables.Tag = null; lvDebug_Runnables.Items.Clear(); } for (var i = 0; i < bl.Items.Length; i++) { var it = bl.Items[i]; ListViewItem lvi; if (bs.Block != lvDebug_Runnables.Tag) { lvi = lvDebug_Runnables.Items.Add(it.Description.ToString()); lvi.Tag = it.Annotation; it.Annotation.FirstRunnable.Annotation.ListViewItem = lvi; } else { lvi = lvDebug_Runnables.Items[i]; } lvi.ImageIndex = (bs.NextItem == i) ? 0 : (((rn != null) && (rn.ExecutionIndex == i)) ? 1 : -1); if (lvi.ImageIndex == 0) { lvi.EnsureVisible(); } lvi.BackColor = it.BreakPoint ? Color.Gold : Color.White; } lvDebug_Runnables.Tag = bs.Block; }
public Future <object> Schedule(Runnable r, long delay, TimeUnit unit) { return(Schedule <object> (r, delay, unit)); }
public void Test_Type_Insert_Select() { Runnable drop1 = new Runnable(); Runnable drop2 = new Runnable(); Runnable create1 = new Runnable(); Runnable create2 = new Runnable(); drop1.Sql(@" BEGIN EXECUTE IMMEDIATE 'DROP TABLE ""jerry_types""'; EXCEPTION WHEN OTHERS THEN NULL; END;"); drop2.Sql(@" BEGIN EXECUTE IMMEDIATE 'DROP TABLE ""jerry_types2""'; EXCEPTION WHEN OTHERS THEN NULL; END;"); create1.Sql(@" CREATE TABLE ""jerry_types""( ""Char"" char(20) NOT NULL, ""VarChar"" varchar(20) NOT NULL, ""VarChar2"" varchar2(20) NOT NULL, ""Clob"" clob NOT NULL, ""NClob"" nclob NOT NULL, ""NChar"" nchar(20) NOT NULL, ""NVarChar2"" nvarchar2(20) NOT NULL, ""Long"" long NOT NULL, ""Date"" date NOT NULL, ""Number"" number NOT NULL, ""Blob"" blob NOT NULL, ""Raw"" raw(20) NOT NULL, ""TimeStamp"" timestamp NOT NULL, ""TimeStampTz"" timestamp with time zone NOT NULL, ""TimeStampLz"" timestamp with local time zone NOT NULL, ""IntervalDS"" interval day to second NOT NULL )"); create2.Sql(@" CREATE TABLE ""jerry_types2""( ""LongRaw"" long raw NOT NULL )"); Runner.Command(drop1); Runner.Command(drop2); Runner.Command(create1); Runner.Command(create2); Runnable <TypeModel, object> insert1 = new Runnable <TypeModel, object>(TypeModel.GetSample()); Runnable <TypeModel2, object> insert2 = new Runnable <TypeModel2, object>(TypeModel2.GetSample()); insert1.Sql(@"INSERT INTO ""jerry_types"" ( "); insert1.M(p => p.ColNames()); insert1.Sql(" ) VALUES ( "); insert1.M(p => p.Pars()); insert1.Sql(")"); insert2.Sql(@"INSERT INTO ""jerry_types2"" ( "); insert2.M(p => p.ColNames()); insert2.Sql(" ) VALUES ( "); insert2.M(p => p.Pars()); insert2.Sql(")"); Runner.Command(insert1); Runner.Command(insert2); Runnable <object, TypeModel> select1 = new Runnable <object, TypeModel>(); Runnable <object, TypeModel2> select2 = new Runnable <object, TypeModel2>(); select1.Sql("SELECT "); select1.R(p => p.Star()); select1.Sql(@" FROM ""jerry_types"" "); select1.R(p => p.Ali()); select2.Sql("SELECT "); select2.R(p => p.Star()); select2.Sql(@" FROM ""jerry_types2"" "); select2.R(p => p.Ali()); TypeModel sample1 = TypeModel.GetSample(); TypeModel2 sample2 = TypeModel2.GetSample(); TypeModel fromDb1 = Runner.Query(select1).FirstOrDefault(); TypeModel2 fromDb2 = Runner.Query(select2).FirstOrDefault(); this.CompareTypeModels(fromDb1, sample1); this.CompareTypeModels(fromDb2, sample2); TypeModel fromDb3 = new TypeModel(); TypeModel2 fromDb4 = new TypeModel2(); Runnable <TypeModel, object> bind1 = new Runnable <TypeModel, object>(fromDb3); Runnable <TypeModel2, object> bind2 = new Runnable <TypeModel2, object>(fromDb4); bind1.Sql("SELECT "); bind1.M(p => p.Cols().As().Props()); bind1.Sql(@" FROM ""jerry_types"" "); bind1.M(p => p.Ali()); bind2.Sql("SELECT "); bind2.M(p => p.Cols().As().Props()); bind2.Sql(@" FROM ""jerry_types2"" "); bind2.M(p => p.Ali()); Runner.Command(bind1); Runner.Command(bind2); this.CompareTypeModels(fromDb3, sample1); this.CompareTypeModels(fromDb4, sample2); }
public void PostHandler(Runnable runnable) { this.m_handler.Post(runnable); }
/* public void finalize() throws Throwable{ disconnect(); jsch=null; } */ public void disconnect() { if(!_isConnected) return; //System.Console.WriteLine(this+": disconnect"); //Thread.dumpStack(); /* for(int i=0; i<Channel.pool.size(); i++){ try{ Channel c=((Channel)(Channel.pool.elementAt(i))); if(c.session==this) c.eof(); } catch(Exception e){ } } */ Channel.disconnect(this); _isConnected=false; PortWatcher.delPort(this); ChannelForwardedTCPIP.delPort(this); lock(connectThread) { connectThread.yield(); connectThread.interrupt(); connectThread=null; } thread=null; try { if(io!=null) { if(io.ins!=null) io.ins.Close(); if(io.outs!=null) io.outs.Close(); if(io.outs_ext!=null) io.outs_ext.Close(); } if(proxy==null) { if(socket!=null) socket.close(); } else { lock(proxy) { proxy.close(); } proxy=null; } } catch(Exception e) { // e.printStackTrace(); } io=null; socket=null; // lock(jsch.pool){ // jsch.pool.removeElement(this); // } jsch.removeSession(this); //System.gc(); }
public If(Runnable a, Runnable b) { i = a; t = b; f = null; }
internal void delete() { thread=null; try { if(ss!=null)ss.close(); ss=null; } catch(Exception e) { } }
public If(Runnable a, Runnable b, Runnable c) { i = a; t = b; f = c; }
public Block(Runnable compoundStatment) { this.compoundStatment = compoundStatment; }
public AssignVar(string name, Runnable code) { variableName = name; this.code = code; }
public Sharpen.Thread NewThread(Runnable r) { Sharpen.Thread thread = new Sharpen.Thread(r); thread.SetContextClassLoader(this._enclosing.jobClassLoader); return(thread); }
public RunnableFuture <T> newTaskFor <T>(Runnable runnable, T value) { return(new FutureTask <T>(runnable, value)); }
public override void runPendingAnimations() { bool removalsPending = mPendingRemovals.Count > 0; bool movesPending = mPendingMoves.Count > 0; bool changesPending = mPendingChanges.Count > 0; bool additionsPending = mPendingAdditions.Count > 0; if (!removalsPending && !movesPending && !additionsPending && !changesPending) { // nothing to animate return; } // First, remove stuff foreach (RecyclerView.ViewHolder holder in mPendingRemovals) { animateRemoveImpl(holder); } mPendingRemovals.Clear(); // Next, move stuff if (movesPending) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.ArrayList<MoveInfo> moves = new java.util.ArrayList<MoveInfo>(); List <MoveInfo> moves = new List <MoveInfo>(); moves.AddRange(mPendingMoves); mMovesList.Add(moves); mPendingMoves.Clear(); Runnable mover = () => { foreach (MoveInfo moveInfo in moves) { animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, moveInfo.toX, moveInfo.toY); } moves.Clear(); mMovesList.Remove(moves); }; if (removalsPending) { View view = moves[0].holder.itemView; ViewCompat.postOnAnimationDelayed(view, mover, RemoveDuration); } else { mover.run(); } } // Next, change stuff, to run in parallel with move animations if (changesPending) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.ArrayList<ChangeInfo> changes = new java.util.ArrayList<ChangeInfo>(); List <ChangeInfo> changes = new List <ChangeInfo>(); changes.AddRange(mPendingChanges); mChangesList.Add(changes); mPendingChanges.Clear(); Runnable changer = () => { foreach (ChangeInfo change in changes) { animateChangeImpl(change); } changes.Clear(); mChangesList.Remove(changes); }; if (removalsPending) { RecyclerView.ViewHolder holder = changes[0].oldHolder; ViewCompat.postOnAnimationDelayed(holder.itemView, changer, RemoveDuration); } else { changer.run(); } } // Next, add stuff if (additionsPending) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.ArrayList<android.support.v7.widget.RecyclerView.ViewHolder> additions = new java.util.ArrayList<android.support.v7.widget.RecyclerView.ViewHolder>(); List <RecyclerView.ViewHolder> additions = new List <RecyclerView.ViewHolder>(); additions.AddRange(mPendingAdditions); mAdditionsList.Add(additions); mPendingAdditions.Clear(); Runnable adder = () => { foreach (RecyclerView.ViewHolder holder in additions) { animateAddImpl(holder); } additions.Clear(); mAdditionsList.Remove(additions); }; if (removalsPending || movesPending || changesPending) { long removeDuration = removalsPending ? RemoveDuration : 0; long moveDuration = movesPending ? MoveDuration : 0; long changeDuration = changesPending ? ChangeDuration : 0; long totalDelay = removeDuration + Math.Max(moveDuration, changeDuration); View view = additions[0].itemView; ViewCompat.postOnAnimationDelayed(view, adder, totalDelay); } else { adder.run(); } } }
public Thread(Runnable runnable) : this(runnable, null, null) { }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); _testClusterConfigName = "cranfield_solr_config"; _testClusterConfigPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/cranfield_solr_config.zip"; _testRankerTrainingPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/ranker_training_data.csv"; _testAnswerDataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/ranker_answer_data.csv"; _indexDataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/cranfield_data.json"; _testQuery = "What is the basic mechanisim of the transonic aileron buzz"; _collectionNameToDelete = "TestCollectionToDelete"; _createdRankerName = "RankerToDelete"; VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["retrieve_and_rank"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _retrieveAndRank = new RetrieveAndRank(credentials); // Get clusters Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get clusters."); if (!_retrieveAndRank.GetClusters(OnGetClusters, OnFail)) { Log.Debug("TestRetrieveAndRank.GetClusters()", "Failed to get clusters!"); } while (!_getClustersTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Create cluster Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to create cluster."); if (!_retrieveAndRank.CreateCluster(OnCreateCluster, OnFail, "unity-test-cluster", "1")) { Log.Debug("TestRetrieveAndRank.CreateCluster()", "Failed to create cluster!"); } while (!_createClusterTested || !_readyToContinue) { yield return(null); } // Wait for cluster status to be `READY`. Runnable.Run(CheckClusterStatus(10f)); while (!_isClusterReady) { yield return(null); } _readyToContinue = false; // List cluster configs Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get cluster configs."); if (!_retrieveAndRank.GetClusterConfigs(OnGetClusterConfigs, OnFail, _clusterToDelete)) { Log.Debug("TestRetrieveAndRank.GetClusterConfigs()", "Failed to get cluster configs!"); } while (!_getClusterConfigsTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Upload cluster config Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to upload cluster config."); if (!_retrieveAndRank.UploadClusterConfig(OnUploadClusterConfig, OnFail, _clusterToDelete, _testClusterConfigName, _testClusterConfigPath)) { Log.Debug("TestRetrieveAndRank.UploadClusterConfig()", "Failed to upload cluster config {0}!", _testClusterConfigPath); } while (!_uploadClusterConfigTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Get cluster Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get cluster."); if (!_retrieveAndRank.GetCluster(OnGetCluster, OnFail, _clusterToDelete)) { Log.Debug("TestRetrieveAndRank.GetCluster()", "Failed to get cluster!"); } while (!_getClusterTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Get cluster config Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get cluster config."); if (!_retrieveAndRank.GetClusterConfig(OnGetClusterConfig, OnFail, _clusterToDelete, _testClusterConfigName)) { Log.Debug("TestRetrieveAndRank.GetClusterConfig()", "Failed to get cluster config {0}!", _testClusterConfigName); } while (!_getClusterConfigTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // List Collection request Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get collections."); if (!_retrieveAndRank.ForwardCollectionRequest(OnGetCollections, OnFail, _clusterToDelete, CollectionsAction.List)) { Log.Debug("TestRetrieveAndRank.ForwardCollectionRequest()", "Failed to get collections!"); } while (!_getCollectionsTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Create Collection request Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to create collection."); if (!_retrieveAndRank.ForwardCollectionRequest(OnCreateCollection, OnFail, _clusterToDelete, CollectionsAction.Create, _collectionNameToDelete, _testClusterConfigName)) { Log.Debug("TestRetrieveAndRank.ForwardCollectionRequest()", "Failed to create collections!"); } while (!_createCollectionTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Index documents Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to index documents."); if (!_retrieveAndRank.IndexDocuments(OnIndexDocuments, OnFail, _indexDataPath, _clusterToDelete, _collectionNameToDelete)) { Log.Debug("TestRetrieveAndRank.IndexDocuments()", "Failed to index documents!"); } while (!_indexDocumentsTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Get rankers Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get rankers."); if (!_retrieveAndRank.GetRankers(OnGetRankers, OnFail)) { Log.Debug("TestRetrieveAndRank.GetRankers()", "Failed to get rankers!"); } while (!_getRankersTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Create ranker Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to create ranker."); if (!_retrieveAndRank.CreateRanker(OnCreateRanker, OnFail, _testRankerTrainingPath, _createdRankerName)) { Log.Debug("TestRetrieveAndRank.CreateRanker()", "Failed to create ranker!"); } while (!_createRankerTested || !_readyToContinue) { yield return(null); } // Wait for ranker status to be `Available`. Log.Debug("TestRetrieveAndRank.RunTest()", "Checking ranker status in 10 seconds"); Runnable.Run(CheckRankerStatus(10f)); while (!_isRankerReady || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Standard Search string[] fl = { "title", "id", "body", "author", "bibliography" }; Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to search standard."); if (!_retrieveAndRank.Search(OnSearchStandard, OnFail, _clusterToDelete, _collectionNameToDelete, _testQuery, fl)) { Log.Debug("TestRetrieveAndRank.Search()", "Failed to search!"); } while (!_searchStandardTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Rank Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to rank."); if (!_retrieveAndRank.Rank(OnRank, OnFail, _rankerIdToDelete, _testAnswerDataPath)) { Log.Debug("TestRetrieveAndRank.Rank()", "Failed to rank!"); } while (!_rankTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Get ranker info Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to get rankers."); if (!_retrieveAndRank.GetRanker(OnGetRanker, OnFail, _rankerIdToDelete)) { Log.Debug("TestRetrieveAndRank.GetRanker()", "Failed to get ranker!"); } while (!_getRankerTested) { yield return(null); } _readyToContinue = false; // Delete rankers Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to delete ranker {0}.", _rankerIdToDelete); if (!_retrieveAndRank.DeleteRanker(OnDeleteRanker, OnFail, _rankerIdToDelete)) { Log.Debug("TestRetrieveAndRank.DeleteRanker()", "Failed to delete ranker {0}!", _rankerIdToDelete); } while (!_deleteRankerTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete Collection request Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to delete collection {0}.", "TestCollectionToDelete"); if (!_retrieveAndRank.ForwardCollectionRequest(OnDeleteCollection, OnFail, _clusterToDelete, CollectionsAction.Delete, "TestCollectionToDelete")) { Log.Debug("TestRetrieveAndRank.ForwardCollectionRequest()", "Failed to delete collections!"); } while (!_deleteCollectionTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete cluster config string clusterConfigToDelete = "test-config"; Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to delete cluster config."); if (!_retrieveAndRank.DeleteClusterConfig(OnDeleteClusterConfig, OnFail, _clusterToDelete, clusterConfigToDelete)) { Log.Debug("TestRetrieveAndRank.DeleteClusterConfig()", "Failed to delete cluster config {0}", clusterConfigToDelete); } while (!_deleteClusterConfigTested || !_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete cluster Log.Debug("TestRetrieveAndRank.RunTest()", "Attempting to delete cluster {0}.", _clusterToDelete); if (!_retrieveAndRank.DeleteCluster(OnDeleteCluster, OnFail, _clusterToDelete)) { Log.Debug("TestRetrieveAndRank.DeleteCluster()", "Failed to delete cluster!"); } while (!_deleteClusterTested || !_readyToContinue) { yield return(null); } Log.Debug("TestRetrieveAndRank.RunTest()", "Retrieve and rank examples complete!"); yield break; }
private IEnumerator Examples() { // Get Environments Log.Debug("ExampleDiscovery.RunTest()", "Attempting to get environments"); if (!_service.GetEnvironments(OnGetEnvironments, OnFail)) { Log.Debug("ExampleDiscovery.GetEnvironments()", "Failed to get environments"); } while (!_getEnvironmentsTested) { yield return(null); } // Wait for environment to be ready Runnable.Run(CheckEnvironmentState(0f)); while (!_isEnvironmentReady) { yield return(null); } // GetEnvironment Log.Debug("ExampleDiscovery.RunTest()", "Attempting to get environment"); if (!_service.GetEnvironment(OnGetEnvironment, OnFail, _environmentId)) { Log.Debug("ExampleDiscovery.GetEnvironment()", "Failed to get environment"); } while (!_getEnvironmentTested) { yield return(null); } // Get Configurations Log.Debug("ExampleDiscovery.RunTest()", "Attempting to get configurations"); if (!_service.GetConfigurations(OnGetConfigurations, OnFail, _environmentId)) { Log.Debug("ExampleDiscovery.GetConfigurations()", "Failed to get configurations"); } while (!_getConfigurationsTested) { yield return(null); } // Add Configuration Log.Debug("ExampleDiscovery.RunTest()", "Attempting to add configuration"); if (!_service.AddConfiguration(OnAddConfiguration, OnFail, _environmentId, _configurationJson.Replace("{guid}", System.Guid.NewGuid().ToString()))) { Log.Debug("ExampleDiscovery.AddConfiguration()", "Failed to add configuration"); } while (!_addConfigurationTested) { yield return(null); } // Get Configuration Log.Debug("ExampleDiscovery.RunTest()", "Attempting to get configuration"); if (!_service.GetConfiguration(OnGetConfiguration, OnFail, _environmentId, _createdConfigurationId)) { Log.Debug("ExampleDiscovery.GetConfiguration()", "Failed to get configuration"); } while (!_getConfigurationTested) { yield return(null); } // Preview Configuration Log.Debug("ExampleDiscovery.RunTest()", "Attempting to preview configuration"); if (!_service.PreviewConfiguration(OnPreviewConfiguration, OnFail, _environmentId, _createdConfigurationId, null, _filePathToIngest, _metadata)) { Log.Debug("ExampleDiscovery.PreviewConfiguration()", "Failed to preview configuration"); } while (!_previewConfigurationTested) { yield return(null); } // Get Collections Log.Debug("ExampleDiscovery.RunTest()", "Attempting to get collections"); if (!_service.GetCollections(OnGetCollections, OnFail, _environmentId)) { Log.Debug("ExampleDiscovery.GetCollections()", "Failed to get collections"); } while (!_getCollectionsTested) { yield return(null); } // Add Collection Log.Debug("ExampleDiscovery.RunTest()", "Attempting to add collection"); if (!_service.AddCollection(OnAddCollection, OnFail, _environmentId, _createdCollectionName + System.Guid.NewGuid().ToString(), _createdCollectionDescription, _createdConfigurationId)) { Log.Debug("ExampleDiscovery.AddCollection()", "Failed to add collection"); } while (!_addCollectionTested) { yield return(null); } // Get Collection Log.Debug("ExampleDiscovery.RunTest()", "Attempting to get collection"); if (!_service.GetCollection(OnGetCollection, OnFail, _environmentId, _createdCollectionId)) { Log.Debug("ExampleDiscovery.GetCollection()", "Failed to get collection"); } while (!_getCollectionTested) { yield return(null); } if (!_service.GetFields(OnGetFields, OnFail, _environmentId, _createdCollectionId)) { Log.Debug("ExampleDiscovery.GetFields()", "Failed to get fields"); } while (!_getFieldsTested) { yield return(null); } // Add Document Log.Debug("ExampleDiscovery.RunTest()", "Attempting to add document"); if (!_service.AddDocument(OnAddDocument, OnFail, _environmentId, _createdCollectionId, _documentFilePath, _createdConfigurationId, null)) { Log.Debug("ExampleDiscovery.AddDocument()", "Failed to add document"); } while (!_addDocumentTested) { yield return(null); } // Get Document Log.Debug("ExampleDiscovery.RunTest()", "Attempting to get document"); if (!_service.GetDocument(OnGetDocument, OnFail, _environmentId, _createdCollectionId, _createdDocumentID)) { Log.Debug("ExampleDiscovery.GetDocument()", "Failed to get document"); } while (!_getDocumentTested) { yield return(null); } // Update Document Log.Debug("ExampleDiscovery.RunTest()", "Attempting to update document"); if (!_service.UpdateDocument(OnUpdateDocument, OnFail, _environmentId, _createdCollectionId, _createdDocumentID, _documentFilePath, _createdConfigurationId, null)) { Log.Debug("ExampleDiscovery.UpdateDocument()", "Failed to update document"); } while (!_updateDocumentTested) { yield return(null); } // Query Log.Debug("ExampleDiscovery.RunTest()", "Attempting to query"); if (!_service.Query(OnQuery, OnFail, _environmentId, _createdCollectionId, naturalLanguageQuery: _query)) { while (!_queryTested) { yield return(null); } } // List Credentials Log.Debug("ExampleDiscovery.RunTest()", "Attempting to list credentials"); _service.ListCredentials(OnListCredentials, OnFail, _environmentId); while (!_listCredentialsTested) { yield return(null); } // Create Credentials Log.Debug("ExampleDiscovery.RunTest()", "Attempting to create credentials"); SourceCredentials credentialsParameter = new SourceCredentials() { SourceType = SourceCredentials.SourceTypeEnum.box, CredentialDetails = new CredentialDetails() { CredentialType = CredentialDetails.CredentialTypeEnum.oauth2, EnterpriseId = "myEnterpriseId", ClientId = "myClientId", ClientSecret = "myClientSecret", PublicKeyId = "myPublicIdKey", Passphrase = "myPassphrase", PrivateKey = "myPrivateKey" } }; _service.CreateCredentials(OnCreateCredentials, OnFail, _environmentId, credentialsParameter); while (!_createCredentialsTested) { yield return(null); } // Get Credential Log.Debug("ExampleDiscovery.RunTest()", "Attempting to get credential"); _service.GetCredential(OnGetCredential, OnFail, _environmentId, _createdCredentialId); while (!_getCredentialTested) { yield return(null); } // Get metrics event rate Log.Debug("ExampleDiscovery.RunTest()", "Attempting to Get metrics event rate"); _service.GetMetricsEventRate(OnGetMetricsEventRate, OnFail); while (!_getMetricsEventRateTested) { yield return(null); } // Get metrics query Log.Debug("ExampleDiscovery.RunTest()", "Attempting to Get metrics query"); _service.GetMetricsQuery(OnGetMetricsQuery, OnFail); while (!_getMetricsQueryTested) { yield return(null); } // Get metrics query event Log.Debug("ExampleDiscovery.RunTest()", "Attempting to Get metrics query event"); _service.GetMetricsQueryEvent(OnGetMetricsQueryEvent, OnFail); while (!_getMetricsQueryEventTested) { yield return(null); } // Get metrics query no result Log.Debug("ExampleDiscovery.RunTest()", "Attempting to Get metrics query no result"); _service.GetMetricsQueryNoResults(OnGetMetricsQueryNoResult, OnFail); while (!_getMetricsQueryNoResultTested) { yield return(null); } // Get metrics query token event Log.Debug("ExampleDiscovery.RunTest()", "Attempting to Get metrics query token event"); _service.GetMetricsQueryTokenEvent(OnGetMetricsQueryTokenEvent, OnFail); while (!_getMetricsQueryTokenEventTested) { yield return(null); } // Query log Log.Debug("ExampleDiscovery.RunTest()", "Attempting to Query log"); _service.QueryLog(OnQueryLog, OnFail); while (!_queryLogTested) { yield return(null); } // Create event Log.Debug("ExampleDiscovery.RunTest()", "Attempting to create event"); CreateEventObject queryEvent = new CreateEventObject() { Type = CreateEventObject.TypeEnum.click, Data = new EventData() { EnvironmentId = _environmentId, SessionToken = _sessionToken, CollectionId = _createdCollectionId, DocumentId = _createdDocumentID } }; _service.CreateEvent(OnCreateEvent, OnFail, queryEvent); while (!_createEventTested) { yield return(null); } // DeleteCredential Log.Debug("ExampleDiscovery.RunTest()", "Attempting to delete credential"); _service.DeleteCredentials(OnDeleteCredentials, OnFail, _environmentId, _createdCredentialId); while (!_deleteCredentialsTested) { yield return(null); } // Delete Document Log.Debug("ExampleDiscovery.RunTest()", "Attempting to delete document {0}", _createdDocumentID); if (!_service.DeleteDocument(OnDeleteDocument, OnFail, _environmentId, _createdCollectionId, _createdDocumentID)) { Log.Debug("ExampleDiscovery.DeleteDocument()", "Failed to delete document"); } while (!_deleteDocumentTested) { yield return(null); } _isEnvironmentReady = false; Runnable.Run(CheckEnvironmentState(_waitTime)); while (!_isEnvironmentReady) { yield return(null); } // Delete Collection Log.Debug("ExampleDiscovery.RunTest()", "Attempting to delete collection {0}", _createdCollectionId); if (!_service.DeleteCollection(OnDeleteCollection, OnFail, _environmentId, _createdCollectionId)) { Log.Debug("ExampleDiscovery.DeleteCollection()", "Failed to delete collection"); } while (!_deleteCollectionTested) { yield return(null); } _isEnvironmentReady = false; Runnable.Run(CheckEnvironmentState(_waitTime)); while (!_isEnvironmentReady) { yield return(null); } // Delete Configuration Log.Debug("ExampleDiscovery.RunTest()", "Attempting to delete configuration {0}", _environmentId); if (!_service.DeleteConfiguration(OnDeleteConfiguration, OnFail, _environmentId, _createdConfigurationId)) { Log.Debug("ExampleDiscovery.DeleteConfiguration()", "Failed to delete configuration"); } while (!_deleteConfigurationTested) { yield return(null); } _isEnvironmentReady = false; Runnable.Run(CheckEnvironmentState(_waitTime)); while (!_isEnvironmentReady) { yield return(null); } Log.Debug("ExampleDiscovery.RunTest()", "Discovery examples complete."); }
private IEnumerator ProcessRequestQueue() { // yield AFTER we increment the connection count, so the Send() function can return immediately _activeConnections += 1; #if UNITY_EDITOR if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) { yield return(null); } #else yield return(null); #endif while (_requests.Count > 0) { Request req = _requests.Dequeue(); if (req.Cancel) { continue; } string url = URL; if (!string.IsNullOrEmpty(req.Function)) { url += req.Function; } StringBuilder args = null; foreach (var kp in req.Parameters) { var key = kp.Key; var value = kp.Value; if (value is string) { value = WWW.EscapeURL((string)value); // escape the value } else if (value is byte[]) { value = Convert.ToBase64String((byte[])value); // convert any byte data into base64 string } else if (value is Int32 || value is Int64 || value is UInt32 || value is UInt64 || value is float || value is bool) { value = value.ToString(); } else if (value != null) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Unsupported parameter value type {0}", value.GetType().Name); } else { Log.Error("RESTConnector.ProcessRequestQueue()", "Parameter {0} value is null", key); } if (args == null) { args = new StringBuilder(); } else { args.Append("&"); // append separator } args.Append(key + "=" + value); // append key=value } if (args != null && args.Length > 0) { url += "?" + args.ToString(); } AddHeaders(req.Headers); Response resp = new Response(); DateTime startTime = DateTime.Now; if (!req.Delete) { WWW www = null; if (req.Forms != null) { if (req.Send != null) { Log.Warning("RESTConnector", "Do not use both Send & Form fields in a Request object."); } WWWForm form = new WWWForm(); try { foreach (var formData in req.Forms) { if (formData.Value.IsBinary) { form.AddBinaryData(formData.Key, formData.Value.Contents, formData.Value.FileName, formData.Value.MimeType); } else if (formData.Value.BoxedObject is string) { form.AddField(formData.Key, (string)formData.Value.BoxedObject); } else if (formData.Value.BoxedObject is int) { form.AddField(formData.Key, (int)formData.Value.BoxedObject); } else if (formData.Value.BoxedObject != null) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Unsupported form field type {0}", formData.Value.BoxedObject.GetType().ToString()); } } foreach (var headerData in form.headers) { req.Headers[headerData.Key] = headerData.Value; } } catch (Exception e) { Log.Error("RESTConnector.ProcessRequestQueue()", "Exception when initializing WWWForm: {0}", e.ToString()); } www = new WWW(url, form.data, req.Headers); } else if (req.Send == null) { www = new WWW(url, null, req.Headers); } else { www = new WWW(url, req.Send, req.Headers); } #if ENABLE_DEBUGGING Log.Debug("RESTConnector", "URL: {0}", url); #endif // wait for the request to complete. float timeout = Mathf.Max(Constants.Config.Timeout, req.Timeout); while (!www.isDone) { if (req.Cancel) { break; } if ((DateTime.Now - startTime).TotalSeconds > timeout) { break; } if (req.OnUploadProgress != null) { req.OnUploadProgress(www.uploadProgress); } if (req.OnDownloadProgress != null) { req.OnDownloadProgress(www.progress); } #if UNITY_EDITOR if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) { yield return(null); } #else yield return(null); #endif } if (req.Cancel) { continue; } bool bError = false; Error error = null; if (!string.IsNullOrEmpty(www.error)) { long nErrorCode = -1; int nSeperator = www.error.IndexOf(' '); if (nSeperator > 0 && long.TryParse(www.error.Substring(0, nSeperator).Trim(), out nErrorCode)) { switch (nErrorCode) { case HTTP_STATUS_OK: case HTTP_STATUS_CREATED: bError = false; break; default: bError = true; break; } } else { bError = true; } error = new Error() { URL = url, ErrorCode = resp.HttpResponseCode = nErrorCode, ErrorMessage = www.error, Response = www.text, ResponseHeaders = www.responseHeaders }; if (bError) { Log.Error("RESTConnector.ProcessRequestQueue()", "URL: {0}, ErrorCode: {1}, Error: {2}, Response: {3}", url, nErrorCode, www.error, string.IsNullOrEmpty(www.text) ? "" : www.text); } else { Log.Warning("RESTConnector.ProcessRequestQueue()", "URL: {0}, ErrorCode: {1}, Error: {2}, Response: {3}", url, nErrorCode, www.error, string.IsNullOrEmpty(www.text) ? "" : www.text); } } if (!www.isDone) { Log.Error("RESTConnector.ProcessRequestQueue()", "Request timed out for URL: {0}", url); bError = true; } /*if (!bError && (www.bytes == null || www.bytes.Length == 0)) * { * Log.Warning("RESTConnector.ProcessRequestQueue()", "No data recevied for URL: {0}", url); * bError = true; * }*/ // generate the Response object now.. if (!bError) { resp.Success = true; resp.Data = www.bytes; resp.HttpResponseCode = GetResponseCode(www); } else { resp.Success = false; resp.Error = error; } resp.Headers = www.responseHeaders; resp.ElapsedTime = (float)(DateTime.Now - startTime).TotalSeconds; // if the response is over a threshold, then log with status instead of debug if (resp.ElapsedTime > LogResponseTime) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Request {0} completed in {1} seconds.", url, resp.ElapsedTime); } if (req.OnResponse != null) { req.OnResponse(req, resp); } www.Dispose(); } else { #if ENABLE_DEBUGGING Log.Debug("RESTConnector.ProcessRequestQueue90", "Delete Request URL: {0}", url); #endif float timeout = Mathf.Max(Constants.Config.Timeout, req.Timeout); DeleteRequest deleteReq = new DeleteRequest(); Runnable.Run(deleteReq.Send(url, req.Headers)); while (!deleteReq.IsComplete) { if (req.Cancel) { break; } if ((DateTime.Now - startTime).TotalSeconds > timeout) { break; } yield return(null); } if (req.Cancel) { continue; } resp.Success = deleteReq.Success; resp.Data = deleteReq.Data; resp.Error = deleteReq.Error; resp.HttpResponseCode = deleteReq.HttpResponseCode; resp.ElapsedTime = (float)(DateTime.Now - startTime).TotalSeconds; resp.Headers = deleteReq.ResponseHeaders; if (req.OnResponse != null) { req.OnResponse(req, resp); } } } // reduce the connection count before we exit.. _activeConnections -= 1; yield break; }
public Action(Runnable runnable) { Runnable = runnable; }
public void Post(Runnable runnable) { runnable.Run(); }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; string credentialsFilepath = "../sdk-credentials/credentials.json"; // Load credentials file if it exists. If it doesn't exist, don't run the tests. if (File.Exists(credentialsFilepath)) { result = File.ReadAllText(credentialsFilepath); } else { yield break; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.GetCredentialByname("speech-to-text-sdk")[0].Credentials; // Create credential and instantiate service TokenOptions tokenOptions = new TokenOptions() { IamApiKey = credential.IamApikey, }; // Create credential and instantiate service Credentials credentials = new Credentials(tokenOptions, credential.Url); // Wait for tokendata while (!credentials.HasIamTokenData()) { yield return(null); } _speechToText = new SpeechToText(credentials); _customCorpusFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/speech-to-text/theJabberwocky-utf8.txt"; _customWordsFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/speech-to-text/test-stt-words.json"; _grammarFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/speech-to-text/confirm.abnf"; _acousticResourceMimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl)); Runnable.Run(DownloadAcousticResource()); while (!_isAudioLoaded) { yield return(null); } // Recognize Log.Debug("TestSpeechToText.Examples()", "Attempting to recognize"); List <string> keywords = new List <string>(); keywords.Add("speech"); _speechToText.KeywordsThreshold = 0.5f; _speechToText.InactivityTimeout = 120; _speechToText.StreamMultipart = false; _speechToText.Keywords = keywords.ToArray(); _speechToText.Recognize(HandleOnRecognize, OnFail, _acousticResourceData, _acousticResourceMimeType); while (!_recognizeTested) { yield return(null); } // Get models Log.Debug("TestSpeechToText.Examples()", "Attempting to get models"); _speechToText.GetModels(HandleGetModels, OnFail); while (!_getModelsTested) { yield return(null); } // Get model Log.Debug("TestSpeechToText.Examples()", "Attempting to get model {0}", _modelNameToGet); _speechToText.GetModel(HandleGetModel, OnFail, _modelNameToGet); while (!_getModelTested) { yield return(null); } // Get customizations Log.Debug("TestSpeechToText.Examples()", "Attempting to get customizations"); _speechToText.GetCustomizations(HandleGetCustomizations, OnFail); while (!_getCustomizationsTested) { yield return(null); } // Create customization Log.Debug("TestSpeechToText.Examples()", "Attempting create customization"); _speechToText.CreateCustomization(HandleCreateCustomization, OnFail, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity"); while (!_createCustomizationsTested) { yield return(null); } // Get customization Log.Debug("TestSpeechToText.Examples()", "Attempting to get customization {0}", _createdCustomizationID); _speechToText.GetCustomization(HandleGetCustomization, OnFail, _createdCustomizationID); while (!_getCustomizationTested) { yield return(null); } // Get custom corpora Log.Debug("TestSpeechToText.Examples()", "Attempting to get custom corpora for {0}", _createdCustomizationID); _speechToText.GetCustomCorpora(HandleGetCustomCorpora, OnFail, _createdCustomizationID); while (!_getCustomCorporaTested) { yield return(null); } // Add custom corpus Log.Debug("TestSpeechToText.Examples()", "Attempting to add custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); string corpusData = File.ReadAllText(_customCorpusFilePath); _speechToText.AddCustomCorpus(HandleAddCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName, true, corpusData); while (!_addCustomCorpusTested) { yield return(null); } // Get custom corpus Log.Debug("TestSpeechToText.Examples()", "Attempting to get custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.GetCustomCorpus(HandleGetCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName); while (!_getCustomCorpusTested) { yield return(null); } // Wait for customization Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom words Log.Debug("TestSpeechToText.Examples()", "Attempting to get custom words."); _speechToText.GetCustomWords(HandleGetCustomWords, OnFail, _createdCustomizationID); while (!_getCustomWordsTested) { yield return(null); } // Add custom words from path Log.Debug("TestSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words json path {1}", _createdCustomizationID, _customWordsFilePath); string customWords = File.ReadAllText(_customWordsFilePath); _speechToText.AddCustomWords(HandleAddCustomWordsFromPath, OnFail, _createdCustomizationID, customWords); while (!_addCustomWordsFromPathTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Add custom words from object Words words = new Words(); Word w0 = new Word(); List <Word> wordList = new List <Word>(); w0.word = "mikey"; w0.sounds_like = new string[1]; w0.sounds_like[0] = "my key"; w0.display_as = "Mikey"; wordList.Add(w0); Word w1 = new Word(); w1.word = "charlie"; w1.sounds_like = new string[1]; w1.sounds_like[0] = "char lee"; w1.display_as = "Charlie"; wordList.Add(w1); Word w2 = new Word(); w2.word = "bijou"; w2.sounds_like = new string[1]; w2.sounds_like[0] = "be joo"; w2.display_as = "Bijou"; wordList.Add(w2); words.words = wordList.ToArray(); Log.Debug("TestSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words object", _createdCustomizationID); _speechToText.AddCustomWords(HandleAddCustomWordsFromObject, OnFail, _createdCustomizationID, words); while (!_addCustomWordsFromObjectTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom word Log.Debug("TestSpeechToText.Examples()", "Attempting to get custom word {1} in customization {0}", _createdCustomizationID, words.words[0].word); _speechToText.GetCustomWord(HandleGetCustomWord, OnFail, _createdCustomizationID, words.words[0].word); while (!_getCustomWordTested) { yield return(null); } // Train customization Log.Debug("TestSpeechToText.Examples()", "Attempting to train customization {0}", _createdCustomizationID); _speechToText.TrainCustomization(HandleTrainCustomization, OnFail, _createdCustomizationID); while (!_trainCustomizationTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Delete custom word Log.Debug("TestSpeechToText.Examples()", "Attempting to delete custom word {1} in customization {0}", _createdCustomizationID, words.words[2].word); _speechToText.DeleteCustomWord(HandleDeleteCustomWord, OnFail, _createdCustomizationID, words.words[2].word); while (!_deleteCustomWordTested) { yield return(null); } // Delay Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete custom corpus Log.Debug("TestSpeechToText.Examples()", "Attempting to delete custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.DeleteCustomCorpus(HandleDeleteCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName); while (!_deleteCustomCorpusTested) { yield return(null); } // Delay Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Reset customization Log.Debug("TestSpeechToText.Examples()", "Attempting to reset customization {0}", _createdCustomizationID); _speechToText.ResetCustomization(HandleResetCustomization, OnFail, _createdCustomizationID); while (!_resetCustomizationTested) { yield return(null); } // Delay Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // List Grammars Log.Debug("TestSpeechToText.Examples()", "Attempting to list grammars {0}", _createdCustomizationID); _speechToText.ListGrammars(OnListGrammars, OnFail, _createdCustomizationID); while (!_listGrammarsTested) { yield return(null); } // Add Grammar Log.Debug("TestSpeechToText.Examples()", "Attempting to add grammar {0}", _createdCustomizationID); string grammarFile = File.ReadAllText(_grammarFilePath); _speechToText.AddGrammar(OnAddGrammar, OnFail, _createdCustomizationID, _grammarName, grammarFile, _grammarFileContentType); while (!_addGrammarTested) { yield return(null); } // Get Grammar Log.Debug("TestSpeechToText.Examples()", "Attempting to get grammar {0}", _createdCustomizationID); _speechToText.GetGrammar(OnGetGrammar, OnFail, _createdCustomizationID, _grammarName); while (!_getGrammarTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Delete Grammar Log.Debug("TestSpeechToText.Examples()", "Attempting to delete grammar {0}", _createdCustomizationID); _speechToText.DeleteGrammar(OnDeleteGrammar, OnFail, _createdCustomizationID, _grammarName); while (!_deleteGrammarTested) { yield return(null); } _readyToContinue = false; // Delete customization Log.Debug("TestSpeechToText.Examples()", "Attempting to delete customization {0}", _createdCustomizationID); _speechToText.DeleteCustomization(HandleDeleteCustomization, OnFail, _createdCustomizationID); while (!_deleteCustomizationsTested) { yield return(null); } // List acoustic customizations Log.Debug("TestSpeechToText.Examples()", "Attempting to get acoustic customizations"); _speechToText.GetCustomAcousticModels(HandleGetCustomAcousticModels, OnFail); while (!_getAcousticCustomizationsTested) { yield return(null); } // Create acoustic customization Log.Debug("TestSpeechToText.Examples()", "Attempting to create acoustic customization"); _speechToText.CreateAcousticCustomization(HandleCreateAcousticCustomization, OnFail, _createdAcousticModelName); while (!_createAcousticCustomizationsTested) { yield return(null); } // Get acoustic customization Log.Debug("TestSpeechToText.Examples()", "Attempting to get acoustic customization {0}", _createdAcousticModelId); _speechToText.GetCustomAcousticModel(HandleGetCustomAcousticModel, OnFail, _createdAcousticModelId); while (!_getAcousticCustomizationTested) { yield return(null); } while (!_isAudioLoaded) { yield return(null); } // Create acoustic resource Log.Debug("TestSpeechToText.Examples()", "Attempting to create audio resource {1} on {0}", _createdAcousticModelId, _acousticResourceName); string mimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl)); _speechToText.AddAcousticResource(HandleAddAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName, mimeType, mimeType, true, _acousticResourceData); while (!_addAcousticResourcesTested) { yield return(null); } // Wait for customization _isAcousticCustomizationReady = false; Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId)); while (!_isAcousticCustomizationReady) { yield return(null); } // List acoustic resources Log.Debug("TestSpeechToText.Examples()", "Attempting to get audio resources {0}", _createdAcousticModelId); _speechToText.GetCustomAcousticResources(HandleGetCustomAcousticResources, OnFail, _createdAcousticModelId); while (!_getAcousticResourcesTested) { yield return(null); } // Train acoustic customization Log.Debug("TestSpeechToText.Examples()", "Attempting to train acoustic customization {0}", _createdAcousticModelId); _speechToText.TrainAcousticCustomization(HandleTrainAcousticCustomization, OnFail, _createdAcousticModelId, null, true); while (!_trainAcousticCustomizationsTested) { yield return(null); } // Get acoustic resource Log.Debug("TestSpeechToText.Examples()", "Attempting to get audio resource {1} from {0}", _createdAcousticModelId, _acousticResourceName); _speechToText.GetCustomAcousticResource(HandleGetCustomAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName); while (!_getAcousticResourceTested) { yield return(null); } // Wait for customization _isAcousticCustomizationReady = false; Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId)); while (!_isAcousticCustomizationReady) { yield return(null); } // Delete acoustic resource DeleteAcousticResource(); while (!_deleteAcousticResource) { yield return(null); } // Delay Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete acoustic resource for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // Reset acoustic customization Log.Debug("TestSpeechToText.Examples()", "Attempting to reset acoustic customization {0}", _createdAcousticModelId); _speechToText.ResetAcousticCustomization(HandleResetAcousticCustomization, OnFail, _createdAcousticModelId); while (!_resetAcousticCustomizationsTested) { yield return(null); } // Delay Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete acoustic customization for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } // Delete acoustic customization DeleteAcousticCustomization(); while (!_deleteAcousticCustomizationsTested) { yield return(null); } // Delay Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying complete for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } Log.Debug("TestSpeechToText.RunTest()", "Speech to Text examples complete."); yield break; }
public void run() { thread=this; byte[] foo; Buffer buf=new Buffer(); Packet packet=new Packet(buf); int i=0; Channel channel; int[] start=new int[1]; int[] length=new int[1]; KeyExchange kex=null; try { while(_isConnected && thread!=null) { buf=read(buf); int msgType=buf.buffer[5]&0xff; // if(msgType!=94) //System.Console.WriteLine("read: 94 ? "+msgType); if(kex!=null && kex.getState()==msgType) { bool result=kex.next(buf); if(!result) { throw new JSchException("verify: "+result); } continue; } switch(msgType) { case SSH_MSG_KEXINIT: //System.Console.WriteLine("KEXINIT"); kex=receive_kexinit(buf); break; case SSH_MSG_NEWKEYS: //System.Console.WriteLine("NEWKEYS"); send_newkeys(); receive_newkeys(buf, kex); kex=null; break; case SSH_MSG_CHANNEL_DATA: buf.getInt(); buf.getByte(); buf.getByte(); i=buf.getInt(); channel=Channel.getChannel(i, this); foo=buf.getString(start, length); if(channel==null) { break; } try { channel.write(foo, start[0], length[0]); } catch(Exception e) { //System.Console.WriteLine(e); try{channel.disconnect();} catch(Exception ee){} break; } int len=length[0]; channel.setLocalWindowSize(channel.lwsize-len); if(channel.lwsize<channel.lwsize_max/2) { packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST); buf.putInt(channel.getRecipient()); buf.putInt(channel.lwsize_max-channel.lwsize); write(packet); channel.setLocalWindowSize(channel.lwsize_max); } break; case SSH_MSG_CHANNEL_EXTENDED_DATA: buf.getInt(); buf.getShort(); i=buf.getInt(); channel=Channel.getChannel(i, this); buf.getInt(); // data_type_code == 1 foo=buf.getString(start, length); //System.Console.WriteLine("stderr: "+new String(foo,start[0],length[0])); if(channel==null) { break; } //channel.write(foo, start[0], length[0]); channel.write_ext(foo, start[0], length[0]); len=length[0]; channel.setLocalWindowSize(channel.lwsize-len); if(channel.lwsize<channel.lwsize_max/2) { packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST); buf.putInt(channel.getRecipient()); buf.putInt(channel.lwsize_max-channel.lwsize); write(packet); channel.setLocalWindowSize(channel.lwsize_max); } break; case SSH_MSG_CHANNEL_WINDOW_ADJUST: buf.getInt(); buf.getShort(); i=buf.getInt(); channel=Channel.getChannel(i, this); if(channel==null) { break; } channel.addRemoteWindowSize(buf.getInt()); break; case SSH_MSG_CHANNEL_EOF: buf.getInt(); buf.getShort(); i=buf.getInt(); channel=Channel.getChannel(i, this); if(channel!=null) { //channel._eof_remote=true; //channel.eof(); channel.eof_remote(); } /* packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_EOF); buf.putInt(channel.getRecipient()); write(packet); */ break; case SSH_MSG_CHANNEL_CLOSE: buf.getInt(); buf.getShort(); i=buf.getInt(); channel=Channel.getChannel(i, this); if(channel!=null) { // channel.close(); channel.disconnect(); } /* if(Channel.pool.size()==0){ thread=null; } */ break; case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: buf.getInt(); buf.getShort(); i=buf.getInt(); channel=Channel.getChannel(i, this); if(channel==null) { //break; } channel.setRecipient(buf.getInt()); channel.setRemoteWindowSize(buf.getInt()); channel.setRemotePacketSize(buf.getInt()); break; case SSH_MSG_CHANNEL_OPEN_FAILURE: buf.getInt(); buf.getShort(); i=buf.getInt(); channel=Channel.getChannel(i, this); if(channel==null) { //break; } int reason_code=buf.getInt(); //foo=buf.getString(); // additional textual information //foo=buf.getString(); // language tag channel.exitstatus=reason_code; channel._close=true; channel._eof_remote=true; channel.setRecipient(0); break; case SSH_MSG_CHANNEL_REQUEST: buf.getInt(); buf.getShort(); i=buf.getInt(); foo=buf.getString(); bool reply=(buf.getByte()!=0); channel=Channel.getChannel(i, this); if(channel!=null) { byte reply_type=(byte)SSH_MSG_CHANNEL_FAILURE; if((new String(foo)).equals("exit-status")) { i=buf.getInt(); // exit-status channel.setExitStatus(i); // System.Console.WriteLine("exit-stauts: "+i); // channel.close(); reply_type=(byte)SSH_MSG_CHANNEL_SUCCESS; } if(reply) { packet.reset(); buf.putByte(reply_type); buf.putInt(channel.getRecipient()); write(packet); } } else { } break; case SSH_MSG_CHANNEL_OPEN: buf.getInt(); buf.getShort(); foo=buf.getString(); String ctyp=new String(foo); //System.Console.WriteLine("type="+ctyp); if(!new String("forwarded-tcpip").equals(ctyp) && !(new String("x11").equals(ctyp) && x11_forwarding)) { System.Console.WriteLine("Session.run: CHANNEL OPEN "+ctyp); throw new IOException("Session.run: CHANNEL OPEN "+ctyp); } else { channel=Channel.getChannel(ctyp); addChannel(channel); channel.getData(buf); channel.init(); packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_OPEN_CONFIRMATION); buf.putInt(channel.getRecipient()); buf.putInt(channel.id); buf.putInt(channel.lwsize); buf.putInt(channel.lmpsize); write(packet); Thread tmp=new Thread(channel); tmp.setName("Channel "+ctyp+" "+host); tmp.start(); break; } case SSH_MSG_CHANNEL_SUCCESS: buf.getInt(); buf.getShort(); i=buf.getInt(); channel=Channel.getChannel(i, this); if(channel==null) { break; } channel.reply=1; break; case SSH_MSG_CHANNEL_FAILURE: buf.getInt(); buf.getShort(); i=buf.getInt(); channel=Channel.getChannel(i, this); if(channel==null) { break; } channel.reply=0; break; case SSH_MSG_GLOBAL_REQUEST: buf.getInt(); buf.getShort(); foo=buf.getString(); // request name reply=(buf.getByte()!=0); if(reply) { packet.reset(); buf.putByte((byte)SSH_MSG_REQUEST_FAILURE); write(packet); } break; case SSH_MSG_REQUEST_FAILURE: case SSH_MSG_REQUEST_SUCCESS: Thread t=grr.getThread(); if(t!=null) { grr.setReply(msgType==SSH_MSG_REQUEST_SUCCESS? 1 : 0); t.interrupt(); } break; default: System.Console.WriteLine("Session.run: unsupported type "+msgType); throw new IOException("Unknown SSH message type "+msgType); } } } catch(Exception e) { //System.Console.WriteLine("# Session.run"); //e.printStackTrace(); } try { disconnect(); } catch(NullReferenceException e) { //System.Console.WriteLine("@1"); //e.printStackTrace(); } catch(Exception e) { //System.Console.WriteLine("@2"); //e.printStackTrace(); } _isConnected=false; }
public SmartBandService() { _runnable = new Runnable(HandlerRunnable); }
public void Execute (Runnable r) { InternalExecute (r, true); }
private IEnumerator Examples() { // Get all classifiers Log.Debug("ExampleVisualRecognition.Examples()", "Attempting to get all classifiers"); if (!_visualRecognition.GetClassifiers(OnGetClassifiers, OnFail)) { Log.Debug("ExampleVisualRecognition.GetClassifiers()", "Failed to get all classifiers!"); } while (!_getClassifiersTested) { yield return(null); } #if TRAIN_CLASSIFIER // Train classifier Log.Debug("ExampleVisualRecognition.Examples()", "Attempting to train classifier"); string positiveExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_positive_examples.zip"; string negativeExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/negative_examples.zip"; Dictionary <string, string> positiveExamples = new Dictionary <string, string>(); positiveExamples.Add("giraffe", positiveExamplesPath); if (!_visualRecognition.TrainClassifier(OnTrainClassifier, OnFail, "unity-test-classifier-example", positiveExamples, negativeExamplesPath)) { Log.Debug("ExampleVisualRecognition.TrainClassifier()", "Failed to train classifier!"); } while (!_trainClassifierTested) { yield return(null); } // Find classifier by ID Log.Debug("ExampleVisualRecognition.Examples()", "Attempting to find classifier by ID"); if (!_visualRecognition.GetClassifier(OnGetClassifier, OnFail, _classifierID)) { Log.Debug("ExampleVisualRecognition.GetClassifier()", "Failed to get classifier!"); } while (!_getClassifierTested) { yield return(null); } #endif // Classify get Log.Debug("ExampleVisualRecognition.Examples()", "Attempting to get classify via URL"); if (!_visualRecognition.Classify(_imageURL, OnClassifyGet, OnFail)) { Log.Debug("ExampleVisualRecognition.Classify()", "Classify image failed!"); } while (!_classifyGetTested) { yield return(null); } // Classify post image Log.Debug("ExampleVisualRecognition.Examples()", "Attempting to classify via image on file system"); string imagesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_to_classify.jpg"; string[] owners = { "IBM", "me" }; string[] classifierIDs = { "default", _classifierID }; if (!_visualRecognition.Classify(OnClassifyPost, OnFail, imagesPath, owners, classifierIDs, 0.5f)) { Log.Debug("ExampleVisualRecognition.Classify()", "Classify image failed!"); } while (!_classifyPostTested) { yield return(null); } // Detect faces get Log.Debug("ExampleVisualRecognition.Examples()", "Attempting to detect faces via URL"); if (!_visualRecognition.DetectFaces(_imageURL, OnDetectFacesGet, OnFail)) { Log.Debug("ExampleVisualRecognition.DetectFaces()", "Detect faces failed!"); } while (!_detectFacesGetTested) { yield return(null); } // Detect faces post image Log.Debug("ExampleVisualRecognition.Examples()", "Attempting to detect faces via image"); string faceExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/obama.jpg"; if (!_visualRecognition.DetectFaces(OnDetectFacesPost, OnFail, faceExamplePath)) { Log.Debug("ExampleVisualRecognition.DetectFaces()", "Detect faces failed!"); } while (!_detectFacesPostTested) { yield return(null); } #if DELETE_TRAINED_CLASSIFIER #region Delay Runnable.Run(Delay(_delayTime)); while (_isWaitingForDelay) { yield return(null); } #endregion // Delete classifier by ID Log.Debug("ExampleVisualRecognition.Examples()", "Attempting to delete classifier"); if (!_visualRecognition.DeleteClassifier(OnDeleteClassifier, OnFail, _classifierToDelete)) { Log.Debug("ExampleVisualRecognition.DeleteClassifier()", "Failed to delete classifier!"); } while (!_deleteClassifierTested) { yield return(null); } #endif Log.Debug("ExampleVisualRecognition.Examples()", "Visual Recogition tests complete"); }
public void run() { Buffer buf=new Buffer(300); // ?? Packet packet=new Packet(buf); thread=this; try { while(thread!=null) { Socket socket=ss.accept(); socket.setTcpNoDelay(true); Stream In=socket.getInputStream(); Stream Out=socket.getOutputStream(); ChannelDirectTCPIP channel=new ChannelDirectTCPIP(); channel.init(); channel.setInputStream(In); channel.setOutputStream(Out); session.addChannel(channel); ((ChannelDirectTCPIP)channel).setHost(host); ((ChannelDirectTCPIP)channel).setPort(rport); ((ChannelDirectTCPIP)channel).setOrgIPAddress(socket.getInetAddress().getHostAddress()); ((ChannelDirectTCPIP)channel).setOrgPort(socket.getPort()); channel.connect(); if(channel.exitstatus!=-1) { } } } catch(Exception e) { //System.out.println("! "+e); } delete(); }
void Start() { LogSystem.InstallDefaultReactors(); _dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; Runnable.Run(CreateService()); }
public Thread(Runnable e) { }
internal Given(Runnable runnable, string callerMember, string callerFile, string testId, string reportId, BDTestBase bdTestBase) : base(runnable, callerMember, callerFile, testId, reportId, StepType.Given, bdTestBase) { }
public void add(Runnable c) { tmp.Add(c); }
public void JsonValue_IsReferencedCorrectly() { Runnable table = new Runnable(); table.Sql(@" DROP TABLE IF EXISTS jerry_json; CREATE TABLE jerry_json( `Json` varchar(8000) NOT NULL );"); Runner.Command(table); List <TestModel> testModels = new List <TestModel>() { new TestModel() { Json = new JsonModel() { Value1 = 10, Value3 = 20 } }, new TestModel() { Json = new JsonModel() { Value1 = 20, Value3 = 30 } }, }; Runnable <TestModel, object> insert1 = new Runnable <TestModel, object>(testModels[0]); Runnable <TestModel, object> insert2 = new Runnable <TestModel, object>(testModels[1]); insert1.Sql("INSERT INTO jerry_json ( `Json` ) VALUES ( "); insert1.M(p => p.Par(m => m.Json)); insert1.Sql(" );"); insert2.Sql("INSERT INTO jerry_json ( `Json` ) VALUES ( "); insert2.M(p => p.Par(m => m.Json)); insert2.Sql(" );"); Runner.Command(insert1); Runner.Command(insert2); Runnable <object, JsonView> select = new Runnable <object, JsonView>(); select.Sql("SELECT `Json` AS "); select.R(p => p.Prop(m => m.Json)); select.Sql(", `Json` AS "); select.R(p => p.Prop(m => m.JsonString)); select.Sql(" FROM jerry_json "); select.R(p => p.Ali()); select.Sql(" WHERE "); select.R(p => p.Json(m => m.Json.Value1)); select.Sql(" = 10 AND "); select.R(p => p.Json(m => m.Json.Value3)); select.Sql(" = 20 "); IList <JsonView> result = Runner.Query(select); result.Count.ShouldBe(1); result[0].Json.Value1.ShouldBe(10); result[0].Json.Value3.ShouldBe(20); }