internal override void requestData(DataProcessor dproc) { if (backend == null) { dproc.AddDatasource(name, rrdPath, dsName, consolFun); } else { dproc.AddDatasource(name, rrdPath, dsName, consolFun, backend); } }
public CommunicationHandler(TcpClient serverCon, IErrorHandler error, IInvokable invoke, INotifiable notify, ILobby lobby) { _errorHandler = error; _tcpClient = serverCon; _tcpClient.DataReceived += TcpClient_DataReceived; _tcpClient.Disconnected += TcpClient_Disconnnected; _tcpClient.Start(); _processor = new DataProcessor(invoke, notify, lobby); }
/** * заполнить данными списки для выгрузки * */ public void PrepareData(DataProcessor dp) { listSortament = dp.GetSortamentList(); listHimsostav = dp.GetHimsostavList(); listPostavka = dp.GetPostavkaList(); listGrupmater = dp.GetGrupmaterList(); listMater = dp.GetMaterList(); }
public PhoneDataController() { _sessionCtx = SessionContextProvider.GetSessionContext(); _dataProcessor = new DataProcessor(_sessionCtx.DataContext); _piWebClients = _dataProcessor.Consumers.Select(consumer => new PIWebClient(_sessionCtx.UserContext, consumer)).ToList(); _efClient = new PIWebClient(_sessionCtx.UserContext, null); }
/** * Creates graph from the corresponding {@link RrdGraphDef} object. * * @param gdef Graph definition * @throws IOException Thrown in case of I/O error * @throws RrdException Thrown in case of JRobin related error */ public RrdGraph(RrdGraphDef gdef) { this.gdef = gdef; signature = gdef.getSignature(); worker = new ImageWorker(100, 100); // Dummy worker, just to start with something try { createGraph(); } finally { worker.dispose(); worker = null; dproc = null; } }
private void btnRun_Click(object sender, RoutedEventArgs e) { DataProcessor dp = new DataProcessor(); SpectrXmlWriter sxw = new SpectrXmlWriter(env.OutputFile); sxw.PrepareData(dp); sxw.MakeXml(); sxw.UploadSortament(); sxw.UploadGrupmater(); sxw.UploadHimsostav(); sxw.UploadPostavka(); MessageBox.Show("Выгружено!"); }
public virtual void resolveText(DataProcessor dproc, ValueScaler valueScaler) { resolvedText = text; marker = ""; if (resolvedText != null) { foreach (String mark in RrdGraphConstants.MARKERS) { if (resolvedText.EndsWith(mark)) { marker = mark; resolvedText = resolvedText.Substring(0, resolvedText.Length - marker.Length); trimIfGlue(); break; } } } enabled = resolvedText != null; }
public override void resolveText(DataProcessor dproc, ValueScaler valueScaler){ base.resolveText(dproc, valueScaler); if (resolvedText != null) { double value = dproc.GetAggregate(srcName, consolFun); Match matcher = UNIT_PATTERN.Match(resolvedText); if (matcher.Success) { // unit specified ValueScaler.Scaled scaled = valueScaler.scale(value, matcher.Groups[2].Equals("s")); resolvedText = resolvedText.Substring(0, matcher.Index) + matcher.Groups[1] + scaled.unit + resolvedText.Substring(matcher.Index + matcher.Length); value = scaled.value; } resolvedText = String.Format(resolvedText, value); trimIfGlue(); } }
public void DescerializrJsonFeed_Success() { const string jsonData = @"{""TimeSlots"":[{""Id"":8,""StartTime"":""8:00 AM"",""EndTime"":""9:00 AM""}], ""Speakers"":[{""Id"":65,""Name"":""Peter Parker"",""Bio"":""Peter is a superhero."",""ImageUrl"":""image1""},], ""Sessions"":[{""Id"":74,""Name"":""Session Name"",""Abstract"":""Session Abstract"",""SpeakerIds"":[65],""TimeSlotId"":8,""TrackId"":30,""Tags"":[]}], ""Sponsors"":[{""Id"":16,""Name"":""Sponsor Name"",""Description"":""Sponsor Description"",""LogoUrl"":""image2"",""URL"":""url Address"",""SponsorType"":""Inactive""}]}"; var processor = new DataProcessor(); var result = processor.DescerializeJsonFeed(jsonData); Assert.That(result, Is.Not.Null); Assert.That(result.TimeSlots.Count, Is.EqualTo(1)); Assert.That(result.Speakers.Count, Is.EqualTo(1)); Assert.That(result.Sessions.Count, Is.EqualTo(1)); Assert.That(result.Sponsors.Count, Is.EqualTo(1)); Assert.That(result.TimeSlots[0].Id, Is.EqualTo(8)); Assert.That(result.Speakers[0].Name, Is.EqualTo("Peter Parker")); Assert.That(result.Sessions[0].Id, Is.EqualTo(74)); Assert.That(result.Sponsors[0].Description, Is.EqualTo("Sponsor Description")); }
static DataProcessorUtility() { System.Type dataProcessorBaseType = typeof(DataProcessor); Assembly assembly = Assembly.GetExecutingAssembly(); System.Type[] types = assembly.GetTypes(); for (int i = 0; i < types.Length; i++) { if (!types[i].IsClass || types[i].IsAbstract) { continue; } if (dataProcessorBaseType.IsAssignableFrom(types[i])) { DataProcessor dataProcessor = (DataProcessor)Activator.CreateInstance(types[i]); foreach (string typeString in dataProcessor.GetTypeStrings()) { s_DataProcessors.Add(typeString.ToLower(), dataProcessor); } } } }
private EvaluationResult DumpData(Context context, ModuleLiteral env, EvaluationStackFrame args) { var pathTable = context.FrontEndContext.PathTable; var data = Args.AsIs(args, 0); string dataAsString = null; switch (data) { case string s: dataAsString = s; break; case IImplicitPath pathData: dataAsString = pathData.Path.ToString(context.PathTable); break; case PathAtom pathAtom: dataAsString = pathAtom.ToString(context.StringTable); break; case RelativePath relativePath: dataAsString = relativePath.ToString(context.StringTable); break; case int n: dataAsString = n.ToString(CultureInfo.InvariantCulture); break; default: // This is effectively only for object literals // Slow path dataAsString = DataProcessor.ProcessData(context.StringTable, m_dataSeparator, m_dataContents, context.FrontEndContext.PipDataBuilderPool, EvaluationResult.Create(data), new ConversionContext(pos: 1)).ToString(context.PathTable); break; } return(EvaluationResult.Create(dataAsString)); }
public async Task <bool> UpdateDataProcessor(DataProcessor model) { var existing = await _context.DataProcessors.Include(p => p.Contacts) .SingleOrDefaultAsync(m => m.ID == model.ID); if (existing == null) { return(false); } _context.Entry(existing).CurrentValues.SetValues(model); //remove contacts that have been deleted foreach (var existingContact in existing.Contacts) { if (model.Contacts.All(c => c.Id != existingContact.Id)) { _context.Contacts.Remove(existingContact); } } //add or update new contacts foreach (var newContact in model.Contacts) { var current = existing.Contacts.SingleOrDefault(c => c.Id == newContact.Id); if (current != null) { _context.Entry(current).CurrentValues.SetValues(newContact); } else { existing.Contacts.Add(newContact); } } //TODO check if try catch (here or later) await _context.SaveChangesAsync(); return(true); }
static DataProcessorUtility() { System.Type dataProcessorBaseType = typeof(DataProcessor); System.Type[] types = Utility.Assembly.GetTypes(DataProcessorAssemblyNames); for (int i = 0; i < types.Length; i++) { if (!types[i].IsClass || types[i].IsAbstract) { continue; } if (dataProcessorBaseType.IsAssignableFrom(types[i])) { DataProcessor dataProcessor = (DataProcessor)Activator.CreateInstance(types[i]); if (dataProcessor.ContentType == ContentType.Value) { s_DataProcessors.Add(dataProcessor.LanguageKeyword.ToLower(), dataProcessor); dataProcessor = (DataProcessor)Activator.CreateInstance(types[i]); dataProcessor.IsList = true; s_DataProcessors.Add(Const.ListTypePrefix + dataProcessor.LanguageKeyword.ToLower(), dataProcessor); } else if (dataProcessor.ContentType == ContentType.ID) { s_DataProcessors.Add(Const.IDSign, dataProcessor); } else if (dataProcessor.ContentType == ContentType.Comment) { s_DataProcessors.Add(Const.CommentSign, dataProcessor); s_DataProcessors.Add("", dataProcessor); } } } }
private void SendButtonClicked(object sender, EventArgs e) { // Check if there are files currently queued if (CurrentSelectedFiles.Count <= 0) { return; } // And the transfer processe(s) are not currently running. // The button is supposed to gray out when this is true, but you never know if (_GUIState == GUIState.TransfersRunning) { return; } List <LocalFileStructure> fList = new List <LocalFileStructure>(); // Sift through the files to see if there are some waiting to be sent for (int i = 0; i < CurrentSelectedFiles.Count; i++) { if (CurrentSelectedFiles[i].CurrentState == FileStatus.Inactive) { fList.Add(CurrentSelectedFiles[i].FileStructLocal); } } if (TransferType == FileTransferType.Local) { DataProcessor.SendFiles(fList, targetDevice.EndPoint); return; } if (TransferType == FileTransferType.Online) { StartOnlineUpload(); } }
public static void Main(string[] args) { var method = typeof(FileStream).GetMethod("Init", BindingFlags.Instance | BindingFlags.NonPublic); var body = MethodBody.Read(method, true); body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldarg_1)); var debugWriteLineMethod = typeof(Debug).GetMethod("WriteLine", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null); body.Instructions.Insert(1, Instruction.Create(OpCodes.Call, debugWriteLineMethod)); Console.WriteLine(body); var parameterTypes = new [] { method.DeclaringType }.Concat(method.GetParameters().Select(p => p.ParameterType)).ToArray(); var del = body.CreateDelegate(method.ReturnType, parameterTypes); Action unhook; if (!MethodUtil.HookMethod(method, del.Method, out unhook)) { throw new InvalidOperationException("Unable to hook method"); } File.WriteAllText(@"c:\temp\test.txt", "test"); using (var mock = new Mock <int, int[]>(x => DataReader.Read(x))) { //mock.Set(MockedMethod); mock.Set(x => { if (x == 42) { return new[] { 1, 4, 7, 8 } } ; throw new InvalidOperationException(); }); var dataProcessor = new DataProcessor(); Assert.AreEqual(5, dataProcessor.FindAverage(42)); } }
private void SendAllFilesButtonClick(object sender, EventArgs e) { // Check if there are files currently queued if (FileDisplayList.Count <= 0) { return; } // And the transfer processe(s) are not currently running. // The button is supposed to gray out when this is true, but you never know if (_GUIState == GUIState.TransfersRunning) { return; } UploadList = new List <LocalFileStructure>(); //Sift through the files to see if there are some waiting to be sent for (int i = 0; i < FileDisplayList.Count; i++) { if (FileDisplayList[i].FileStructure.FileStatus == FileStatus.Inactive || FileDisplayList[i].FileStructure.FileStatus == FileStatus.QueuedForDownload) { FileDisplayList[i].FileStructure.FileStatus = FileStatus.QueuedForDownload; UploadList.Add(FileDisplayList[i].FileStructure); } } if (UploadList.Count > 0) { ChangeGuiState(GUIState.TransfersRunning); DataProcessor.SendFiles(UploadList, SelectedNetworkDevice.EndPoint); } }
private async void Button3_Click(object sender, EventArgs e) { var newStatusTitle = textBox1.Text; var newStatusCode = textBox2.Text; var newStatusParentId = textBox3.Text; var newStatusKeysWords = textBox4.Text; if (!string.IsNullOrEmpty(newStatusTitle) && !string.IsNullOrEmpty(newStatusCode)) { var newStatusError = new StatusError() { StatusCode = Convert.ToInt32(newStatusCode), StatusTitle = newStatusTitle, }; if (!string.IsNullOrEmpty(newStatusParentId)) { newStatusError.SubStatusId = ObjectId.Parse(newStatusParentId); } if (!string.IsNullOrEmpty(newStatusKeysWords)) { var arr = newStatusKeysWords.Split(','); newStatusError.KeyWords = new BsonArray(arr); } await DataProcessor.SaveStatusErrorIntoDb(newStatusError); LoadDataToList(); textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); } }
public void AddProduct(Product Pr) { //IEnumerable<IEnumerable<Product>> products = DataProcessor.LoadJson<IEnumerable<Product>>(Tools.Utils.ProductsPath); IEnumerable <IEnumerable <Product> > products = DataProcessor.LoadJson <IEnumerable <Product> >(null); IEnumerable <Product> filteredProducts = new List <Product>(); filteredProducts = products.SelectMany(iepr => iepr.Where(Prod => Prod.Name == Pr.Name && Prod.PriceUnit == Pr.PriceUnit && Prod.Category == Pr.Category && Prod.Shop == Pr.Shop)); ScannedProduct pr = new ScannedProduct() { Shop = Pr.Shop, Name = Pr.Name, PriceUnit = Pr.PriceUnit, Price = Convert.ToDouble(Pr.Price), Id = (from fil in filteredProducts select fil.Id).First() }; ProductEditor.AddProducts(pr); }
public List <double> LoginWithEncryptedData(List <double> encryptedLoginData) //receives encrypted json string { try { JObject credentials = JObject.Parse(MatrixCryptography.Decrypt(encryptedLoginData)); string macAddress = credentials["mac_address"].ToString(); string password = credentials["password"].ToString(); bool isDataSourceFromCookie = bool.Parse(credentials["from_cookie"].ToString()); Output.ShowLog("LoginWithEncryptedData() => " + macAddress + " Credentials from cookie? " + isDataSourceFromCookie); if (isDataSourceFromCookie && Time.TimeDistanceInMinute(new Time(credentials["last_login_time"].ToString()), Time.CurrentTime) > 4320) { return(DataProcessor.ProcessLoggedInUserData(null)); } User loggedInUser = ClientManager.Instance.RegisterLoggedInUser(macAddress, password); return(DataProcessor.ProcessLoggedInUserData(loggedInUser)); } catch (Exception ex) { Output.ShowLog(ex.Message); return(null); } }
private void button1_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txt_username.Text) || String.IsNullOrEmpty(txt_password.Text)) { MessageBox.Show("Upišite korisničko ime i lozinku"); return; } var clas = new DataProcessor(); var response = clas.ProccesData(txt_username.Text, txt_password.Text, 1); if (response == "") { MessageBox.Show("Krivo korisničko ime ili lozinka"); } else { this.Hide(); MainForm mainF = new MainForm(); mainF.FormClosed += new FormClosedEventHandler(MainForm_FormClosing); mainF.IsMdiContainer = true; mainF.Show(); } }
static void Main(string[] args) { SearchSection Config = (SearchSection)ConfigurationManager.GetSection("searches"); string action = Console.ReadLine(); if (action != String.Empty) { Analyzer analyzer = new StandardAnalyzer(); IndexSearcher searcher = new IndexSearcher(Config.Searches["product"].IndexDirectory); MultiFieldQueryParser parserName = new MultiFieldQueryParser(new string[] { "productname", "keywords", "description" }, analyzer); Query queryName = parserName.Parse("三星"); Query queryCategory = new WildcardQuery(new Term("catepath", "*82*")); //Query queryCategory = parserCategory.Parse("82"); BooleanQuery bQuery = new BooleanQuery(); bQuery.Add(queryName, BooleanClause.Occur.MUST); bQuery.Add(queryCategory, BooleanClause.Occur.MUST); Hits hits = searcher.Search(bQuery); for (int i = 0; i < hits.Length(); i++) { Document d = hits.Doc(i); Console.WriteLine(d.Get("productname")); } } else { DataProcessor.Process("product"); Console.Read(); } }
public void CanProcessData() { // Positive cases string jsonInputCase1 = "{data:[{\"hello\" : 1}]}"; string jsonInputCase2 = "{data:[{\"userGroup\" : \"one,two\"}]}"; string jsonInputCase3 = "{\r\n \"status\": {\r\n \"code\": 200,\r\n \"text\": \"\",\r\n \"timeStamp\": \"2018-10-24T05:56:30+00:00\"\r\n },\r\n \"data\": [\r\n {\r\n \"success\": true,\r\n \"transactions\": [\r\n {\r\n \"id\": 1,\r\n \"type\": \"STARTUP\",\r\n \"user\": \"Cron\",\r\n \"timestamp\": \"2017-09-25 06:27:16\",\r\n \"price\": \"0.00\",\r\n \"discount\": \"0.00\",\r\n \"state\": \"ACTIVE\",\r\n \"site_Id\": 816899,\r\n \"accountId\": 1,\r\n \"expire\": \"2018-09-25 06:27:16\",\r\n \"startDate\": \"2017-09-25 06:27:16\",\r\n \"billingDate\": \"2018-09-25 06:27:16\",\r\n \"onExpiry\": \"RENEW\",\r\n \"apiId\": \"professional\",\r\n \"resellerId\": 86,\r\n \"userGroup\": \"professional,site_n,social,site_n,social\",\r\n \"code\": \"EUR\",\r\n \"currencyName\": \"Euro\"\r\n },\r\n {\r\n \"id\": 2,\r\n \"type\": \"RENEWAL\",\r\n \"user\": \"Cron\",\r\n \"timestamp\": \"2017-09-25 06:27:16\",\r\n \"price\": \"0.00\",\r\n \"discount\": \"0.00\",\r\n \"state\": \"ACTIVE\",\r\n \"site_Id\": 816899,\r\n \"accountId\": 1,\r\n \"expire\": \"2018-09-25 06:27:16\",\r\n \"startDate\": \"2017-09-25 06:27:16\",\r\n \"billingDate\": \"2018-09-25 06:27:16\",\r\n \"onExpiry\": \"RENEW\",\r\n \"apiId\": \"professional\",\r\n \"resellerId\": 86,\r\n \"userGroup\": \"professional,site_n,social,site_n,social\",\r\n \"code\": \"EUR\",\r\n \"currencyName\": \"Euro\"\r\n },\r\n {\r\n \"id\": 3,\r\n \"type\": \"STARTUP\",\r\n \"user\": \"Cron\",\r\n \"timestamp\": \"2017-09-25 06:28:20\",\r\n \"price\": \"0.00\",\r\n \"discount\": \"0.00\",\r\n \"state\": \"TERMINATED\",\r\n \"site_Id\": 816901,\r\n \"accountId\": 3,\r\n \"expire\": \"2018-09-25 06:28:20\",\r\n \"startDate\": \"2017-09-25 06:28:20\",\r\n \"billingDate\": \"2018-09-25 06:28:20\",\r\n \"onExpiry\": \"RENEW\",\r\n \"apiId\": \"professional\",\r\n \"resellerId\": 86,\r\n \"userGroup\": \"professional,site_n,social,site_n,social\",\r\n \"code\": \"EUR\",\r\n \"currencyName\": \"Euro\"\r\n },\r\n {\r\n \"id\": 4,\r\n \"type\": \"RENEWAL\",\r\n \"user\": \"Cron\",\r\n \"timestamp\": \"2017-09-25 06:28:20\",\r\n \"price\": \"0.00\",\r\n \"discount\": \"0.00\",\r\n \"state\": \"TERMINATED\",\r\n \"site_Id\": 816901,\r\n \"accountId\": 3,\r\n \"expire\": \"2018-09-25 06:28:20\",\r\n \"startDate\": \"2017-09-25 06:28:20\",\r\n \"billingDate\": \"2018-09-25 06:28:20\",\r\n \"onExpiry\": \"RENEW\",\r\n \"apiId\": \"professional\",\r\n \"resellerId\": 86,\r\n \"userGroup\": \"professional,site_n,social,site_n,social\",\r\n \"code\": \"EUR\",\r\n \"currencyName\": \"Euro\"\r\n },\r\n {\r\n \"id\": 5,\r\n \"type\": \"STARTUP\",\r\n \"user\": \"Cron\",\r\n \"timestamp\": \"2017-09-25 06:47:09\",\r\n \"price\": \"0.00\",\r\n \"discount\": \"0.00\",\r\n \"state\": \"TERMINATED\",\r\n \"site_Id\": 816902,\r\n \"accountId\": 4,\r\n \"expire\": \"2017-11-25 06:47:09\",\r\n \"startDate\": \"2017-09-25 06:47:09\",\r\n \"billingDate\": \"2017-11-25 06:47:09\",\r\n \"onExpiry\": \"TERMINATE\",\r\n \"apiId\": \"trial\",\r\n \"resellerId\": 191,\r\n \"userGroup\": \"trial\",\r\n \"code\": \"EUR\",\r\n \"currencyName\": \"Euro\"\r\n } ],\r\n \"meta\": {\r\n \"count\": 263,\r\n \"lastId\": 263\r\n }\r\n }\r\n ]\r\n}"; string expectedCase1 = "[{\r\n \t\"id\": 1,\r\n \t\"type\": \"STARTUP\",\r\n \t\"user\": \"Cron\",\r\n \t\"timestamp\": \"2017-09-25 06:27:16\",\r\n \t\"price\": \"0.00\",\r\n \t\"discount\": \"0.00\",\r\n \t\"state\": \"ACTIVE\",\r\n \t\"site_Id\": 816899,\r\n \t\"accountId\": 1,\r\n \t\"expire\": \"2018-09-25 06:27:16\",\r\n \t\"startDate\": \"2017-09-25 06:27:16\",\r\n \t\"billingDate\": \"2018-09-25 06:27:16\",\r\n \t\"onExpiry\": \"RENEW\",\r\n \t\"apiId\": \"professional\",\r\n \t\"resellerId\": 86,\r\n \t\"userGroup\": \"professional,site_n,social,site_n,social\",\r\n \t\"code\": \"EUR\",\r\n \t\"currencyName\": \"Euro\"\r\n }]"; //Processor need to adhere to interface segregation principle, to allow for processors to be stored in same collection. TransactionDataProcessor processor = new TransactionDataProcessor(); dynamic data1 = DataProcessor.ConvertDataToDynamicObject(jsonInputCase3); // Assert.AreEqual("{data:[{\"hello\" : 1}]}", jsonInputCase1); dynamic extractedData = processor.ExtractDataArray(data1); JArray datastr = processor.Process(extractedData); JToken ob = processor.Process(extractedData); //JsonConvert.DeserializeObject<List<RootObject>>(string); //Assert.AreEqual("", ob.ToString()); // JArray output = processor.Process(data1); }
private void openLOGSFilesToolStripMenuItem_Click(object sender, EventArgs e) { var listDoc = new List <string>(); var files = new OpenFileDialog(); files.Multiselect = true; files.Filter = @"LOGS Files (.log)|*.log"; if (files.ShowDialog() == DialogResult.OK) { textBox2PathFolder.Text = Path.GetDirectoryName(files.FileName); foreach (String file in files.FileNames.Where(d => d.Contains("Server"))) { var filter = Builders <BsonDocument> .Filter.Eq("FileName", file); var dt = DataProcessor.GetDataFind(filter, "LogsFiles", 0, Int32.MaxValue).Result; if (!dt.Any()) { listDoc.Add(file); } } var pars = new Parser(listDoc, this); } }
public void ProccessFile_InvalidData_RowsIgnoredIncrements() { // arrange string[] fileLines = new string[] { "1,sample Airport ", "1,sample Airport " }; int rowsIgnored = 0; mockFileParser.Setup(x => x.GetAllLinesFromFile(It.IsAny <string>())) .Returns(fileLines); mockService.Setup(x => x.SplitLine(It.IsAny <string>())) .Returns(new string[] { "1", "sample Airport" }); mockService.Setup(x => x.IsValid(It.IsAny <string[]>(), It.IsAny <string>())) .Returns(false); var dataProcessor = new DataProcessor(mockDataDAL.Object, mockDataInstantiator.Object, mockService.Object, mockLogger.Object, mockFileParser.Object); // act dataProcessor.ProccessFile(null, null, ref rowsIgnored); // assert Assert.AreEqual(fileLines.Length, rowsIgnored); }
private static void AddEnumType(ref List <DataProcessor> addList) { foreach (var assemblyName in AssemblyNames) { Assembly assembly = null; try { assembly = Assembly.Load(assemblyName); } catch { continue; } if (assembly == null) { continue; } var types = assembly.GetTypes(); foreach (var type in types) { if (type.IsEnum) { Type enumProcessorType = typeof(EnumProcessor <>).MakeGenericType(type); DataProcessor dataProcessor = (DataProcessor)Activator.CreateInstance(enumProcessorType); foreach (var typeString in dataProcessor.GetTypeStrings()) { s_DataProcessors.Add(typeString.ToLower(), dataProcessor); } addList.Add(dataProcessor); } } } }
private void GetOrder() { string orderUniqueNumber = txtOrderNumber.Text; if (orderUniqueNumber == "") { return; } try { var restClient = (OrdersRestClient)DataProcessor.GetRestClient("OrdersRestClient"); var ordersPayload = restClient.GetOrder(orderUniqueNumber).Payload as OrdersPayloadElement; _order = new OrderDecorator(ordersPayload.Orders[0]); RefreshOrder(); } catch (LogicalApiException e) { MessageBox.Show(String.Format("Ошибка. Код: {0}. Сообщение: {1}", e.Code, e.Message)); } catch (Exception ex) { MessageBox.Show(String.Format("Ошибка: {0}", ex.Message)); } }
public void Validate_Login() { string username = "******"; string password = "******"; int userId = 3; //postavljamo useru atribute jer će nam trebati prilikom poziva druge funkcije User user = new User { Id = 3, Password = "******", Username = "******" }; Person person = new Person(); var repository = new Mock <IUserRepository>(); repository.Setup(x => x.GetUserByUsernameAndPassword(username, password, 1)).Returns(user); repository.Setup(x => x.GetPersonFromUserId(userId)).Returns(person); DataProcessor processor = new DataProcessor(); processor.Repository = (IUserRepository)repository.Object; var res = processor.ProccesData(username, password, 1); repository.Verify(x => x.GetUserByUsernameAndPassword(username, password, 1), Times.Exactly(1)); }
public void GetTop10Makelaars_OK() { // Setup List <string> jsonContentPages = new List <string>(); jsonContentPages.Add(ResourceTestData.JsonResponseOK); jsonContentPages.Add(ResourceTestData.JsonResponseOK); jsonContentPages.Add(ResourceTestData.JsonResponseOK); jsonContentPages.Add(ResourceTestData.JsonResponseOK); jsonContentPages.Add(ResourceTestData.JsonResponseOK); fundaServiceAgentMock.Setup(x => x.GetSearchResultsPages(It.IsAny <string>())).Returns(jsonContentPages); var dataProcessor = new DataProcessor(fundaServiceAgentMock.Object); //// Execute var results = dataProcessor.GetTop10Makelaars("Amsterdam"); //// Test Assert.Equal(2, results.Count); Assert.Equal("11 Makelaars", results[0].Name); Assert.Equal("Admiraal makelaardij", results[1].Name); Assert.Equal(5, results[0].Count); Assert.Equal(5, results[1].Count); }
public void FinishedHandlerTest() { //This test will check if the Finished handler works correctly. Dictionary <int, Athlete> TestAthleteList = new Dictionary <int, Athlete>(); int BibNumber = 55; string FirstName = "Jim"; string LastName = "Jameson"; string Gender = "M"; int Age = 30; Athlete TestAthlete = new Athlete(BibNumber, FirstName, LastName, Gender, Age); //when added to List, TestAthlete's finish time is default value TestAthleteList.Add(BibNumber, TestAthlete); DateTime TestFinishTime = new DateTime(2017, 8, 15, 7, 00, 00); DataProcessor processor = new DataProcessor(); processor.ProcessorAthleteList = TestAthleteList; string line = $"Started,{BibNumber},{TestFinishTime},{TestFinishTime}"; var message = RaceData.Messages.AthleteUpdate.Create(line); processor.ProcessUpdate(message); //processor should change TestAthlete's start time Assert.AreEqual(TestAthleteList[55].StartTime, TestFinishTime); //check }
public DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage, string searchField = null, string searchTerm = null) { Record[] records = null; using (var oH = new ObjectHelper(DbSettings)) { StatusObject fetchStatus; if (searchField != null || searchTerm != null) { if (searchField.Equals("*")) { fetchStatus = oH.GetRecordsByGlobalSearch(_recordType, _searchValue, lowerPageBoundary, rowsPerPage); } else { fetchStatus = oH.GetRecordsByTypeSearch(_recordType, searchField, searchTerm, lowerPageBoundary, rowsPerPage); } if (fetchStatus.Success) { records = (Record[])fetchStatus.Result; } } else { fetchStatus = oH.GetRecordsByType(_recordType, lowerPageBoundary, rowsPerPage); if (fetchStatus.Success) { records = (Record[])fetchStatus.Result; } } } return(DataProcessor.FillRecordDataTable(_recordType, records)); }
internal DataSeriesObject(IDataSeries series, DateTime dateTime1, DateTime dateTime2, EventQueue queue, DataProcessor processor) { this.series = series; eventQueue = queue; if (processor == null) { this.processor = new DataProcessor(); } else { this.processor = processor; } if (!(dateTime1 == DateTime.MinValue) && (dateTime1 >= series.DateTime1)) { index1 = series.GetIndex(dateTime1, SearchOption.Next); } else { index1 = 0L; } if (!(dateTime2 == DateTime.MaxValue) && (dateTime2 <= series.DateTime2)) { index2 = series.GetIndex(dateTime2); } else { index2 = series.Count - 1L; } current = index1; progressDelta = (int)Math.Ceiling(Count() / 100.0); progressCount = progressDelta; progressPercent = 0; }
public void Process_ShouldAggregateItemsCorrectly_ForSingleProductInSingleWarehouse(IFixture fixture, string productId, int productQty, string warehouseName, DataProcessor sut) { // arrange var model = _modelBuilder(fixture, productId, new Dictionary <string, int> { { warehouseName, productQty } }) .Create(); // act var actual = sut.Process(new[] { model }); // assert actual.ShouldHaveSingleItem().WarehouseName.ShouldBe(warehouseName); actual.ShouldHaveSingleItem().TotalCount.ShouldBe(productQty); actual.ShouldHaveSingleItem().Items.ShouldHaveSingleItem().Id.ShouldBe(productId); actual.ShouldHaveSingleItem().Items.ShouldHaveSingleItem().Count.ShouldBe(productQty); }
/// <summary> /// Handler for the Window Client Download Data Complete event. Saves the historical data to a file /// </summary> /// <param name="sender">object - The WebClient</param> /// <param name="e">The data returned by the downloader.</param> private async void wClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { WebClient client = (WebClient)sender; var ticker = client.QueryString["symbol"]; DirectoryInfo dir = new DirectoryInfo(client.QueryString["OutputDirectory"]); string errorMessage = string.Empty; DataProcessor processor = new DataProcessor(); using (MemoryStream ms = new MemoryStream(e.Result)) { string historicalData = processor.processStreamMadeOfOneDayLinesToExtractHistoricalData(ms, out errorMessage); if (!String.IsNullOrEmpty(errorMessage)) { string message = $"{ticker} {DateTime.Now} Daily Ticker had an error. {errorMessage}"; logger.Log(message); } else { Console.WriteLine("D " + ticker); await SaveDataAsync(dir.FullName, historicalData, ticker); } } }
protected void SaveAsBmp(string path, Rectangle area, float normalization, float maxValue, DataProcessor.Abstract.DataStringProcessor processor, Behaviors.TileCreator.TileOutputType outputType, System.Drawing.Imaging.ColorPalette palette = null, Filters.ImageFilterProxy filter = null) { var destinationFileName = Path.ChangeExtension(path, ".bmp"); var padding = (area.Width % 4); padding = padding == 0 ? 0 : 4 - padding; //since bitmap width has to be multiple of 4 at all times, we have to add padding bytes var padBytes = new byte[padding]; int strDataLength = SourceFile.Width * SourceFile.Header.BytesPerSample; byte[] frameStrData = new byte[area.Width * SourceFile.Header.BytesPerSample]; float[] floatFrameStrData = new float[area.Width]; var bmpHeader = GetBitmapFileHeader(area.Width, area.Height, palette); using (var fr = System.IO.File.Open(SourceFile.Properties.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (var fw = System.IO.File.Open(destinationFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { long lineToStartSaving = (long)area.Y * (long)(SourceFile.Width * SourceFile.Header.BytesPerSample + SourceFile.Header.StrHeaderLength); long sampleToStartSaving = area.X * SourceFile.Header.BytesPerSample; long offset = lineToStartSaving + sampleToStartSaving; fr.Seek(SourceFile.Header.FileHeaderLength, SeekOrigin.Begin); fr.Seek(offset, SeekOrigin.Current); fw.Write(bmpHeader, 0, bmpHeader.Length); for (int i = 0; i < area.Height; i++) { OnProgressReport((int)((double)i / (double)area.Height * 100)); if (OnCancelWorker()) { fw.Flush(); return; } fr.Seek(SourceFile.Header.StrHeaderLength, SeekOrigin.Current); fr.Read(frameStrData, 0, frameStrData.Length); var processedData = processor.ProcessDataString(frameStrData); byte[] processedBytes = null; switch (outputType) { case Behaviors.TileCreator.TileOutputType.Linear: { processedBytes = processedData.AsParallel().Select(x => TileCreator.NormalizationHelpers.ToByteRange( TileCreator.NormalizationHelpers.GetLinearValue(x, normalization))).ToArray(); break; } case Behaviors.TileCreator.TileOutputType.Logarithmic: { processedBytes = processedData.AsParallel().Select(x => TileCreator.NormalizationHelpers.ToByteRange( TileCreator.NormalizationHelpers.GetLogarithmicValue(x, maxValue))).ToArray(); break; } case Behaviors.TileCreator.TileOutputType.LinearLogarithmic: { processedBytes = processedData.AsParallel().Select(x => TileCreator.NormalizationHelpers.ToByteRange( TileCreator.NormalizationHelpers.GetLinearLogarithmicValue(x, maxValue, normalization))).ToArray(); break; } default: break; } if (filter != null) { processedBytes = filter.Filter.ApplyFilters(processedBytes); } fw.Write(processedBytes, 0, floatFrameStrData.Length); fw.Write(padBytes, 0, padBytes.Length); fr.Seek(strDataLength - frameStrData.Length, SeekOrigin.Current); } } } }
private DataProcessor CreateDataProcessor(String rpnExpression) { var dataProcessor = new DataProcessor(request.FetchStart, request.FetchEnd); foreach (String dsName in dsNames) { dataProcessor.AddDatasource(dsName, this); } if (rpnExpression != null) { dataProcessor.AddDatasource(RPN_SOURCE_NAME, rpnExpression); try { dataProcessor.ProcessData(); } catch (IOException ioe) { // highly unlikely, since all datasources have already calculated values throw new InvalidOperationException("Impossible error: " + ioe); } } return dataProcessor; }
/// <summary> /// This method deletes the data stored in specified tags of the PI Data Archive /// To delete data, it is required to first read the values that you want to delete, and then /// Call the update values method with the AFUpdateOption.Remove option /// <remarks> /// </remarks> /// </summary> private void DeleteData() { try { ValidateParameters(); piConnectionMgr = new PiConnectionMgr(Server); piConnectionMgr.Connect(); PIServer server = piConnectionMgr.GetPiServer(); var timer = Stopwatch.StartNew(); // Gets the tags and creates a point list with the tags, to prepare for bulk read call var points = PIPoint.FindPIPoints(server, TagList); var pointList = new PIPointList(points); Logger.InfoFormat("Initialized PI Points for deletion: {0}", string.Join(", ", points.Select(p => p.Name))); // converts strings to AFTime objects this will throw an error if invalid var startTime = new AFTime(StartTime); var endTime = new AFTime(EndTime); if (startTime > endTime) throw new PIDeleteUtilInvalidParameterException("Start Time must be smaller than End Time"); // defines the data eraser task that will work in parallel as the data querying task dataEraser = new DataProcessor(EraseData); var eraseTask = Task.Run(() => dataEraser.Run()); // splits iterates the period, over foreach (var period in Library.Helpers.EachNDay(startTime, endTime, Days)) { Logger.InfoFormat("Getting tags information for period {0} to {1} ({2} Days chunk)", startTime, endTime, Days); // makes the first data call var data = pointList.RecordedValues(period, AFBoundaryType.Inside, null, false, new PIPagingConfiguration(PIPageType.TagCount, 100)); Logger.InfoFormat("Adding the data to the queue for deletion. ({0} to {1})", startTime, endTime); // we push this data into the data processor queue so we can continue to query for the rest of the data. dataEraser.DataQueue.Add(data); } dataEraser.DataQueue.CompleteAdding(); // // this will tell the data eraser that no more data will be added and allow it to complete eraseTask.Wait(); // waiting for the data processor to complete Logger.InfoFormat( "Deletion process completed in {0} seconds. With {1} events deleted (assuming there was no errors).", Math.Round(timer.Elapsed.TotalSeconds, 0), dataEraser.TotalEventProcessed); } catch (Exception ex) { Logger.Error(ex); } }
/// <summary> /// Fills the textBoxURL with data formated with DateTime or milliseconds in the first column /// </summary> /// <param name="dateFormat"></param> private void fillTextBoxWithProcessedData(string dateFormat) { // Stream from the downloaded Data using (MemoryStream ms = new MemoryStream(System.Text.Encoding.Default.GetBytes(downloadedData))) { DataProcessor dp = new DataProcessor(); string errorMessage; string resultValue; //processStreamOfOneMinuteBarsToReplaceGoogleDateWithFormatted if (radioButtonLastQuoute.Checked) { // Only display the last quote of the stream resultValue = dp.processStreamMadeOfOneMinuteBarsToExtractMostRecentOHLCVForCurrentDay(ms, out errorMessage); } else if (radioButtonMinutes.Checked) { // show minute data resultValue = dp.ProcessStreamOfOneMinuteBarsToReplaceGoogleDateWithFormatted(ms, dateFormat, out errorMessage); } else { // Show daily data resultValue = dp.processStreamMadeOfOneDayLinesToExtractHistoricalData(ms, out errorMessage); } // Show an error message or the processed data if (!String.IsNullOrEmpty(errorMessage)) { richTextBoxData.Text = errorMessage; ErrorFunction(errorMessage, new Exception(errorMessage)); } else { richTextBoxData.Text = resultValue; } } }
internal override void requestData(DataProcessor dproc) { dproc.AddDatasource(name, plottable); }
/// <summary> /// Initialize for a processing pass. /// </summary> public void start_pass(J_BUF_MODE pass_mode) { switch (pass_mode) { case J_BUF_MODE.JBUF_PASS_THRU: if (m_cinfo.m_upsample.NeedContextRows()) { m_dataProcessor = DataProcessor.context_main; make_funny_pointers(); /* Create the xbuffer[] lists */ m_whichFunny = 0; /* Read first iMCU row into xbuffer[0] */ m_context_state = CTX_PREPARE_FOR_IMCU; m_iMCU_row_ctr = 0; } else { /* Simple case with no context needed */ m_dataProcessor = DataProcessor.simple_main; } m_buffer_full = false; /* Mark buffer empty */ m_rowgroup_ctr = 0; break; case J_BUF_MODE.JBUF_CRANK_DEST: /* For last pass of 2-pass quantization, just crank the postprocessor */ m_dataProcessor = DataProcessor.crank_post; break; default: m_cinfo.ERREXIT(J_MESSAGE_CODE.JERR_BAD_BUFFER_MODE); break; } }
public void Ctor_When_ProductRepo_ISNull_ThrowsException() { _ = new DataProcessor(_mockRetailerProductRepository.Object, null); }
internal RpnCalculator(String rpnExpression, String sourceName, DataProcessor dataProcessor) { this.rpnExpression = rpnExpression; this.sourceName = sourceName; this.dataProcessor = dataProcessor; timestamps = dataProcessor.GetTimestamps(); timeStep = timestamps[1] - timestamps[0]; calculatedValues = new double[timestamps.Length]; String[] st = rpnExpression.Split(','); tokens = new Token[st.Length]; for (int i = 0; i < st.Length; i++) { tokens[i] = CreateToken(st[i]); } }
/// <summary> /// Process the downloaded minute data for one symbol and call the save method /// </summary> /// <param name="symbol">string - The symbols</param> /// <param name="singleLetterDirectoryInfo">DirectoryInfo - the folder to save minute files</param> private async Task ProcessAndSaveMinuteDataByDay(MemoryStream ms, string symbol, DirectoryInfo singleLetterDirectoryInfo) { DataProcessor dp = new DataProcessor(); string errorMessage; string resultValue = dp.ProcessStreamOfOneMinuteBarsToReplaceGoogleDateWithFormatted(ms, "Millisecond", out errorMessage); if (!String.IsNullOrEmpty(errorMessage)) { string message = $"{symbol} {DateTime.Now} Minute Symbol had an error. {errorMessage}"; logger.Log(message); } Console.WriteLine("M " + symbol); await SaveDataAsync(singleLetterDirectoryInfo.FullName, resultValue, symbol); }
public void Process_ShouldAggregateItemsCorrectly_ForMultipleProductsInMultipleWarehouses(IFixture fixture, string product1Id, string product2Id, string wh1Name, string wh2Name, string wh3Name, DataProcessor sut) { // arrange var modelA = _modelBuilder(fixture, product1Id, new Dictionary <string, int> { { wh1Name, 2 }, { wh2Name, 3 }, { wh3Name, 1 } }) .Create(); var modelB = _modelBuilder(fixture, product2Id, new Dictionary <string, int> { { wh1Name, 5 }, { wh2Name, 6 } }) .Create(); var models = new[] { modelA, modelB }; // act var actual = sut.Process(models); // assert actual.ShouldNotBeNull(); actual.Count().ShouldBe(3); actual.ShouldContain(g => wh1Name.Equals(g.WarehouseName) && g.TotalCount == 7 && g.Items.Count() == 2 && g.Items.SingleOrDefault(i => product1Id.Equals(i.Id) && i.Count == 2) != null && g.Items.SingleOrDefault(i => product2Id.Equals(i.Id) && i.Count == 5) != null); actual.ShouldContain(g => wh2Name.Equals(g.WarehouseName) && g.TotalCount == 9 && g.Items.Count() == 2 && g.Items.SingleOrDefault(i => product1Id.Equals(i.Id) && i.Count == 3) != null && g.Items.SingleOrDefault(i => product2Id.Equals(i.Id) && i.Count == 6) != null); actual.ShouldContain(g => wh3Name.Equals(g.WarehouseName) && g.TotalCount == 1 && g.Items.Count() == 1 && product1Id.Equals(g.Items.ShouldHaveSingleItem().Id) && g.Items.ShouldHaveSingleItem().Count == 1); }
//public Component DisplayController //{ // get { return displayController; } // set { displayController = value; } //} //public Component AudioController //{ // get { return audioController; } // set { audioController = value; } //} public MedicalServer(GraphControl graphControl) : base(graphControl) { this.IsCompositeComponnet = true; //MedicalServer为复合组件 //this.bmp = new Bitmap(@"..\..\..\picture\MedicalServer.png"); this.bmp = Resource1.MedicalServer; this.Text = "MedicalServer"; this.Rectangle = new RectangleF(400, 300, 84, 56); //设置组件位置及大小 this.name = "MedicalServer"; //创建MedicalServer组件端口并显示 this.input_ports = new Input_port[1]; //组件input端口数组 this.output_ports = new Output_port[1]; //组件output端口数组 this.input_ports[0] = new Input_port((this.ID + "_P1"), this.name + "Port", "input", "String", this); this.output_ports[0] = new Output_port((this.ID + "_P2"), this.name + "Port", "output", "String", this); int input_port_LocationX = (int)(this.Location.X); int input_ports_LocationY = (int)(this.Location.Y + 1 * (this.Height / (1 + 1)) - input_ports[0].Height / 2); int output_port_LocationX = (int)(this.Location.X + this.Width - 2); int output_ports_LocationY = (int)(this.Location.Y + 1 * (this.Height / (1 + 1)) - output_ports[0].Height / 2); input_ports[0].Rectangle = new RectangleF(input_port_LocationX, input_ports_LocationY, 15, 15); output_ports[0].Rectangle = new RectangleF(output_port_LocationX, output_ports_LocationY, 15, 15); this.graphControl.AddShape(input_ports[0], new Point(input_port_LocationX, input_ports_LocationY)); this.graphControl.AddShape(output_ports[0], new Point(output_port_LocationX, output_ports_LocationY)); //创建WiredModule组件 this.wiredModule = new WiredModule(null, null, null, null); this.wiredModule.Mac_address = wiredModule_mac_address; //创建WiredModule组件端口 this.wiredModule.input_ports = new Input_port[1]; this.wiredModule.input_ports[0] = new Input_port(this.wiredModule.ID + "_P1", this.wiredModule.name + "Port", "input", "string", this.wiredModule); this.wiredModule.output_ports = new Output_port[1]; this.wiredModule.output_ports[0] = new Output_port(this.wiredModule.ID + "_P2", this.wiredModule.name + "Port", "output", "string", this.wiredModule); //创建MyBuffer组件 this.myBuffer = new MyBuffer(null, null, null, null); //创建MyBuffer组件端口 this.myBuffer.input_ports = new Input_port[1]; this.myBuffer.input_ports[0] = new Input_port(this.myBuffer.ID + "_P1", this.myBuffer.name + "Port", "input", "string", this.myBuffer); this.myBuffer.output_ports = new Output_port[1]; this.myBuffer.output_ports[0] = new Output_port(this.myBuffer.ID + "_P2", this.myBuffer.name + "Port", "output", "string", this.myBuffer); //创建DataProcessor组件 this.dataProcessor = new DataProcessor(null, null, null, null); this.dataProcessor.IPv6_address1 = Server_IPv6_address; //创建DataProcessor组件端口 this.dataProcessor.input_ports = new Input_port[1]; this.dataProcessor.input_ports[0] = new Input_port(this.dataProcessor.ID + "_P1", this.dataProcessor.name + "Port", "input", "string", this.dataProcessor); this.dataProcessor.output_ports = new Output_port[1]; this.dataProcessor.output_ports[0] = new Output_port(this.dataProcessor.ID + "_P2", this.dataProcessor.name + "Port", "output", "string", this.dataProcessor); //创建DataAnalyzer组件 this.dataAnalyzer = new DataAnalyzer(null, null, null, null); //创建DataAnalyzer组件端口 this.dataAnalyzer.input_ports = new Input_port[1]; this.dataAnalyzer.input_ports[0] = new Input_port(this.dataAnalyzer.ID + "_P1", this.dataAnalyzer.name + "Port", "input", "string", this.dataAnalyzer); //this.dataAnalyzer.output_ports = new Output_port[3]; this.dataAnalyzer.output_ports = new Output_port[2]; this.dataAnalyzer.output_ports[0] = new Output_port(this.dataAnalyzer.ID + "_P2", this.dataAnalyzer.name + "Port", "output", "string", this.dataAnalyzer); this.dataAnalyzer.output_ports[1] = new Output_port(this.dataAnalyzer.ID + "_P3", this.dataAnalyzer.name + "Port", "output", "string", this.dataAnalyzer); //this.dataAnalyzer.output_ports[2] = new Output_port(this.dataAnalyzer.ID + "_P4", // this.dataAnalyzer.name + "Port", "output", "string", this.dataAnalyzer); //创建DataMemory组件 this.dataMemory = new DataMemory(null, null, null, null); //创建DataMemory组件端口 this.dataMemory.input_ports = new Input_port[1]; this.dataMemory.input_ports[0] = new Input_port(this.dataMemory.ID + "_P1", this.dataMemory.name + "Port", "input", "string", this.dataMemory); //this.dataMemory.output_ports = new Output_port[1]; //this.dataMemory.output_ports[0] = new Output_port(this.dataMemory.ID + "_P2", // this.dataMemory.name + "Port", "output", "string", this.dataMemory); ////创建DisplayController组件 //this.displayController = new DisplayController(null, null, null, null); ////创建DisplayController组件端口 //this.displayController.input_ports = new Input_port[1]; //this.displayController.input_ports[0] = new Input_port(this.displayController.ID + "_P1", // this.displayController.name + "Port", "input", "string", this.displayController); ////this.displayController.output_ports = new Output_port[1]; ////this.displayController.output_ports[0] = new Output_port(this.displayController.ID + "_P2", //// this.displayController.name + "Port", "output", "string", this.displayController); ////创建AudioController组件 //this.audioController = new AudioController(null, null, null, null); ////创建AudioController组件端口 //this.audioController.input_ports = new Input_port[1]; //this.audioController.input_ports[0] = new Input_port(this.audioController.ID + "_P1", // this.audioController.name + "Port", "input", "string", this.audioController); ////this.audioController.output_ports = new Output_port[1]; ////this.audioController.output_ports[0] = new Output_port(this.audioController.ID + "_P2", //// this.audioController.name + "Port", "output", "string", this.audioController); //--------------------------------------------------------------// //--------建立内部组件端口到MedicalServer组件端口的连线---------// //--------------------------------------------------------------// //1、建立MedicalServer组件input端口到WiredModule组件input端口的连线 Connection connection1 = new Connection(); connection1.From = this.input_ports[0].PortConnector1; connection1.To = this.wiredModule.input_ports[0].PortConnector1; //修改ConnectionCollection.cs第78行,获取Add方法 //将连线添加到组件输出端口连接点 this.input_ports[0].PortConnector1.Connections.Add(connection1); //2、建立DataAnalyzer组件output1端口到MedicalServer组件output端口的连线 Connection connection2 = new Connection(); connection2.From = this.DataAnalyzer.output_ports[1].PortConnector1; connection2.To = this.output_ports[0].PortConnector1; //将连线添加到组件输出端口连接点 this.DataAnalyzer.output_ports[1].PortConnector1.Connections.Add(connection2); //-------------------------------------------------------------------// ////2、建立WiredModule组件output端口到Mybuffer组件input端口的连线 //Connection connection2 = new Connection(); //connection2.From = this.wiredModule.output_ports[0].PortConnector1; //connection2.To = this.myBuffer.input_ports[0].PortConnector1; ////将连线添加到组件输出端口连接点 //this.wiredModule.output_ports[0].PortConnector1.Connections.Add(connection2); ////3、建立Mybuffer组件output端口到DataProcessor组件input端口的连线 //Connection connection3 = new Connection(); //connection3.From = this.myBuffer.output_ports[0].PortConnector1; //connection3.To = this.dataProcessor.input_ports[0].PortConnector1; ////将连线添加到组件输出端口连接点 //this.myBuffer.output_ports[0].PortConnector1.Connections.Add(connection3); ////4、建立DataProcessor组件output端口到DataAnalyzer组件input端口的连线 //Connection connection4 = new Connection(); //connection4.From = this.dataProcessor.output_ports[0].PortConnector1; //connection4.To = this.dataAnalyzer.input_ports[0].PortConnector1; ////将连线添加到组件输出端口连接点 //this.dataProcessor.output_ports[0].PortConnector1.Connections.Add(connection4); ////5、建立DataAnalyzer组件output端口到DataMemory组件input端口的连线 //Connection connection5 = new Connection(); //connection5.From = this.dataAnalyzer.output_ports[0].PortConnector1; //connection5.To = this.dataMemory.input_ports[0].PortConnector1; ////将连线添加到组件输出端口连接点 //this.dataAnalyzer.output_ports[0].PortConnector1.Connections.Add(connection5); ////6、建立DataAnalyzer组件output端口到DisplayController组件input端口的连线 //Connection connection6 = new Connection(); //connection6.From = this.dataAnalyzer.output_ports[1].PortConnector1; //connection6.To = this.displayController.input_ports[0].PortConnector1; ////将连线添加到组件输出端口连接点 //this.dataAnalyzer.output_ports[1].PortConnector1.Connections.Add(connection6); ////7、建立DataAnalyzer组件output端口到AudioController组件input端口的连线 //Connection connection7 = new Connection(); //connection7.From = this.dataAnalyzer.output_ports[2].PortConnector1; //connection7.To = this.audioController.input_ports[0].PortConnector1; ////将连线添加到组件输出端口连接点 //this.dataAnalyzer.output_ports[2].PortConnector1.Connections.Add(connection7); this.InsideForm = new InsideForm(this); //构建内部结构显示表单 }
public void Process_ShouldAggregateItemsCorrectly_ForMultipleProductsInSingleWarehouse(IFixture fixture, string productAId, string productBId, string warehouseName, int product1Qty, int product2Qty, DataProcessor sut) { // arrange var modelA = _modelBuilder(fixture, productAId, new Dictionary <string, int> { { warehouseName, product1Qty } }) .Create(); var modelB = _modelBuilder(fixture, productBId, new Dictionary <string, int> { { warehouseName, product2Qty } }) .Create(); var models = new[] { modelA, modelB }; // act var actual = sut.Process(models); // assert actual.ShouldHaveSingleItem().WarehouseName.ShouldBe(warehouseName); actual.ShouldHaveSingleItem().TotalCount.ShouldBe(product1Qty + product2Qty); actual.ShouldHaveSingleItem().Items.Count().ShouldBe(2); actual.ShouldHaveSingleItem().Items.ShouldContain(i => productAId.Equals(i.Id) && i.Count == product1Qty); actual.ShouldHaveSingleItem().Items.ShouldContain(i => productBId.Equals(i.Id) && i.Count == product2Qty); }
public void Ctor_When_Parameters_AreNull_ThrowsException() { _ = new DataProcessor(null, null); }
/******************************************** * 函数名称:run() * 功能:医疗服务器组件执行函数 * 参数:无 * 返回值:无 * *****************************************/ public void run() { while (true) { if (Form1.stop) { this.EmptyingQueue(); return; } //-------------------医疗服务器input端口传输数据----------------// //若input端口不为空 if (this.input_ports != null) { foreach (Input_port input in this.input_ports) { PortDataTransfer(input); //input端口进行数据传输 } } //-------------------有线模块组件启动执行-------------------// WiredModule wiredM = (WiredModule)this.wiredModule; //step1、有线模块组件接收数据 wiredM.ComponentDataReceive(wiredM); //step2、执行有线模块数据帧解封装功能 wiredM.EthernetFrameDecapsulation(); //step3、有线模块组件output端口传输数据 wiredM.ComponentDataTransfer(wiredM); //--------------------缓冲区组件启动执行--------------------// MyBuffer buf = (MyBuffer)this.myBuffer; //step1、缓冲区组件接收数据 buf.ComponentDataReceive(buf); //step2、执行缓冲区功能 buf.MessageBuffering(null); //step3、缓冲区1组件output端口传输数据 buf.ComponentDataTransfer(buf); //---------------网络数据处理模块组件启动执行--------------// DataProcessor dp = (DataProcessor)this.dataProcessor; //step1、网络数据处理模块接收数据 dp.ComponentDataReceive(dp); //step2、执行网络数据处理模块功能 dp.NetworkDataProcessing(); //step3、网络数据处理模块output端口传输数据 dp.ComponentDataTransfer(dp); //----------------信息分析控制模块启动执行------------------// DataAnalyzer da = (DataAnalyzer)this.dataAnalyzer; //step1、信息分析控制模块接收数据 da.ComponentDataReceive(da); //step2、执行信息分析控制模块功能 da.DataAnalysis(); //step3、信息分析控制模块output端口传输数据 da.ComponentDataTransfer(da); //----------------医疗服务器output端口传输数据--------------// //若output端口不为空 if (this.output_ports != null) { foreach (Output_port output in this.output_ports) { PortDataTransfer(output); //output端口进行数据传输 } } } }// public void run()
public void SetProcessor(DataProcessor processor) { _processor = processor; }
public void TestDataProcessor() { DateTime start = new DateTime(2012, 08, 22); RrdDef def = new RrdDef(SAMPLE, start.GetTimestamp(), 60); def.AddDatasource("speed",DataSourceType.COUNTER,120,double.NaN,double.NaN); // Step : every minute def.AddArchive(ConsolidationFunction.AVERAGE, 0, 5, 12 * 24 * 30); // Archive average every 5 minutes during 30 days def.AddArchive(ConsolidationFunction.AVERAGE, 0, 5 * 12, 24 * 30); // Archive average every hour during 30 days start = start.AddSeconds(40); using (RrdDb db = RrdDb.Create(def)) { Sample sample = db.CreateSample(); for (int i = 1; i < 60 * 24 * 3; i++) // add 3 days of samples { sample.Set(start.AddMinutes(i), 100 * i); sample.Update(); } } DataProcessor dataProcessor = new DataProcessor(start.AddHours(3), start.AddHours(13)); dataProcessor.FetchRequestResolution = 3600; dataProcessor.AddDatasource("speed", SAMPLE, "speed", ConsolidationFunction.AVERAGE); dataProcessor.AddDatasource("speedByHour", "speed, STEP, *"); dataProcessor.ProcessData(); double[] vals = dataProcessor.GetValues("speedByHour"); Assert.AreEqual(12, vals.Length); for (int i = 0; i < vals.Length; i++) { Assert.AreEqual(6000,((int)vals[i])); } }
internal abstract void requestData(DataProcessor dproc);
public void Ctor_When_RetailerProductRepo_IsNull_ThrowsException() { _ = new DataProcessor(null, _mockProductRepository.Object); }
protected void SaveAsBrl4(string path, Rectangle area, string newExt, DataProcessor.Abstract.DataStringProcessor processor) { using (var fr = System.IO.File.Open(_file.Properties.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var fname = Path.ChangeExtension(path, newExt); using (var fw = System.IO.File.Open(fname, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { fr.Seek(Marshal.SizeOf(typeof(RlViewer.Headers.Concrete.Rl4.Rl4RliFileHeader)), SeekOrigin.Begin); var rlSubHeader = _head.HeaderStruct.rlParams .ChangeImgDimensions(area.Width, area.Height) .ChangeFragmentShift(area.X, area.Y); RlViewer.Headers.Concrete.Rl4.Rl4RliFileHeader rl4Header = new Headers.Concrete.Rl4.Rl4RliFileHeader(_head.HeaderStruct.fileSign, _head.HeaderStruct.fileVersion, _head.HeaderStruct.rhgParams, rlSubHeader, _head.HeaderStruct.synthParams, _head.HeaderStruct.reserved); var brl4Head = rl4Header.ToBrl4(0, 1, 0); fw.Write(RlViewer.Behaviors.Converters.StructIO.WriteStruct<RlViewer.Headers.Concrete.Brl4.Brl4RliFileHeader>(brl4Head), 0, Marshal.SizeOf(brl4Head)); byte[] strHeader = new byte[SourceFile.Header.StrHeaderLength]; int strDataLength = _file.Width * _file.Header.BytesPerSample; byte[] frameData = new byte[area.Width * _file.Header.BytesPerSample]; long lineToStartSaving = (long)area.Y * (long)(_file.Width * _file.Header.BytesPerSample + SourceFile.Header.StrHeaderLength); long sampleToStartSaving = area.X * _file.Header.BytesPerSample; fr.Seek(lineToStartSaving, SeekOrigin.Current); for (int i = 0; i < area.Height; i++) { //read-write string header OnProgressReport((int)((double)i / (double)area.Height * 100)); if (OnCancelWorker()) { return; } fr.Read(strHeader, 0, SourceFile.Header.StrHeaderLength); var brl4StrHead = Converters.FileHeaderConverters.ToBrl4StrHeader(strHeader); fw.Write(brl4StrHead, 0, SourceFile.Header.StrHeaderLength); fr.Seek(sampleToStartSaving, SeekOrigin.Current); fr.Read(frameData, 0, frameData.Length); var processedFrame = processor.ProcessRawDataString(frameData); fw.Write(processedFrame, 0, processedFrame.Length); fr.Seek(strDataLength - frameData.Length - sampleToStartSaving, SeekOrigin.Current); } } } }
private void fetchData() { dproc = new DataProcessor(gdef.startTime, gdef.endTime); dproc.IsPoolUsed = gdef.poolUsed; if (gdef.step > 0) { dproc.Step = gdef.step; } foreach (Source src in gdef.sources) { src.requestData(dproc); } dproc.ProcessData(); //long[] t = dproc.getTimestamps(); //im.start = t[0]; //im.end = t[t.length - 1]; im.start = gdef.startTime; im.end = gdef.endTime; }
internal override void requestData(DataProcessor dproc) { dproc.AddDatasource(name, defName, consolFun); }