private async Task ProcessCurrentVideoFrame() { try { if (mediaElement.MediaPlayer == null) { return; } mediaElement.MediaPlayer.takeSnapshot(0, path, InfoSettingFix.FixTakeWidth, InfoSettingFix.FixTakeHeight); data = File.ReadAllBytes(path); int byteLength = data.Length; //Trường hợp data trống và byte 2 Frame liên tiếp bằng nhau if (data == null || byteLength == 0 || byteLength == this.ByteLength) { return; } this.ByteLength = byteLength; CurrentFrame = new CurrentFrameModel() { CaptureTime = DateTime.Now, DataCurrent = data }; RealtimeFixModel.ListFrame4.Enqueue(CurrentFrame); data = null; } catch (Exception ex) { return; } CoreUtil.FreeMemory(); }
public UserPropertyDrawer GetPropertyDrawer(Type propertyType) { UserPropertyDrawer drawer = null; if (mPropertyDrawers.Count == 0) { var customTypes = CoreUtil.FindSubTypes(typeof(UserPropertyDrawer)); foreach (var type in customTypes) { var attributes = type.GetCustomAttributes(typeof(UserPropertyDrawerAttribute), true); var drawerType = attributes.Length > 0 ? ((UserPropertyDrawerAttribute)attributes[0]).type : null; if (drawerType != null) { var instance = (UserPropertyDrawer)CoreUtil.CreateInstance(type, null); mPropertyDrawers.Add(drawerType, instance); } } } if (propertyType.IsArray) { drawer = mPropertyDrawers[typeof(Array)]; } else if (mPropertyDrawers.ContainsKey(propertyType)) { drawer = mPropertyDrawers[propertyType]; } return(drawer); }
/// <summary> /// 根据Response解析result结果 /// </summary> /// <param name="url">提交eSight的url</param> /// <param name="hrm">eSight返回的http result</param> /// <returns>解析过的结果,JObject</returns> public JObject HCCheckResult(string url, HttpResponseMessage hrm) { if (hrm.IsSuccessStatusCode) { string retVal = hrm.Content.ReadAsStringAsync().Result; LogUtil.HWLogger.API.Info("Huawei return:" + retVal); JObject data = JsonUtil.DeserializeObject <JObject>(hrm.Content.ReadAsStringAsync().Result); return(data); } else { string webErrorCode = ConstMgr.ErrorCode.SYS_UNKNOWN_ERR; if (hrm != null) { int statusCode = CoreUtil.GetObjTranNull <int>(hrm.StatusCode); if (statusCode >= 400 && statusCode <= 600) { webErrorCode = "-50" + statusCode; } } LogUtil.HWLogger.API.ErrorFormat("Accessing[{0}] ,StatusCode:[{1}],ReasonPhrase:[{2}], Error occurred: [{3}]", url, hrm.StatusCode, hrm.ReasonPhrase, hrm.Content.ReadAsStringAsync().Result); throw new ESSessionExpceion(webErrorCode, this, String.Format("Accessing[{0}] ,StatusCode:[{1}],ReasonPhrase:[{2}], Error occurred: [{3}]", url, hrm.StatusCode, hrm.ReasonPhrase, hrm.Content.ReadAsStringAsync().Result)); } }
ISerializer Search(string dir, IGeneralConfig generalConfig, AssetInfo info) { var combined = Path.Combine(dir, info.File.Filename); var filename = Path.GetFileName(combined).ToUpperInvariant(); dir = Path.GetDirectoryName(combined); var resolved = generalConfig.ResolvePath(dir); if (!Directory.Exists(resolved)) { return(null); } var directory = Path.Combine(resolved, filename); if (Directory.Exists(directory)) { var s = _containerLoaderRegistry.Load(directory, info, ContainerFormat.Directory); if (s != null) { return(s); } } var files = Directory.GetFiles(resolved); foreach (var path in files.Where(x => Path.GetFileNameWithoutExtension(x).ToUpperInvariant() == filename)) { if (info.File.Sha256Hashes != null) { var hash = GetHash(path); if (info.File.Sha256Hashes.All(x => !hash.Equals(x, StringComparison.OrdinalIgnoreCase))) { var expected = string.Join(", ", info.File.Sha256Hashes); CoreUtil.LogWarn( $"Found file {path} for asset {info.AssetId}, but its " + $"hash ({hash}) did not match any of the expected ones ({expected})"); return(null); } } ISerializer s; var extension = Path.GetExtension(path).ToUpperInvariant(); switch (extension) { case ".XLD": s = _containerLoaderRegistry.Load(path, info, ContainerFormat.Xld); break; case ".ZIP": s = _containerLoaderRegistry.Load(path, info, ContainerFormat.Zip); break; default: s = _containerLoaderRegistry.Load(path, info, info.File.ContainerFormat); break; } if (s != null) { return(s); } } return(null); }
/// <summary> /// 删除失败的软件源任务 /// </summary> private WebReturnResult <int> DeleteTask(object eventData) { var ret = new WebReturnResult <int>() { Code = CoreUtil.GetObjTranNull <int>(ConstMgr.ErrorCode.SYS_UNKNOWN_ERR), Description = "", Data = 0 }; try { LogUtil.HWLogger.UI.Info("Deleting failed software source task..."); int deleteTaskResult = ESightEngine.Instance.ClearAllFailedSoftwareSourceTask(); ret.Code = 0; ret.Data = deleteTaskResult; ret.Description = "Deleting failed software source task successful!"; LogUtil.HWLogger.UI.InfoFormat("Deleting failed software source task successful! the ret is [{0}]", JsonUtil.SerializeObject(ret)); } catch (BaseException ex) { LogUtil.HWLogger.UI.Error("Deleting failed software source task failed: ", ex); ret.Code = CoreUtil.GetObjTranNull <int>(ex.Code); ret.ErrorModel = ex.ErrorModel; ret.Data = 0; ret.Description = ex.Message; } catch (Exception ex) { LogUtil.HWLogger.UI.Error("Deleting failed software source task failed: ", ex); ret.Code = CoreUtil.GetObjTranNull <int>(ConstMgr.ErrorCode.SYS_UNKNOWN_ERR); ret.Data = 0; ret.Description = ex.InnerException.Message ?? ex.Message; } return(ret); }
/// <summary> /// 根据eSight返回的状态,返回更新到数据库的状态。 /// </summary> /// <param name="oldStatus">旧的数据库状态</param> /// <param name="taskStatus">eSight返回的taskStatus</param> /// <param name="taskResult">eSight返回的taskResult</param> /// <param name="taskCode">eSight返回的taskCode</param> /// <returns>判断后的任务状态</returns> private string GetTaskStatus(string oldStatus, string taskStatus, string taskResult, string taskCode) { if (taskResult == "Failed") { return(ConstMgr.HWESightTask.SYNC_STATUS_HW_FAILED); //失败优先返回 } if (string.Equals(taskResult, "Partion Success", StringComparison.OrdinalIgnoreCase)) { return(ConstMgr.HWESightTask.SYNC_STATUS_HW_PFAILED); } //部分成功 //返回非0,默认返回错误。 if (CoreUtil.GetObjTranNull <int>(taskCode) != 0) { return(ConstMgr.HWESightTask.SYNC_STATUS_HW_FAILED); } //成功,返回finishe. if (taskResult == "Success") { return(ConstMgr.HWESightTask.SYNC_STATUS_FINISHED); } //完成,返回finishe. if (taskStatus == "Complete") { return(ConstMgr.HWESightTask.SYNC_STATUS_FINISHED); } //正在运行 if (taskStatus == "Running") { return(ConstMgr.HWESightTask.SYNC_STATUS_CREATED); } return(oldStatus); }
public object LoadAssetCached(AssetId id) { object asset = _assetCache.Get(id); if (asset is Exception) // If it failed to load once then stop trying (at least until an asset:reload / cycle) { return(null); } if (asset != null) { return(asset); } try { asset = LoadAssetInternal(id); } catch (Exception e) { if (CoreUtil.IsCriticalException(e)) { throw; } Raise(new LogEvent(LogEvent.Level.Error, $"Could not load asset {id}: {e}")); asset = e; } _assetCache.Add(asset, id); return(asset is Exception ? null : asset); }
/// <summary> /// Calculates number of occurrences of each word in a webpage. /// </summary> /// <returns>Dictionary of each word.</returns> public override Dictionary <string, int> CalculateOccuranceInText() { if (IsFilterStopWords && stopwordDictionary == null) { stopwordDictionary = CoreUtil.ProcessStopWords(StopWords); } if (htmlPage == null) { var htmlWeb = new HtmlWeb(); var lastStatusCode = HttpStatusCode.OK; htmlWeb.PostResponse = (request, response) => { if (response != null) { lastStatusCode = response.StatusCode; } }; htmlPage = htmlWeb.Load(Input); if (lastStatusCode != HttpStatusCode.OK) { throw new Exception($"{Constant.WEB_REQUEST_ERROR_MESSAGE} {lastStatusCode}"); } } var bodyText = htmlPage.DocumentNode.SelectSingleNode("//body").InnerText; allWordDictionary = CoreUtil.ProcessInput(bodyText, stopwordDictionary); return(allWordDictionary); }
public void ProcessMetaTag_WithWordsNotExistWithinMetaTag_ReturnDictionaryOfWordOccurenceListedInMetaTag(string html) { //arrange var stopwordDictionary = new Dictionary <string, int>(StringComparer.InvariantCultureIgnoreCase); var allWordDictionary = new Dictionary <string, int>(StringComparer.InvariantCultureIgnoreCase) { { "happy", 5 }, { "coding", 5 }, { "Seo", 5 }, { "Analyser", 5 }, { "Text", 5 } }; var expected = new Dictionary <string, int>(StringComparer.InvariantCultureIgnoreCase) { { "hello", 0 }, { "world", 0 }, { "happy", 5 }, { "coding", 5 }, { "start", 0 }, { "today", 0 } }; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//meta"); //act var actual = CoreUtil.ProcessMetaTag(nodes, stopwordDictionary, allWordDictionary); //assert Assert.AreEqual(actual, expected); }
/// <summary> /// 区域查找 /// </summary> /// <param name="queryArea">选择的范围,经纬度之间','隔开,"小经,小纬,大经,大纬"</param> /// <param name="ncfilepath">nc文件路径</param> /// <param name="zoom">地图缩放等级</param> public string ZoneLookUp(string queryArea, string ncfilepath, string zoom) { Inital(ncfilepath); IRectangle zoneQueryRect = CoreUtil.GetRectangle <QueryRectangleF>(queryArea); //前台所要查找的范围 //2.读取nc文件 //先读取经纬度信息,确定读取的下标 NCFileUtil ncFile = new NCFileUtil(ncfilepath); NcLonLatModel ncLatLonModel = ncFile.ReadNcLonLat(models[0]); int minLonIndex = 0, maxLonIndex = 0, minLatIndex = 0, maxLatIndex = 0; CoreUtil.GetIndex(ncLatLonModel.Lon, zoneQueryRect.minLon, zoneQueryRect.maxLon, ref minLonIndex, ref maxLonIndex); CoreUtil.GetIndex(ncLatLonModel.Lat, zoneQueryRect.minLat, zoneQueryRect.maxLat, ref minLatIndex, ref maxLatIndex); ncLatLonModel.minLonIndex = minLonIndex; ncLatLonModel.minLatIndex = minLatIndex; ncLatLonModel.maxLonIndex = maxLonIndex; ncLatLonModel.maxLatIndex = maxLatIndex; QueryNcDataModel queryNcDataModel = new QueryNcDataModel(); queryNcDataModel.ncLatLonModel = ncLatLonModel; queryNcDataModel.StartRow = minLatIndex; queryNcDataModel.StartColumn = minLonIndex; queryNcDataModel.EndRow = maxLatIndex; queryNcDataModel.EndColumn = maxLonIndex; queryNcDataModel.RowCount = maxLatIndex - minLatIndex + 1; queryNcDataModel.ColumnCount = maxLonIndex - minLonIndex + 1; queryNcDataModel.Dir = ncFile.GetValueInArea(models[0].Dir, minLatIndex, minLonIndex, queryNcDataModel.RowCount, queryNcDataModel.ColumnCount); queryNcDataModel.Value = ncFile.GetValueInArea(models[0].Value, minLatIndex, minLonIndex, queryNcDataModel.RowCount, queryNcDataModel.ColumnCount); queryNcDataModel.Levels = CoreUtil.GetLEVEL(queryNcDataModel.RowCount, queryNcDataModel.ColumnCount, 6); GFSWeatherJson gfsjson = new GFSWeatherJson(); string json = gfsjson.createGeoJsonFromNetcdf(queryNcDataModel, int.Parse(zoom)); return(json); }
public static async Task Initialize(SQLiteControl command) { Temporaries = new StatefulModel.SortedObservableCollection <TNicoTemporary, DateTime>( await command.SelectNicoTemporary(), x => x.Date, true ); Histories = new StatefulModel.SortedObservableCollection <VNicoHistory, DateTime>( await command.SelectNicoHistory(), x => x.Date, true ); Favorites = new StatefulModel.SortedObservableCollection <TNicoFavorite, DateTime>( await command.SelectNicoFavorite(), x => x.Date, true ); var combo = XDocument.Load(CoreUtil.RelativePathToAbsolutePath(NicoComboPath)).Root; Combos = combo.Descendants("combo") .SelectMany(xml => { return(xml.Descendants("item") .Select(tag => new ComboboxItemModel( (string)xml.Attribute("group"), (string)tag.Attribute("value"), (string)tag.Attribute("display") ))); }) .ToArray(); }
public FaceInfo[] GetFaceInfo(IEnumerable <Face> DetectedFaces, IEnumerable <Emotion> DetectedEmotion, IEnumerable <IdentifyResult> IdentifiedPersons) { List <FaceInfo> faceInfoList = new List <FaceInfo>(); if (DetectedFaces != null) { foreach (var detectedFace in DetectedFaces) { FaceInfo faceInfo = new FaceInfo(); // Check if we have age/gender for this face. if (detectedFace?.FaceAttributes != null) { faceInfo.Attributes = detectedFace.FaceAttributes; } // Check if we identified this face. If so send the name along. if (IdentifiedPersons != null) { var matchingPerson = IdentifiedPersons.FirstOrDefault(p => p.FaceId == detectedFace.FaceId); string name; if (matchingPerson != null && matchingPerson.Candidates.Length > 0 && personMap.TryGetValue(matchingPerson.Candidates[0].PersonId, out name)) { faceInfo.Name = name; } } // Check if we have emotion for this face. If so send it along. if (DetectedEmotion != null) { Emotion matchingEmotion = CoreUtil.FindFaceClosestToRegion(DetectedEmotion, detectedFace.FaceRectangle); if (matchingEmotion != null) { faceInfo.Emotion = matchingEmotion.Scores; } } //// Check if we have an unique Id for this face. If so send it along. //if (SimilarFaceMatches != null) //{ // var matchingPerson = SimilarFaceMatches.FirstOrDefault(p => p.Face.FaceId == detectedFace.FaceId); // if (matchingPerson != null) // { // faceInfo.UniqueId = matchingPerson.SimilarPersistedFace.PersistedFaceId.ToString("N").Substring(0, 4); // } //} faceInfoList.Add(faceInfo); } } else if (DetectedEmotion != null) { // If we are here we only have emotion. No age/gender or id. faceInfoList.AddRange(DetectedEmotion.Select(emotion => new FaceInfo { Emotion = emotion.Scores })); } return(faceInfoList.ToArray()); }
/// <summary> /// Calculates number of occurrences of each word listed in keywords Meta Tag. /// </summary> /// <returns>Dictionary of each word listed in keywords meta tags.</returns> public override Dictionary <string, int> CalculateOccuranceInMetaTag() { if (IsFilterStopWords && stopwordDictionary == null) { stopwordDictionary = CoreUtil.ProcessStopWords(StopWords); } if (htmlPage == null) { var htmlWeb = new HtmlWeb(); var lastStatusCode = HttpStatusCode.OK; htmlWeb.PostResponse = (request, response) => { if (response != null) { lastStatusCode = response.StatusCode; } }; htmlPage = htmlWeb.Load(Input); if (lastStatusCode != HttpStatusCode.OK) { throw new Exception($"{Constant.WEB_REQUEST_ERROR_MESSAGE} {lastStatusCode}"); } } var metaTagCollection = htmlPage.DocumentNode.SelectNodes("//meta"); return(CoreUtil.ProcessMetaTag(metaTagCollection, stopwordDictionary, allWordDictionary)); }
public SettingsManager(GeneralSettings settings) { _settings = settings ?? throw new ArgumentNullException(nameof(settings)); On <SetLanguageEvent>(e => { if (_settings.Language == e.Language) { return; } _settings.Language = e.Language; }); On <SetMusicVolumeEvent>(e => _settings.MusicVolume = e.Value); On <SetFxVolumeEvent>(e => _settings.FxVolume = e.Value); On <SetCombatDelayEvent>(e => _settings.CombatDelay = e.Value); On <DebugFlagEvent>(e => { _settings.DebugFlags = (DebugFlags)CoreUtil.UpdateFlag((uint)_settings.DebugFlags, e.Operation, (uint)e.Flag); TraceAttachment = (_settings.DebugFlags & DebugFlags.TraceAttachment) != 0; }); On <SpecialEvent>(e => _settings.Special1 = CoreUtil.UpdateValue(_settings.Special1, e.Operation, e.Argument)); On <Special2Event>(e => _settings.Special2 = CoreUtil.UpdateValue(_settings.Special2, e.Operation, e.Argument)); On <EngineFlagEvent>(e => _settings.Flags = (EngineFlags)CoreUtil.UpdateFlag((uint)_settings.Flags, e.Operation, (uint)e.Flag)); }
/// <summary> /// 根据eSight返回的状态,返回更新到数据库的状态。 /// </summary> /// <param name="oldStatus">旧的数据库状态</param> /// <param name="taskStatus">eSight返回的taskStatus</param> /// <param name="taskResult">eSight返回的taskResult</param> /// <param name="taskCode">eSight返回的taskCode</param> /// <returns>判断后的任务状态</returns> private string GetTaskStatus(string oldStatus, string taskStatus, string taskResult, string taskCode) { if (taskResult == "Failed") { return(ConstMgr.HWESightTask.SYNC_STATUS_HW_FAILED); } if (CoreUtil.GetObjTranNull <int>(taskCode) != 0) { return(ConstMgr.HWESightTask.SYNC_STATUS_HW_FAILED); } if (taskResult == "Success") { return(ConstMgr.HWESightTask.SYNC_STATUS_FINISHED); } if (taskStatus == "Complete") { return(ConstMgr.HWESightTask.SYNC_STATUS_FINISHED); } if (taskStatus == "Running") { return(ConstMgr.HWESightTask.SYNC_STATUS_CREATED); } return(oldStatus); }
public Image <Rgba32> ToImage(int subImage, uint[] palette) { GetSubImageOffset(subImage, out var width, out var height, out var offset, out var stride); Rgba32[] rgbaPixels = new Rgba32[width * height]; unsafe { fixed(Rgba32 *pixelPtr = rgbaPixels) { ReadOnlySpan <byte> fromSlice = TextureData.Slice(offset, width + (height - 1) * stride); var from = new ReadOnlyByteImageBuffer((uint)width, (uint)height, (uint)stride, fromSlice); Span <uint> toBuffer = new Span <uint>((uint *)pixelPtr, rgbaPixels.Length); var to = new UIntImageBuffer((uint)width, (uint)height, width, toBuffer); CoreUtil.Blit8To32(from, to, palette, 255, 0); } } Image <Rgba32> image = new Image <Rgba32>(width, height); image.Frames.AddFrame(rgbaPixels); image.Frames.RemoveFrame(0); return(image); }
public void GetObjTranNullTestInt1() { int testNum = 123; string testStr = "123aa"; Assert.AreNotEqual(CoreUtil.GetObjTranNull <int>(testStr), testNum); }
/// <summary> /// /// </summary> public int GetMinDepth() { var q0 = new Queue <Node>(); var q1 = new Queue <Node>(); int depth = 0; q0.Enqueue(_root); while (true) { // iterate through nodes at the current depth and return if leaf is found while (q0.Count > 0) { var node = q0.Dequeue(); if (node.IsLeaf) { return(depth); } q1.Enqueue(node.Left); q1.Enqueue(node.Right); } // swap queues and continue on the next level CoreUtil.Swap(ref q0, ref q1); depth++; } }
//打开文件 private void openFile() { Console.WriteLine("打开文件"); //获取已打开文件的字节数组 byte[] arr = FileUtil.readFile(filePath); //解码成字符串 string text = CoreUtil.decode(arr); //在显示文本之前,调整warning限制字符数 while (warning < text.Length) { warning *= 2; } //显示文本 textArea.Text = text; textArea.SelectionLength = 0; textArea.SelectionStart = 0; //由于文本区域有改动,需要消掉标题的“*”和状态栏的“未保存” if (this.Text[0] == '*') { this.Text = this.Text.Substring(1, this.Text.Length - 1); } ////已经改动置为false modified = false; statusLabelStatus.Text = "已保存"; //改变标题 this.Text = Path.GetFileName(filePath) + " - " + Program.APP_NAME; }
public void ProcessMetaTag_WithDifferentMetaTagsInHtml_WithEmptyWordDictionary_ReturnDictionaryOfMetaTagWithZeorOccurence(string html) { //arrange var stopwordDictionary = new Dictionary <string, int>(StringComparer.InvariantCultureIgnoreCase); var allWordDictionary = new Dictionary <string, int>(StringComparer.InvariantCultureIgnoreCase); var expected = new Dictionary <string, int>(StringComparer.InvariantCultureIgnoreCase) { { "hello", 0 }, { "world", 0 }, { "happy", 0 }, { "coding", 0 }, { "start", 0 }, { "today", 0 } }; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//meta"); //act var actual = CoreUtil.ProcessMetaTag(nodes, stopwordDictionary, allWordDictionary); //assert Assert.AreEqual(actual, expected); }
/// <summary> /// Calculates number of external links in a webpage. /// </summary> /// <returns>Dictionary of external link.</returns> public override Dictionary <string, int> CalculateExternalLink() { if (htmlPage == null) { var htmlWeb = new HtmlWeb(); var lastStatusCode = HttpStatusCode.OK; htmlWeb.PostResponse = (request, response) => { if (response != null) { lastStatusCode = response.StatusCode; } }; htmlPage = htmlWeb.Load(Input); if (lastStatusCode != HttpStatusCode.OK) { throw new Exception($"{Constant.WEB_REQUEST_ERROR_MESSAGE} {lastStatusCode}"); } } var hrefNodeCollection = htmlPage.DocumentNode.SelectNodes("//a[@href]"); return(CoreUtil.ProcessExternalLink(hrefNodeCollection, Input)); }
internal static void SelectNodes(Node[] nodes) { if (!CoreUtil.CompareIList(UserDatabase.selection.nodes, nodes)) { Command.Execute(new NodeSelectionCommand(nodes)); } }
bool Run(DoScriptEvent doScriptEvent, Action continuation) { var assets = Resolve <IAssetManager>(); var mapManager = Resolve <IMapManager>(); var events = assets.LoadScript(doScriptEvent.ScriptId); if (events == null) { CoreUtil.LogError($"Could not load script {doScriptEvent.ScriptId}"); return(false); } var nodes = new EventNode[events.Count]; var chain = new EventChain(0); // Create, link and add all the nodes. for (ushort i = 0; i < events.Count; i++) { nodes[i] = new EventNode(i, events[i]); } for (ushort i = 0; i < events.Count - 1; i++) { nodes[i].Next = nodes[i + 1]; } for (ushort i = 0; i < events.Count; i++) { chain.Events.Add(nodes[i]); } var source = new EventSource(mapManager.Current.MapId, mapManager.Current.MapId.ToMapText(), TriggerTypes.Default); // TODO: Is there a better trigger type for this? var trigger = new TriggerChainEvent(chain, chain.FirstEvent, source); return(RaiseAsync(trigger, continuation) > 0); }
private void SetErrorCode(int errorCount, string innerErrorCode, string innerErrorModel, ref int errorCode, ref string errorModel) { if (errorCount == 1) { errorCode = CoreUtil.GetObjTranNull <int>(innerErrorCode); errorModel = innerErrorModel; } }
public void HCDeleteTest() { _esSession.Open(); JObject result = _esSession.HCDelete(ConstMgr.HWESightHost.URL_LOGIN); Console.WriteLine(result); Assert.AreEqual(CoreUtil.GetObjTranNull <int>(result.Property("code")), 0); }
public T[] GetValues <T>() { Debug.Assert(typeof(T).IsAssignableFrom(type), string.Format("Type mismatch, {0} : {1}.", typeof(T).Name, type.Name)); var a = persistentObject.values.Select(i => (T)CoreUtil.GetMemberValue(mMemberPath, i)).ToArray(); return(a); }
private async void ProcessingReadQueue() { while (this.isProcessingReadQueue) { await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => { try { if (!this.isReadQueue && RealtimeFixModel.ListImageDetect1.Count > 0) { LogWriter.GetInstance().Write(DateTime.Now.ToString("HH:mm:ss") + " Count ListImageDetect1: " + RealtimeFixModel.ListImageDetect1.Count + "\n\r"); this.isReadQueue = true; ImageAnalyzer imageAnalyzer; lock (RealtimeFixModel.ListFrame1) { imageAnalyzer = RealtimeFixModel.ListImageDetect1.Dequeue(); } await this.ProcessDetectFace(imageAnalyzer); imageAnalyzer = null; } //Nếu rảnh chuyển sang ghi Queue else if (!this.isReadQueue) { if (RealtimeFixModel.ListFrame1.Count > 0) { this.isReadQueue = true; CurrentFrameModel currentFrameModel; lock (RealtimeFixModel.ListFrame1) { currentFrameModel = RealtimeFixModel.ListFrame1.Dequeue(); } ImageAnalyzer imageAnalyzer1 = await this.cameraControl.CaptureFrameAsync(currentFrameModel); if (imageAnalyzer1 != null) { RealtimeFixModel.ListImageDetect1.Enqueue(imageAnalyzer1); } currentFrameModel = null; imageAnalyzer1 = null; this.isReadQueue = false; } } } catch (Exception ex) { this.isReadQueue = false; LogWriter.GetInstance().Write(DateTime.Now.ToString("HH:mm:ss") + " ProcessingReadQueue: " + ex.Message + "\n\r"); } CoreUtil.FreeMemory(); }); await Task.Delay(TimeRead); } }
private async void ProcessCurrentVideoFrame(DispatcherTimer timer) { if (captureManager.CameraStreamState != Windows.Media.Devices.CameraStreamState.Streaming) { return; } if (!await frameProcessingSemaphore.WaitAsync(250)) { return; } try { IEnumerable <DetectedFace> faces = null; // Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case). // GetPreviewFrame will convert the native webcam frame into this format. const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Nv12; using (VideoFrame previewFrame = new VideoFrame(InputPixelFormat, (int)this.videoProperties.Width, (int)this.videoProperties.Height)) { await this.captureManager.GetPreviewFrameAsync(previewFrame); // The returned VideoFrame should be in the supported NV12 format but we need to verify this. if (FaceDetector.IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap.BitmapPixelFormat)) { faces = await this.faceTracker.ProcessNextFrameAsync(previewFrame); if (this.FilterOutSmallFaces) { // We filter out small faces here. faces = faces.Where(f => CoreUtil.IsFaceBigEnoughForDetection((int)f.FaceBox.Height, (int)this.videoProperties.Height)); } this.NumFacesOnLastFrame = faces.Count(); if (this.EnableAutoCaptureMode) { this.UpdateAutoCaptureState(faces); } // Create our visualization using the frame dimensions and face results but run it on the UI thread. var previewFrameSize = new Windows.Foundation.Size(previewFrame.SoftwareBitmap.PixelWidth, previewFrame.SoftwareBitmap.PixelHeight); var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { this.ShowFaceTrackingVisualization(previewFrameSize, faces); }); } } } catch (Exception x) { Debug.WriteLine(x.Message); } finally { frameProcessingSemaphore.Release(); } }
/// <summary> /// Calculates number of occurrences of each word in a english text. /// </summary> /// <returns>Dictionary of each word.</returns> public override Dictionary <string, int> CalculateOccuranceInText() { if (IsFilterStopWords && stopwordDictionary == null) { stopwordDictionary = CoreUtil.ProcessStopWords(StopWords); } return(CoreUtil.ProcessInput(Input, stopwordDictionary)); }
public Face GetLastFaceAttributesForFace(BitmapBounds faceBox) { if (this.lastDetectedFaceSample == null || !this.lastDetectedFaceSample.Any()) { return(null); } return(CoreUtil.FindFaceClosestToRegion(this.lastDetectedFaceSample, faceBox)); }