Exemplo n.º 1
0
        public static RunItem ComputeRunStats(this RunItem runItem)
        {
            try
            {
                Trace.WriteLine("Start ComputeRunStats : RunItem " + runItem.KeyId);
                // Load the base64 keys
                String galKeyString = "", galSingleStepKeyString = "", relinKeyString = "";
                KeyUtilities.GetKeys(runItem.KeyId, ref galKeyString, ref galSingleStepKeyString, ref relinKeyString);

                // Calculate the cipher results
                SEALWrapper sw = new SEALWrapper(4096);
                sw.LoadKeys(galKeyString, galSingleStepKeyString, relinKeyString);
                sw.ComputeStatsCiphers(runItem.Cipher1, runItem.Cipher2, runItem.Summary, runItem.CipherGyro);
                runItem.Stats      = sw.getStats();
                runItem.Summary    = sw.getSummary();
                runItem.CipherGyro = sw.getMlResults();

                Trace.WriteLine("End ComputeRunStats : RunItem " + runItem.KeyId);
            }
            catch (Exception e)
            {
                Trace.TraceError("{%s} occurred while computing stats {RunItem : %d}", runItem.KeyId, e);
            }

            return(runItem);
        }
Exemplo n.º 2
0
        private IEnumerable <RunInfo> RunDefinitions(RunItem runItem, bool singleRun)
        {
            var multiRuns = runItem.MultiRuns;

            if (!singleRun && multiRuns.Count > 0)
            {
                foreach (var item in multiRuns)
                {
                    var info = new RunInfo();
                    RunCore.GetItems(runItem.Name, item.ManagementItemSelected, item.ParameterItemSelected, item.RunOptionItemSelected, item.SiteItemSelected, item.SoilItemSelected, item.VarietyItem,
                                     ref info.Management, ref info.NonVariety, ref info.RunOptions, ref info.Site, ref info.Soil, ref info.Variety);
                    info.Name = item.ManagementItemSelected;

                    yield return(info);
                }
            }
            else
            {
                var info = new RunInfo();
                RunCore.GetItems(runItem.Name, runItem.Normal.ManagementItem, runItem.Normal.ParameterItem, runItem.Normal.RunOptionItem, runItem.Normal.SiteItem, runItem.Normal.SoilItem, runItem.Normal.VarietyItem,
                                 ref info.Management, ref info.NonVariety, ref info.RunOptions, ref info.Site, ref info.Soil, ref info.Variety);
                info.Name = runItem.Normal.ManagementItem;

                yield return(info);
            }
        }
Exemplo n.º 3
0
 public void AddExecutedItem(RunItem exItem)
 {
     MatcherGeneral.Remove(exItem.Name.ToLower());
     exItem.RunNrOfTimes++;
     MatcherPrio.Replace(exItem.Name, exItem);
     SaveTries();
 }
Exemplo n.º 4
0
        public RunManager()
        {
            _DataUpdateSyncEvent = new ManualResetEvent(true);

            RunData            = new RunItem();
            RunData.FacebookId = MobileService.Instance.UserData.FacebookId;
        }
Exemplo n.º 5
0
        public static List <RunItem> MatchControlPanelRunItems(string input)
        {
            //先忽略/page
            //先使用简单粗暴的正则,有时间就优化一下
            var list = new List <RunItem>();

            var itemRegexPattern = @"<h3(.*)</h3>\s*<ul>\s*(?<=<ul>)[\s\S]*?(?=</ul>)";
            var h3TagPattern     = @"<h3[\s\S]*?>(?<value>[\s\S]*?)</h3>";
            var strongPattern    = @"</strong>:\s+(?<value>[\w\.]+)";
            var matches          = Regex.Matches(input, itemRegexPattern);

            foreach (Match match in matches)
            {
                var matchH3     = Regex.Match(match.Value, h3TagPattern);
                var matchStrong = Regex.Match(match.Value, strongPattern);

                if (matchH3.Success == false || matchStrong.Success == false)
                {
                    continue;
                }

                RunItem runItem = new RunItem();
                runItem.Description = matchH3.Groups["value"].Value;
                runItem.Name        = runItem.Description;
                runItem.Path        = "control /name " + matchStrong.Groups["value"].Value;
                list.Add(runItem);
            }
            return(list);
        }
Exemplo n.º 6
0
 public BuddyRunManager() : base()
 {
     BuddyData         = new RunItem();
     _buddyWaypoints   = new ObservableCollection <Geopoint>();
     _routeFinderEvent = new ManualResetEvent(true);
     LocationService.Instance.OnLocationChange += My_OnLocationChange;
 }
Exemplo n.º 7
0
 public void AddItem(RunItem item)
 {
     if (!MatcherPrio.DataDictionary.ContainsKey(item.Name))
     {
         MatcherPrio.Insert(item.Name.ToLower(), item);
         MatcherPrio.Insert(item.KeyWords, item);
     }
 }
Exemplo n.º 8
0
        static async Task SendNewRun()
        {
            // Get distance from user
            Console.Write("Enter the new running distance (km): ");
            var newRunningDistance = Convert.ToInt32(Console.ReadLine());

            if (newRunningDistance < 0)
            {
                Console.WriteLine("Running distance must be greater than 0.");
                return;
            }

            // Encrypt distance
            // We will convert the Int value to Hexadecimal using the ToString("X") method
            var plaintext          = new Plaintext($"{newRunningDistance.ToString("X")}");
            var ciphertextDistance = new Ciphertext();

            _encryptor.Encrypt(plaintext, ciphertextDistance);


            // Convert value to base64 string
            var base64Distance = SEALUtils.CiphertextToBase64String(ciphertextDistance);


            // Get time from user
            Console.Write("Enter the new running time (hours): ");
            var newRunningTime = Convert.ToInt32(Console.ReadLine());

            if (newRunningTime < 0)
            {
                Console.WriteLine("Running time must be greater than 0.");
                return;
            }

            // Encrypt time
            // We will convert the Int value to Hexadecimal using the ToString("X") method
            var plaintextTime  = new Plaintext($"{newRunningTime.ToString("X")}");
            var ciphertextTime = new Ciphertext();

            _encryptor.Encrypt(plaintextTime, ciphertextTime);


            // Convert value to base64 string
            var base64Time = SEALUtils.CiphertextToBase64String(ciphertextTime);


            var metricsRequest = new RunItem
            {
                Distance = base64Distance,
                Time     = base64Time
            };

            LogUtils.RunItemInfo("CLIENT", "SendNewRun", metricsRequest);

            // Send new run to api
            await FitnessTrackerClient.AddNewRunningDistance(metricsRequest);
        }
Exemplo n.º 9
0
        public void ResetItemRunCounter(RunItem exItem)
        {
            exItem.RunNrOfTimes = 0;
            if (exItem.Type == ItemType.File || exItem.Type == ItemType.Directory
                ) //Move it back to general list. Settings and other stuff will always be in the priolist.
            {
                MatcherPrio.Remove(exItem.Name.ToLower());
                MatcherGeneral.Insert(exItem.Name.ToLower(), exItem);
            }

            SaveTries();
        }
Exemplo n.º 10
0
        public ActionResult AddRunItem([FromBody] RunItem request)
        {
            // Add AddRunItem code
            LogUtils.RunItemInfo("API", "AddRunItem", request);
            LogUtils.RunItemInfo("API", "AddRunItem", request, true);
            //var distance = SEALUtils.Base64Decode(request.Distance);
            //var time = SEALUtils.Base64Decode(request.Time);

            _distances.Add(request.Distance);
            _times.Add(request.Time);
            return(Ok());
        }
Exemplo n.º 11
0
        public static async Task AddNewRunningDistance(RunItem metricsRequest)
        {
            var metricsRequestAsJsonStr = JsonConvert.SerializeObject(metricsRequest);

            using (var request = new HttpRequestMessage(HttpMethod.Post, $"{BaseUri}/metrics"))
                using (var content = new StringContent(metricsRequestAsJsonStr, Encoding.UTF8, "application/json"))
                {
                    request.Content = content;
                    var response = await _client.SendAsync(request);

                    response.EnsureSuccessStatusCode();
                }
        }
Exemplo n.º 12
0
        public static List <RunItem> MatchMsSettingRunItems(string input)
        {
            //学艺不精啊哎
            var tdPattern        = "<td>(?<td>(.*))</td>";
            var mssettingPattern = "ms-settings:\\S+";

            var list   = new List <RunItem>();
            var tdList = Regex.Matches(input, tdPattern);

            for (int i = 0; i < tdList.Count; i += 2)
            {
                RunItem runItem = new RunItem();
                runItem.Description = RegexGetSpanValue(tdList[i].Groups["td"].Value);
                var match = Regex.Match(tdList[i + 1].Groups["td"].Value, mssettingPattern);

                if (match.Success == false)
                {
                    continue;
                }

                if (match.Value.Contains("<br>") || match.Value.Contains("<br/>"))
                {
                    var subSettingArray = match.Value.Replace("<br>", ";").Replace("<br/>", ";").Split(';');
                    foreach (var subSetting in subSettingArray)
                    {
                        if (Regex.IsMatch(subSetting, mssettingPattern) == false)
                        {
                            continue;
                        }

                        RunItem subRunItem = new RunItem();
                        subRunItem.Description = runItem.Description;
                        subRunItem.Name        = RegexReplaceChinese(RegexReplaceSpan(subSetting));
                        subRunItem.Path        = subRunItem.Name;
                        list.Add(subRunItem);
                    }
                }
                else
                {
                    runItem.Name = RegexReplaceChinese(RegexReplaceSpan(match.Value));
                    runItem.Path = runItem.Name;
                    list.Add(runItem);
                }
            }

            return(list);
        }
Exemplo n.º 13
0
        private async Task <List <RunItem> > GetAppListAsync(Microsoft.Win32.RegistryKey registryKey, string path)
        {
            var list = new List <RunItem>();

            try
            {
                await Task.Run(() =>
                {
                    var appList = RegisterExtension.GetRegItem(registryKey, path);

                    foreach (var item in appList)
                    {
                        var runitem  = new RunItem();
                        runitem.Name = item;
                        var fullPath = RegisterExtension.GetRegValue(registryKey, path + "\\" + item, null);

                        if (string.IsNullOrEmpty(fullPath))
                        {
                            continue;
                        }

                        fullPath = fullPath.Replace('"', ' ').Trim();

                        if (System.IO.File.Exists(fullPath))
                        {
                            runitem.Path = fullPath;
                        }
                        else
                        {
                            runitem.Path = System.IO.Path.Combine(fullPath, item);
                        }

                        runitem.Description = FileExtension.GetFileDescription(runitem.Path);
                        list.Add(runitem);
                    }
                });

                return(list);
            }
            catch
            {
                return(list);
            }
        }
Exemplo n.º 14
0
        private async Task <IEnumerable <RunItem> > LoadRundll32ItemFromResAsync()
        {
            List <RunItem> list = new List <RunItem>();

            await Task.Run(() => {
                byte[] buffer = Encoding.UTF8.GetBytes(Properties.Resources.rundll32);

                using (System.IO.MemoryStream ms = new MemoryStream(buffer))
                {
                    using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
                    {
                        var tempList = new List <string>();
                        var str      = sr.ReadLine();

                        while (!string.IsNullOrEmpty(str))
                        {
                            tempList.Add(str);
                            str = sr.ReadLine();
                        }

                        for (int i = 0; i < tempList.Count - 2; i += 3)
                        {
                            RunItem runItem = new RunItem();
                            runItem.Path    = tempList[i + 2];
                            runItem.Name    = runItem.Path.Replace("rundll32.exe ", "");

                            if (CurrentCultureName == "zh-CN")
                            {
                                runItem.Description = tempList[i + 1];
                            }
                            else
                            {
                                runItem.Description = tempList[i];
                            }
                            list.Add(runItem);
                        }
                    }
                }
            });

            return(list);
        }
Exemplo n.º 15
0
 public static void RunItemInfo(string from, string method, RunItem runItem, bool convertFromBase64 = false)
 {
     if (convertFromBase64)
     {
         Debug.WriteLine($"[{from}] {method}");
         Debug.WriteLine($"[{from}] SummaryItem contents");
         Debug.WriteLine($"[{from}] \t \t Distance: {SEALUtils.Base64Decode(runItem.Distance)}");
         Debug.WriteLine($"[{from}] \t \t Time: {SEALUtils.Base64Decode(runItem.Time)}");
     }
     else
     {
         Debug.WriteLine($"[{from}] {method}");
         Debug.WriteLine($"[{from}] SummaryItem contents");
         Debug.WriteLine($"[{from}] \t \t Distance: " +
                         $"{(runItem.Distance.Length > 25 ? runItem.Distance.Substring(0, 25) : runItem.Distance)}" +
                         $"{(runItem.Distance.Length > 25 ? "..." : "")}");
         Debug.WriteLine($"[{from}] \t \t Time: " +
                         $"{(runItem.Time.Length > 25 ? runItem.Time.Substring(0, 25) : runItem.Time)}" +
                         $"{(runItem.Time.Length > 25 ? "..." : "")}");
     }
 }
Exemplo n.º 16
0
        private void runItemsBindingSource1_CurrentChanged(object sender, EventArgs e)
        {
            var enabled = runItemsBindingSource1.Current != null;

            buttonDelete.UpdateEnabled(enabled);
            buttonRun.UpdateEnabled(enabled);
            buttonExport.UpdateEnabled(enabled);
            buttonDuplicate.UpdateEnabled(enabled);
            splitContainer1.Panel2.UpdateEnabled(enabled);
            if (enabled)
            {
                if (radioButtonNormal.Checked)//single run only
                {
                    //set the combo boxes state
                    RunItem currentNormalRun = (RunItem)runItemsBindingSource1.Current;
                    string  savedManagement  = currentNormalRun.Normal.ManagementItem;
                    string  savedParameter   = currentNormalRun.Normal.ParameterItem;
                    string  savedVariety     = currentNormalRun.Normal.VarietyItem;

                    if ((string)experimentNameComboBoxRunSingle.SelectedItem == (string)currentNormalRun.Normal.ExperimentItem)
                    {
                        //in case the selected item is already the right one we need to explicitely call SelectindexChanged
                        experimentNameComboBoxRunSingle_SelectedIndexChanged(experimentNameComboBoxRunSingle, null);
                    }
                    else
                    {
                        experimentNameComboBoxRunSingle.SelectedItem = currentNormalRun.Normal.ExperimentItem;
                    }

                    updateCurrentManagement(savedManagement);
                    comboBox1.SelectedItem = managementItemsBindingSource1.Current;

                    updateCurrentParameter(savedParameter);
                    comboBox2.SelectedItem = parameterItemsBindingSource1.Current;

                    updateCurrentVariety(savedVariety);
                    comboBox6.SelectedItem = varietyItemsBindingSource1.Current;
                }
            }
        }
Exemplo n.º 17
0
 public async void SaveRunData(RunItem runData)
 {
     await Service.GetTable <RunItem>().InsertAsync(runData);
 }
Exemplo n.º 18
0
        public void ProcessDirectory(FolderSearch dir, HashSet <RunItem> theBag)
        {
            try
            {
                if (Directory.Exists(dir.Path))
                {
                    if (dir.IncludeFoldersInSearch)
                    {
                        var folder = new RunItem()
                        {
                            Name = new DirectoryInfo(dir.Path).Name,
                            URI  = new StringBuilder(dir.Path).Replace("/", "\\").Replace("//", "\\").ToString(),
                            Type = ItemType.Directory
                        };
                        theBag.Add(folder);
                    }
                }
                else
                {
                    Log.Error($"{dir.Path} does not exist...");
                    return;
                }


                //ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
                //foreach (ManagementObject mgmtObjectin in searcher.Get())
                //{
                //    Console.WriteLine(mgmtObjectin["Name"]);
                //    Console.WriteLine(mgmtObjectin.Path);
                //}


                //var t = theBag.ContainsKey(dir.URI);
                // Process the list of files found in the directory.
                string[] fileEntries = Directory.GetFiles(dir.Path, dir.SearchPattern);
                foreach (string fileName in fileEntries)
                {
                    try
                    {
                        if (Path.GetExtension(fileName) == ".lnk")
                        {
                            Directory.CreateDirectory(Common.LinksPath);
                            File.Copy(fileName, Common.LinksPath + Path.GetFileName(fileName), true);

                            var item = new RunItem();
                            item.Type    = ItemType.Link;
                            item.Command = Common.LinksPath + Path.GetFileName(fileName);
                            WshShell     shell = new WshShell();                                   //Create a new WshShell Interface
                            IWshShortcut link  = (IWshShortcut)shell.CreateShortcut(item.Command); //Link the interface to our shortcut
                            var          uri   = link.TargetPath;
                            item.URI       = uri;
                            item.Arguments = link.Arguments;

                            //var t = link.FullName;
                            //var t2 = link.Description;
                            //var t3 = link.WorkingDirectory;
                            //var t4 = link.FullName;



                            var split    = link.IconLocation.Split(',');
                            var iconName = split[0];
                            item.IconNr = Convert.ToInt32(split[1]);

                            if (File.Exists(iconName))
                            {
                                try
                                {
                                    Stream            iconStream = new FileStream(iconName, FileMode.Open, FileAccess.Read);
                                    IconBitmapDecoder decoder    = new IconBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                                    BitmapFrame       frame      = decoder.Frames[item.IconNr];
                                    item.IconName = iconName;
                                }
                                catch
                                {
                                    if (S.Settings.DebugMode)
                                    {
                                        Log.Error($"Could not add icon for {iconName} nr: {item.IconNr}");
                                    }
                                }
                            }
                            item.Name = Path.GetFileNameWithoutExtension(item.Command).Replace(" - Shortcut", "");  //get the name of the icon and removing the shortcut ending that sometimes are there, because nice-ness
                            if (uri != "")
                            {
                                item.KeyWords.Add(Path.GetFileName(uri));
                            }
                            theBag.Add(item);
                        }
                        else
                        {
                            var item = new RunItem
                            {
                                Type = ItemType.File,
                                URI  = new StringBuilder(fileName).Replace("/", "\\").Replace("//", "\\").ToString()
                            };
                            item.Name = item.FileName;
                            theBag.Add(item);
                        }
                    }
                    catch (Exception e)
                    {
                        if (S.Settings.DebugMode)
                        {
                            Log.Error(e, $"Could not index {fileName}");
                        }
                    }
                }
            }
            catch (Exception)
            {
                if (S.Settings.DebugMode)
                {
                    Log.Debug($"Could not search {dir.Path}");
                }
            }

            if (dir.SearchSubFolders)
            {
                try
                {
                    // Recurse into subdirectories of this directory.
                    string[] subdirectoryEntries = Directory.GetDirectories(dir.Path);
                    foreach (string subdirectory in subdirectoryEntries)
                    {
                        try
                        {
                            ProcessDirectory(
                                new FolderSearch()
                            {
                                Path = subdirectory,
                                IncludeFoldersInSearch = dir.IncludeFoldersInSearch,
                                SearchPattern          = dir.SearchPattern,
                                SearchSubFolders       = dir.SearchSubFolders
                            }, theBag);
                        }
                        catch (Exception e)
                        {
                            Log.Debug(e.Message);
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e.Message);
                }
            }
        }
Exemplo n.º 19
0
        public FitnessFunctions(RunItem runItem, bool singleRun, List <OptiParameter> ParamList, List <OptiObservation> ObservList, ObservationItem ObservItem)
            : this()
        {
            if (runItem == null)
            {
                throw new Exception("RunItem is empty: Select a run in the combobox");
            }
            this.RunInfos  = RunDefinitions(runItem, singleRun).ToList();
            multiMultiYear = runItem.MultiMultiYear;
            multiFirstYear = runItem.MultiFirstYear;
            multiLastYear  = runItem.MultiLastYear;

            observItem_ = ObservItem;
            observItem_.updateObservationDictionary();

            observList_ = ObservList;

            foreach (var item in this.RunInfos)
            {
                item.Management = item.Management.Clone();
                item.RunOptions = item.RunOptions.Clone();
                item.Site       = item.Site.Clone();
                item.Soil       = item.Soil.Clone();
                item.Variety    = item.Variety.Clone();
                item.NonVariety = item.NonVariety.Clone();

                this.Managements.Add(item.Management);
                this.RunOptions.Add(item.RunOptions);
                this.Sites.Add(item.Site);
                this.Soils.Add(item.Soil);
                this.Varieties.Add(item.Variety);
                this.NonVarieties.Add(item.NonVariety);
            }

            // Update of ParamSubModel

            foreach (var item in this.Varieties.First().ParamValue.Keys)
            {
                this.ParamSubModel.Add(item, "Variety");
            }

            foreach (var item in this.NonVarieties.First().ParamValue.Keys)
            {
                this.ParamSubModel.Add(item, "NonVariety");
            }


            // Initialisation of ParamList
            List <string> temp = new List <string>();

            foreach (var item in ParamList)
            {
                switch (this.ParamSubModel[item.Name])
                {
                case "Management":
                    temp = Managements.Select(ii => ii.Name).ToList(); optimizeManagementParameter = true;
                    break;

                case "Soil":
                    temp = Soils.Select(ii => ii.Name).ToList(); optimizeSoilParameter = true;
                    break;

                case "NonVariety":
                    temp = NonVarieties.Select(ii => ii.Name).ToList(); optimizeNonVarietalParameter = true;
                    break;

                case "Variety":
                    temp = Varieties.Select(ii => ii.Name).ToList(); optimizeVarietalParameter = true;
                    break;

                default: break;
                }

                while (temp.Count != 0)
                {
                    if (!ParamValueDictio.ContainsKey(temp[0]))
                    {
                        ParamValueDictio.Add(temp[0], new Dictionary <string, double>());
                    }
                    if (!ParamValueDictio[temp[0]].ContainsKey(item.Name))// should always be true
                    {
                        ParamValueDictio[temp[0]].Add(item.Name, 0);
                        paramValueDictioSize++;
                    }

                    string typeToRemove = temp[0];
                    temp.RemoveAll(elem => elem == typeToRemove);
                }
            }
        }