/// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>用户对象</returns>
        internal static IList <User> GetUserListRandom(string userID)
        {
            var random = new Random();
            var users  = new List <User>();

            _toDoUserList.Remove(userID);

            //模拟用户一
            var entry = _toDoUserList.ElementAt(random.Next(0, _toDoUserList.Count()));
            var user  = new User {
                UserID = entry.Key, UserName = entry.Value
            };

            users.Add(user);
            _toDoUserList.Remove(user.UserID);

            //模拟用户二
            entry = _toDoUserList.ElementAt(random.Next(0, _toDoUserList.Count()));
            user  = new User {
                UserID = entry.Key, UserName = entry.Value
            };
            users.Add(user);
            _toDoUserList.Remove(user.UserID);

            //模拟用户三
            entry = _toDoUserList.ElementAt(random.Next(0, _toDoUserList.Count()));
            user  = new User {
                UserID = entry.Key, UserName = entry.Value
            };
            users.Add(user);
            _toDoUserList.Remove(user.UserID);

            return(users);
        }
Esempio n. 2
0
        private ImportRecordTypesResponse ImportRecordTypes(IDictionary <int, ImportRecordMetadata> metadata, LogController controller,
                                                            CustomisationImportResponse response)
        {
            var thisResponse = new ImportRecordTypesResponse();

            var numberToDo      = metadata.Count();
            var numberCompleted = 0;

            for (var i = 0; i < metadata.Count(); i++)
            {
                var keyValue       = metadata.ElementAt(i);
                var excelRow       = keyValue.Key;
                var recordMetadata = keyValue.Value;
                try
                {
                    controller.UpdateProgress(numberCompleted++, numberToDo, string.Format("Importing {0}", EntityTabName));
                    var isUpdate = RecordService.RecordTypeExists(recordMetadata.SchemaName);
                    RecordService.CreateOrUpdate(recordMetadata);
                    if (!isUpdate)
                    {
                        thisResponse.AddCreatedRecordType(recordMetadata.SchemaName);
                        response.AddResponseItem(recordMetadata.GetPrimaryFieldMetadata(), false);
                    }
                    response.AddResponseItem(excelRow, recordMetadata, isUpdate);
                }
                catch (Exception ex)
                {
                    response.AddResponseItem(excelRow, recordMetadata, ex);
                }
            }
            return(thisResponse);
        }
Esempio n. 3
0
 private void ValidateGameHasCorrectNumberOfPlayers()
 {
     if (playerOrder.Count() < MinimumPlayers || playerOrder.Count() > MaximumPlayers)
     {
         throw new Exception();
     }
 }
Esempio n. 4
0
        /// <summary>
        /// 分配设备的DB1,DB2地址区
        /// </summary>
        /// <returns></returns>
        protected bool AllocDevDBAddr()
        {
            try
            {
                if (devModel != null)
                {
                    //配置DB1
                    AllocDevComAddrsDB1();

                    //配置DB2
                    AllocDevComAddrsDB2();

                    for (int i = 0; i < dicCommuDataDB1.Count(); i++)
                    {
                        int             commuID = i + 1;
                        DevCommDatatype commObj = dicCommuDataDB1[commuID];
                        if (commObj == null)
                        {
                            continue;
                        }

                        dicDataDB1Last[commObj.CommuID] = commObj.Val;
                    }
                    if (dicCommuDataDB2.Count() > 0)
                    {
                        foreach (KeyValuePair <int, DevCommDatatype> keyVal in dicCommuDataDB2)
                        {
                            if (keyVal.Value == null)
                            {
                                continue;
                            }
                            DevCommDatatype commObj = keyVal.Value;
                            dicDataDB2Last[commObj.CommuID] = commObj.Val;
                        }
                    }
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (System.Exception ex)
            {
                //触发错误日志,2004
                int    errorCode = 2004;
                string reStr     = "";
                if (!ECAMWCS.GetErrorContent(errorCode, ref reStr))
                {
                    AddLog("配置设备" + this.devModel.DeviceID + " 出现异常," + ex.Message + "," + ex.StackTrace, EnumLogType.错误);
                }
                else
                {
                    reStr  = "设备:" + this.devModel.DeviceID + reStr;
                    reStr += (ex.Message + "," + ex.StackTrace);
                    OnErrorHappen(errorCode, reStr, true);
                }
                return(false);
            }
        }
Esempio n. 5
0
        private void CheckVariableExists(string name, IDictionary <string, ITestVariable> variables)
        {
            if (!variables.ContainsKey(name))
            {
                var caseIssues = variables.Keys.Where(k => String.Equals(k, name, StringComparison.OrdinalIgnoreCase));

                if (caseIssues.Count() > 0)
                {
                    throw new NBiException($"The variable named '{name}' is not defined. Pay attention, variables are case-sensitive. Did you mean '{string.Join("' or '", caseIssues)}'?");
                }

                var arobaseIssues = variables.Keys.Where(k => String.Equals(k.Replace("@", string.Empty), name, StringComparison.OrdinalIgnoreCase));
                if (arobaseIssues.Count() > 0)
                {
                    throw new NBiException($"The variable named '{name}' is not defined. Pay attention, variables shouldn't begin with an arobase (@). Consider to review the name of the following variable{(arobaseIssues.Count() == 1 ? string.Empty : "s")}: '{(string.Join("' and '", arobaseIssues))}' at the top of your test-suite.");
                }

                var countMsg =
                    variables.Count() == 0 ? "No variables are" :
                    variables.Count() == 1 ? $"1 variable '{(variables).Keys.ElementAt(0)}' is"
                    : $"{variables.Count()} other variables are";

                throw new NBiException($"The variable named '{name}' is not defined. {countMsg} defined at the top of the test-suite.");
            }
        }
Esempio n. 6
0
        private void ImportRelationships(IDictionary <int, Many2ManyRelationshipMetadata> metadata, LogController controller,
                                         CustomisationImportResponse response)
        {
            var numberToDo      = metadata.Count();
            var numberCompleted = 0;

            for (var i = 0; i < metadata.Count(); i++)
            {
                var keyValue       = metadata.ElementAt(i);
                var excelRow       = keyValue.Key;
                var recordMetadata = keyValue.Value;
                try
                {
                    controller.UpdateProgress(numberCompleted++, numberToDo, string.Format("Importing {0}", RelationshipTabName));
                    var isUpdate = RecordService.GetManyToManyRelationships(recordMetadata.RecordType1).Any(r => r.SchemaName == recordMetadata.SchemaName);
                    RecordService.CreateOrUpdate(recordMetadata);
                    response.AddImportedItem(excelRow, recordMetadata, isUpdate);
                }
                catch (Exception ex)
                {
                    response.AddResponseItem(excelRow, recordMetadata, ex);
                }
            }
            if (numberCompleted > 0)
            {
                controller.LogLiteral("Publishing Relationships");
                var publishXml = $"<importexportxml><entities>{string.Join("", metadata.Select(m => "<entity>" + m.Value.RecordType1 + "</entity>").Union(metadata.Select(m => "<entity>" + m.Value.RecordType2 + "</entity>")))}</entities></importexportxml>";
                RecordService.Publish(publishXml);
            }
        }
        /// <summary>
        ///     Create basic dynamic SQL where parameters from a JSON key value pair string
        /// </summary>
        /// <param name="value">json key value pair string</param>
        /// <param name="useOr">if true constructs parameters using or statement if false and</param>
        /// <returns></returns>
        public static string CreateParameters(this string value, bool useOr)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(string.Empty);
            }
            IDictionary <string, object> searchParamters = value.JsonToDictionary();
            var @params = new StringBuilder("");

            if (searchParamters == null)
            {
                return(@params.ToString());
            }
            for (int i = 0; i <= searchParamters.Count() - 1; i++)
            {
                string key = searchParamters.Keys.ElementAt(i);
                var    val = (string)searchParamters[key];
                if (!string.IsNullOrEmpty(key))
                {
                    @params.Append(key).Append(" like '").Append(val.Trim()).Append("%' ");
                    if (i < searchParamters.Count() - 1 && useOr)
                    {
                        @params.Append(" or ");
                    }
                    else if (i < searchParamters.Count() - 1)
                    {
                        @params.Append(" and ");
                    }
                }
            }
            return(@params.ToString());
        }
Esempio n. 8
0
        /*double tertySecondsChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(0.5));
         * double oneMinuteChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(1));
         * double fiveMinuteChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(5));
         * double thertyMinuteChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(30));
         * double sixtyMinuteChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromMinutes(60));
         * double twientyFourHoursChange = trend.ChangePercentageToLatest(ownedExchangeRate, TimeSpan.FromHours(23));
         * double currencyBalance = (account.BalancesInUsd[ownedExchangeRate.MainCurrency] - account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency]);
         * double percentageGrowth = account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency] != 0.0 && account.BalancesInUsd[ownedExchangeRate.MainCurrency] - account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency] != 0.0
         *  ? 100.0 * (account.BalancesInUsd[ownedExchangeRate.MainCurrency] - account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency]) / account.InitialBalancesInUsd[ownedExchangeRate.MainCurrency]
         *  : 0.0;
         * }
         *
         * DateTime now = DateTime.Now;
         * DateTime dateTimeInitial = stockDataPoints.First(k => k.Key > now - timeSpan).Key;
         * if(stockDataPoints[dateTimeInitial] == stockDataPoints.Last().Value ||
         * stockDataPoints.First().Key > now - timeSpan)
         * {
         * return double.NaN;
         * }
         * }
         * }
         *
         * public double ChangePercentageToLatest(IExchangeRate exchangeRate, TimeSpan timeSpan)
         * {
         * IDictionary<DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory;
         *
         * DateTime now = DateTime.Now;
         * DateTime dateTimeInitial = stockDataPoints.First(k => k.Key > now - timeSpan).Key;
         * if (stockDataPoints[dateTimeInitial] == stockDataPoints.Last().Value ||
         * stockDataPoints.First().Key > now - timeSpan)
         * {
         * return double.NaN;
         * }
         * return 100.0 * ((stockDataPoints.Last().Value - stockDataPoints[dateTimeInitial]) / stockDataPoints[dateTimeInitial]);
         * }
         *
         * public double ChangeWeighedPercentageToLatest(IExchangeRate exchangeRate, TimeSpan timeSpan)
         * {
         * IDictionary<DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory;
         *
         * DateTime now = DateTime.Now;
         * DateTime dateTimeInitial = stockDataPoints.First(k => k.Key > now - timeSpan).Key;
         * List<KeyValuePair<DateTime,double>> entries = stockDataPoints.Where(k => k.Key > now - timeSpan).ToList();
         * List<double> weigthedChangesPercentage = entries.Average();
         *
         * List <double> weigthedChanges = new List<double>();
         * for (int i = 1; i < entries.Count; i++)
         * {
         * weigthedChanges.Add(entries[i].Value - entries[i - 1].Value);
         * }
         * return weigthedChanges.Average();
         *
         * return 100.0 * ((stockDataPoints.Last().Value - stockDataPoints[dateTimeInitial]) / stockDataPoints[dateTimeInitial]);
         * }
         *
         *
         * /*  public TrendStatus CalculateTrends(IExchangeRate exchangeRate, int divisor = 3)
         * {
         * Acceleration acceleration = new Acceleration()
         * }*/
        public TrendStatus CalculateTrend(IExchangeRate exchangeRate, int divisor = 3)
        {
            IDictionary <DateTime, double> stockDataPoints = exchangeRate.ExhangeHistory;

            if (stockDataPoints.Count() < MinimumSize && stockDataPoints.Count() < divisor)
            {
                return(TrendStatus.Keep);
            }

            IDictionary <DateTime, double> stockDataPointsDivided = exchangeRate.ExhangeHistory;

            DateTime now = DateTime.Now;
            IDictionary <double, double> stockDataPercentagePointsSeconds = new Dictionary <double, double>();

            int    count         = 0;
            double previousValue = double.NaN;

            foreach (KeyValuePair <DateTime, double> entry in stockDataPoints)
            {
                if (double.IsNaN(previousValue))
                {
                    previousValue = entry.Value;
                    continue;
                }

                if (count % divisor == 0)
                {
                    stockDataPercentagePointsSeconds.Add((now - entry.Key).TotalSeconds,
                                                         entry.Value == previousValue ? 0 : ((entry.Value - previousValue) / previousValue) * 100);
                }
                previousValue = entry.Value;
            }


            if (stockDataPercentagePointsSeconds.Count() < 2)
            {
                return(TrendStatus.Keep);
            }

            IDictionary <double, double> firstDerivatives;
            IDictionary <double, double> secondDerivatives;

            //CalculateDerivatives(stockDataPercentagePointsSeconds, out firstDerivatives, out secondDerivatives);


            /*String toString = String.Join("----", Enumerable.Range(0, stockDataPercentagePointsSeconds.Count).Select(index =>
             *           stockDataPercentagePointsSeconds.Values.ElementAt(index).ToString("N5") + ", " + firstDerivatives.Values.ElementAt(index).ToString("N5") + ", " +
             *           secondDerivatives.Values.ElementAt(index).ToString("N5"))); */


            /*
             * Console.WriteLine("\n");
             * Console.WriteLine("," +  + "," + + ",");
             * Console.WriteLine("\n");
             *
             */

            return(0);
        }
Esempio n. 9
0
 public int GetLargestValueInRegisters()
 {
     if (_registers.Count() == 0)
     {
         ProcessInstructions();
     }
     return(_registers.Values.Max());
 }
Esempio n. 10
0
        public static IDictionaryChangeResult <TKey> CompareTo <TKey, TValue>(this IDictionary <TKey, TValue> local,
                                                                              IDictionary <TKey, TValue> remote)
        {
            if (local == null)
            {
                throw new ArgumentNullException("local");
            }

            if (remote == null)
            {
                throw new ArgumentNullException("remote");
            }

            var changed = new List <TKey>(local.Count());
            var deleted = new List <TKey>(local.Count());

            Parallel.ForEach(local, localItem =>
            {
                /* Check if primary key exists in both local and remote
                 * and if so check if changed, if not it has been deleted
                 */

                TValue changeCandidate;

                if (remote.TryGetValue(localItem.Key, out changeCandidate)
                    ) // Enthält nach dem Beenden dieser Methode den Wert, der dem angegebenen Schlüssel zugeordnet ist
                {
                    // changeCanditate = meta des remote posts

                    // wenn der meta von remote und der meta von lokal gleich sind, dann keine Änderung
                    if (localItem.Value.Equals(changeCandidate))
                    {
                        return;
                    }

                    lock (changed)
                    {
                        changed.Add(localItem.Key);
                    }
                }
                else
                {
                    lock (deleted)
                    {
                        deleted.Add(localItem.Key);
                    }
                }
            });

            var inserted = remote
                           .AsParallel()
                           .Where(x => !local.ContainsKey(x.Key))
                           .Select(x => x.Key)
                           .ToList();

            return(new IDictionaryChangeResult <TKey>(deleted, changed, inserted));
        }
Esempio n. 11
0
 public override IEnumerable <string> GetDynamicMemberNames()
 {
     foreach (var name in dict.Keys)
     {
         yield return(name);
     }
     foreach (var index in Enumerable.Range(0, dict.Count()))
     {
         yield return(index.ToString(CultureInfo.InvariantCulture));
     }
 }
Esempio n. 12
0
        protected override void DoSolve(string input)
        {
            _hexagonCoords = new Dictionary <HexagonCoordinate, bool>();

            DoPart1(input);

            PartOneAnswer = _hexagonCoords.Count(x => x.Value).ToString();

            DoPart2();

            PartTwoAnswer = _hexagonCoords.Count(x => x.Value).ToString();
        }
Esempio n. 13
0
        private Page GetPage(PageKey pageKey, IDictionary <string, object> parameters = null)
        {
            Page page;

            ResolverOverride[] resolverOverrides = null;
            if (parameters != null && parameters.Count() > 0)
            {
                resolverOverrides = new ResolverOverride[parameters.Count()];
                for (int i = 0; i < parameters.Count(); i++)
                {
                    var dictionaryItem = parameters.ElementAt(i);
                    resolverOverrides[i] = new ParameterOverride(dictionaryItem.Key, dictionaryItem.Value);
                }
            }

            switch (pageKey)
            {
            case PageKey.Login:
                page = (Page)ContainerManager.Container.Resolve(typeof(Login), typeof(Login).ToString());
                break;

            case PageKey.Dashboard:
                page = (Page)ContainerManager.Container.Resolve(typeof(Dashboard), typeof(Dashboard).ToString());
                break;

            case PageKey.TrainingReport:
                page = (Page)ContainerManager.Container.Resolve(typeof(TrainingReport), typeof(TrainingReport).ToString());
                break;

            case PageKey.Admin:
                page = (Page)ContainerManager.Container.Resolve(typeof(Admin), typeof(Admin).ToString());
                break;

            case PageKey.ManageDriver:
                page = (Page)ContainerManager.Container.Resolve(typeof(ManageDriver), typeof(ManageDriver).ToString());
                break;

            case PageKey.System:
                page = (Page)ContainerManager.Container.Resolve(typeof(SystemView), typeof(SystemView).ToString());
                break;

            default:
                throw new ArgumentException(
                          $"No such page: {pageKey}. Did you forgot to register your view in Bootstrapper?", nameof(pageKey));
            }

            if (!_pages.ContainsKey(page.GetType()))
            {
                _pages.Add(page.GetType(), pageKey);
            }

            return(page);
        }
        public void Using_XDocument_Gets_All_Stored_Values()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, Lazy <XDocument> >
            {
                {
                    culture, new Lazy <XDocument>(() => new XDocument(
                                                      new XElement(
                                                          "language",
                                                          new XElement("area", new XAttribute("alias", "testArea1"),
                                                                       new XElement("key", new XAttribute("alias", "testKey1"), "testValue1"),
                                                                       new XElement("key", new XAttribute("alias", "testKey2"), "testValue2")),
                                                          new XElement("area", new XAttribute("alias", "testArea2"),
                                                                       new XElement("key", new XAttribute("alias", "blah1"), "blahValue1"),
                                                                       new XElement("key", new XAttribute("alias", "blah2"), "blahValue2")))))
                }
            }, s_loggerFactory.CreateLogger <LocalizedTextService>());

            IDictionary <string, string> result = txtService.GetAllStoredValues(culture);

            Assert.AreEqual(4, result.Count());
            Assert.AreEqual("testArea1/testKey1", result.ElementAt(0).Key);
            Assert.AreEqual("testArea1/testKey2", result.ElementAt(1).Key);
            Assert.AreEqual("testArea2/blah1", result.ElementAt(2).Key);
            Assert.AreEqual("testArea2/blah2", result.ElementAt(3).Key);
            Assert.AreEqual("testValue1", result["testArea1/testKey1"]);
            Assert.AreEqual("testValue2", result["testArea1/testKey2"]);
            Assert.AreEqual("blahValue1", result["testArea2/blah1"]);
            Assert.AreEqual("blahValue2", result["testArea2/blah2"]);
        }
        public IEnumerable <ChartItem> GetChart([NotNull] IThreatModel model, [NotNull] IDictionary <Guid, int> projectedSeverities)
        {
            IEnumerable <ChartItem> result = null;

            var severities = model.Severities?.ToArray();

            if ((severities?.Any() ?? false) && projectedSeverities.Any())
            {
                var list = new List <ChartItem>();

                var total = model.AssignedThreatTypes;
                foreach (var severity in severities)
                {
                    var count = projectedSeverities.Count(x => x.Value == severity.Id);

                    if (count > 0)
                    {
                        list.Add(new ChartItem(severity.Name, count, severity.BackColor));
                    }
                }

                if (list.Any())
                {
                    result = list;
                }
            }

            return(result);
        }
Esempio n. 16
0
 /// <summary>
 /// IDictionary を実装する型 a, b について等価な Key と Value の組み合わせ群を保持するか判定する。
 /// SequenceEqual と異なり列挙される順序の影響を受けない
 /// ref. https://stackoverflow.com/a/3928856/1211392
 /// </summary>
 /// <typeparam name="TK">Key の型</typeparam>
 /// <typeparam name="TV">Value の型</typeparam>
 /// <param name="a">比較において this となる IDictionary を実装する型のインスタンス</param>
 /// <param name="b">比較において this と比較される IDictionary を実装する型のインスタンス</param>
 /// <param name="c">TV型の等価判定関数。 null を与えた場合は EqualityComparer&lt;TV&gt;.Default を採用する</param>
 /// <returns>a, b が等価な Key と Value の組み合わせ群を保持する場合は true 、そうでなければ false</returns>
 public static bool UnorderedEqual <TK, TV>
     (this IDictionary <TK, TV> a
     , IDictionary <TK, TV> b
     , IEqualityComparer <TV> c = null
     )
 {
     if (a.Equals(b))
     {
         return(true);
     }
     if (a.Count() != b.Count())
     {
         return(false);
     }
     c = c ?? EqualityComparer <TV> .Default;
     foreach (var akv in a)
     {
         if (!b.TryGetValue(akv.Key, out TV bv))
         {
             return(false);
         }
         if (!c.Equals(akv.Value, bv))
         {
             return(false);
         }
     }
     return(true);
 }
Esempio n. 17
0
        public void ValidateAvailabilityIsDisplay()
        {
            IndexPage indexPage = new IndexPage(driver, url);

            LoginPage loginPage = indexPage.Header.ClickOnSignIn();

            indexPage = loginPage.Login("*****@*****.**", "1234");

            var manufacturesItems = indexPage.Header.GetManufacturerOptions();

            manufacturerOption = manufacturesItems.ElementAtOrDefault(2).webElement.Text;

            indexPage.Header.SelectManufacturer(manufacturerOption);

            CatalogItemsPage catalogItemPage = indexPage.Header.ClickOnSearchButton();

            catalogItemPage.AddtoCartbuttonInCatalog();

            Thread.Sleep(5000);

            CartPage CartMainPage = catalogItemPage.Header.ClickOnViewCart();

            Thread.Sleep(2000);

            CheckoutPage checkoutPage = CartMainPage.ProceedToCheckOut();

            Thread.Sleep(2000);
            IDictionary <string, string> availabiltyItemsTag = checkoutPage.AvailabiltyTagGet();

            Assert.IsTrue(availabiltyItemsTag.Count() > 0);
        }
Esempio n. 18
0
        private static int CalculateSeating()
        {
            var seatsChanged = 0;

            do
            {
                seatsChanged = 0;
                var nextSeats = new Dictionary <Coordinate, bool>(_seats);

                foreach (var seat in _seats)
                {
                    var nextSeat = ValidateRelativePosition(seat.Key);

                    if (nextSeat != seat.Value)
                    {
                        seatsChanged++;
                    }

                    nextSeats[seat.Key] = nextSeat;
                }

                _seats = new Dictionary <Coordinate, bool>(nextSeats);
            } while (seatsChanged != 0);

            return(_seats.Count(x => x.Value));
        }
Esempio n. 19
0
        /// <summary>
        /// Parse the value to json.
        /// </summary>
        /// <param name="value">Value to parse.</param>
        /// <returns>Json value.</returns>
        public static string ParseJson(IDictionary <string, IList <ConceptoRolPresentacion> > diccionarioListas)
        {
            if (diccionarioListas == null || diccionarioListas.Count() == 0)
            {
                return("{}");
            }
            var builderDictionary = new StringBuilder();

            foreach (var nombreLista in diccionarioListas.Keys)
            {
                var lista       = diccionarioListas[nombreLista];
                var builderList = new StringBuilder();
                foreach (var elemento in lista)
                {
                    var jsonElement = elemento.ToJson();
                    builderList.Append(", ");
                    builderList.Append(jsonElement);
                }
                var jsonLista = "[" + builderList.ToString().Substring(2) + "]";
                builderDictionary.Append(", \"");
                builderDictionary.Append(nombreLista);
                builderDictionary.Append("\" : ");
                builderDictionary.Append(jsonLista);
            }
            var json = "{" + builderDictionary.ToString().Substring(2) + "}";

            return(json);
        }
Esempio n. 20
0
        public bool WriteToDB()
        {
            int afftectedRows = 0;

            using (SQLiteConnection myconnection = new SQLiteConnection(SystemParameters.ConnectionString))
            {
                myconnection.Open();
                using (SQLiteTransaction tr = myconnection.BeginTransaction())
                {
                    using (SQLiteCommand mycommand = new SQLiteCommand(myconnection))
                    {
                        mycommand.Transaction = tr;
                        mycommand.CommandText = String.Format("DELETE FROM {0}", tableName);
                        mycommand.ExecuteNonQuery();
                        foreach (KeyValuePair <string, string> item in list)
                        {
                            mycommand.CommandText = String.Format("INSERT INTO {0} (resource_id, display_name) VALUES ('{1}','{2}')", tableName, item.Key, item.Value);
                            afftectedRows        += mycommand.ExecuteNonQuery();
                        }
                        tr.Commit();
                    }
                }
                myconnection.Close();
            }
            return((afftectedRows == list.Count()) ? true : false);
        }
Esempio n. 21
0
        public double  RemoveEdgeMax()
        {
            IDictionary <double, int> histogramresult = GetHistogramGraphNormalized();
            double NewMax = m_maxValue;

            if (histogramresult.ElementAt(histogramresult.Count - 1).Value > Threshold)
            {
                return(NewMax);
            }
            if (histogramresult.Count() < 2)
            {
                return(NewMax);
            }
            for (int i = histogramresult.Count - 2; i > 0; i--)
            {
                if (histogramresult.ElementAt(i).Value < Threshold)
                {
                    NewMax = (histogramresult.ElementAt(i).Key + histogramresult.ElementAt(i - 1).Key) / 2;
                }
                else
                {
                    break;
                }
            }

            return(NewMax);
        }
Esempio n. 22
0
        /// <summary>
        /// Compare 2 dictionnaire entre eux. Comparaison des clés et des valeurs
        /// </summary>
        public static bool DictionaryEqual <TKey, TValue>(this IDictionary <TKey, TValue> first, IDictionary <TKey, TValue> second)
        {
            if (first == second)
            {
                return(true);
            }
            if (first.IsNullOrEmpty() && second.IsNullOrEmpty())
            {
                return(true);
            }
            if ((first == null) || (second == null))
            {
                return(false);
            }
            if (first.Count() != second.Count())
            {
                return(false);
            }

            var comparer = EqualityComparer <TValue> .Default;

            foreach (KeyValuePair <TKey, TValue> kvp in first)
            {
                TValue secondValue;
                if (!second.TryGetValue(kvp.Key, out secondValue))
                {
                    return(false);
                }
                if (!comparer.Equals(kvp.Value, secondValue))
                {
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 23
0
    // TODO: If you ever figure out how to find the end of a BitStream, remove the count header from this.
    public static void Serialize(this BitStream @this, IDictionary <string, PlayerSnapshot> value)
    {
        if (@this.isWriting)
        {
            // Write count to stream first
            int count = value.Count();
            @this.Serialize(ref count);

            // Then write all deltas
            foreach (var item in value)
            {
                string guid = item.Key;
                @this.Serialize(ref guid);
                @this.Serialize(item.Value);
            }
        }
        else
        {
            // Read count from stream first
            int count = 0;
            @this.Serialize(ref count);

            // Then read all deltas
            for (int i = 0; i < count; i++)
            {
                string guid = null;
                @this.Serialize(ref guid);

                PlayerSnapshot snapshot = new PlayerSnapshot();
                @this.Serialize(snapshot);

                value.Add(guid, snapshot);
            }
        }
    }
Esempio n. 24
0
        void AppendDictionary(OperatorInfo op, bool explode, IDictionary <string, string> dictionary)
        {
            foreach (string key in dictionary.Keys)
            {
                this._Result.Append(key);
                if (explode)
                {
                    this._Result.Append('=');
                }
                else
                {
                    this._Result.Append(',');
                }
                this.AppendValue(dictionary[key], 0, op.AllowReserved);

                if (explode)
                {
                    this._Result.Append(op.Seperator);
                }
                else
                {
                    this._Result.Append(',');
                }
            }
            if (dictionary.Count() > 0)
            {
                this._Result.Remove(this._Result.Length - 1, 1);
            }
        }
Esempio n. 25
0
    // TODO: If you ever figure out how to find the end of a BitStream, remove the count header from this.
    public static void Serialize(this BitStream @this, IDictionary<string, PlayerSnapshot> value)
    {
        if (@this.isWriting)
        {
            // Write count to stream first
            int count = value.Count();
            @this.Serialize(ref count);

            // Then write all deltas
            foreach (var item in value)
            {
                string guid = item.Key;
                @this.Serialize(ref guid);
                @this.Serialize(item.Value);
            }
        }
        else
        {
            // Read count from stream first
            int count = 0;
            @this.Serialize(ref count);

            // Then read all deltas
            for (int i = 0; i < count; i++)
            {
                string guid = null;
                @this.Serialize(ref guid);

                PlayerSnapshot snapshot = new PlayerSnapshot();
                @this.Serialize(snapshot);

                value.Add(guid, snapshot);
            }
        }
    }
Esempio n. 26
0
 private void Alloc <T>()
 {
     if (_dictionary.Count(where => where.Key == typeof(T)) < 1)
     {
         _dictionary.Add(typeof(T), (new List <T>()));
     }
 }
Esempio n. 27
0
        private static IDictionary <string, string> Merge(IDictionary <string, string> inferedSegments, string[] uninferedSegments)
        {
            int remained = uninferedSegments.Count();

            if (remained == 0)
            {
                return(inferedSegments);
            }

            int index     = 0;
            int primaries = Segments.Count(i => i.Value.IsPrimary);

            return(inferedSegments.ToDictionary(k => k.Key, i =>
            {
                if (Segments[i.Key].IsPrimary)
                {
                    primaries--;
                }
                if (string.IsNullOrEmpty(i.Value) && (Segments[i.Key].IsPrimary || primaries < remained) && index < uninferedSegments.Length)
                {
                    remained--;
                    return uninferedSegments[index++];
                }
                //if (Segments[i.Key].IsPrimary && !string.IsNullOrEmpty(i.Value))
                //{
                //    return i.Value;
                //}

                return i.Value;
            }));
        }
Esempio n. 28
0
        /// <summary>
        /// Initializes the mapping of hashes to nodes.
        /// </summary>
        public void Initialize()
        {
            foreach (var server in _servers.Values.Where(x => x.IsDataNode))
            {
                const int weight = 1; //may change this later
                var       factor = Math.Floor(40 * _servers.Count() * weight / (double)_totalWeight);

                for (long n = 0; n < factor; n++)
                {
                    var bytes = Encoding.UTF8.GetBytes(server.EndPoint + "-" + n);
                    using (var md5 = MD5.Create())
                    {
                        var hash = md5.ComputeHash(bytes);
                        for (var j = 0; j < 4; j++)
                        {
                            var key = ((long)(hash[3 + j * 4] & 0xFF) << 24)
                                      | ((long)(hash[2 + j * 4] & 0xFF) << 16)
                                      | ((long)(hash[1 + j * 4] & 0xFF) << 8)
                                      | (uint)(hash[0 + j * 4] & 0xFF);

                            Hashes[key] = server;
                        }
                    }
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Generates srcML from a file
        /// </summary>
        /// <param name="fileNames">An enumerable of filenames</param>
        /// <param name="xmlFileName">the output file name</param>
        /// <param name="language">The language to use</param>
        /// <param name="namespaceArguments">additional arguments</param>
        /// <param name="extensionMapping">an extension mapping</param>
        public void GenerateSrcMLFromFiles(ICollection <string> fileNames, string xmlFileName, Language language, ICollection <UInt32> namespaceArguments, IDictionary <string, Language> extensionMapping)
        {
            UInt32 arguments = GenerateArguments(namespaceArguments);

            try {
                using (Archive srcmlArchive = new Archive()) {
                    if (Convert.ToBoolean(extensionMapping.Count()))
                    {
                        srcmlArchive.RegisterFileExtension(extensionMapping.ElementAt(0).Key, extensionMapping.ElementAt(0).Value.ToString());
                    }
                    foreach (string file in fileNames)
                    {
                        using (Unit srcmlUnit = new Unit()) {
                            srcmlUnit.SetUnitFilename(file);
                            srcmlUnit.SetUnitLanguage(LibSrcMLRunner.SrcMLLanguages.SRCML_LANGUAGE_CXX);
                            srcmlArchive.AddUnit(srcmlUnit);
                        }
                    }
                    srcmlArchive.SetOutputFile(xmlFileName);
                    RunSrcML(srcmlArchive, LibSrcMLRunner.SrcmlCreateArchiveFtF);
                }
            }
            catch (Exception e) {
                throw new SrcMLException(e.Message, e);
            }
        }
Esempio n. 30
0
 /// <summary>
 /// Nots the null and count gt Zero.
 /// </summary>
 /// <param name="argument">Argument.</param>
 /// <param name="argumentName">Argument name.</param>
 public static void NotNullAndCountGTZero <T>(IDictionary <string, T> argument, string argumentName)
 {
     if (argument == null || argument.Count() <= 0)
     {
         throw new ArgumentNullException(argumentName);
     }
 }
Esempio n. 31
0
            IList <IndexSegment> setupEdges(IList <int> vertxIndices)
            {
                IList <IndexSegment> indexList = new List <IndexSegment>();
                int boundLinesDictOffset       = 0;

                if (boundaryLinesDict == null)
                {
                    IEqualityComparer <IndexSegment> segCompare = new SegmentCompare();
                    boundaryLinesDict = new Dictionary <IndexSegment, int>(segCompare);
                }
                else
                {
                    boundLinesDictOffset = boundaryLinesDict.Count();
                }

                for (int ii = 0; ii < vertxIndices.Count; ++ii)
                {
                    IndexSegment segm;
                    if (ii == vertxIndices.Count - 1)
                    {
                        segm = new IndexSegment(vertxIndices[ii], vertxIndices[0]);
                    }
                    else
                    {
                        segm = new IndexSegment(vertxIndices[ii], vertxIndices[ii + 1]);
                    }
                    indexList.Add(segm);
                    boundaryLinesDict.Add(segm, ii + boundLinesDictOffset);  // boundaryLinesDict is a dictionary for the combined outer and inner boundaries, the values should be sequential
                }

                return(indexList);
            }
        private static void VerifyFieldCollection(IDictionary<string, object> fields) {
            fields.Count().Should().Be.GreaterThan(0);
            fields.Keys.Contains("_guid").Should().Be.True();
            fields.Keys.Contains("_id").Should().Be.True();

            fields.Keys.Contains("_name").Should().Be.True();
            fields["_name"].Should().Be("Widget No1");
        }
        private static void VerifyPropertyCollection(IDictionary<string, object> properties) {
            properties.Count().Should().Be.GreaterThan(0);
            properties.Keys.Contains("Guid").Should().Be.True();
            properties.Keys.Contains("DummyString").Should().Be.True();

            properties.Keys.Contains("Name").Should().Be.True();
            properties["Name"].Should().Be("Widget No1");
        }
        public static void AppendQueryArgs(this UriBuilder builder, IDictionary<string, string> args)
        {
            //Requires.NotNull(builder, "builder");

            if (args != null && args.Count() > 0)
            {
                var sb = new StringBuilder(50 + (args.Count() * 10));
                if (!string.IsNullOrEmpty(builder.Query))
                {
                    sb.Append(builder.Query.Substring(1));
                    sb.Append('&');
                }
                sb.Append(CreateQueryString(args));

                builder.Query = sb.ToString();
            }
        }
        private static IDictionary<int, PredictedPlayerScore> FillRemainingStartingPositions(IDictionary<int, PredictedPlayerScore> currentSelectedPlayers, IList<PredictedPlayerScore> playersNotYetSelected)
        {
            if (currentSelectedPlayers.Count() != 5) throw new ArgumentException("Should be 5 mandatory players already selected");
            if (playersNotYetSelected.Count() != 10) throw new ArgumentException("Should be 10 players available to complete team");

            const int PlayerCountRequired = 11 - 1 - GameConstants.MinimumDefendersInStartingTeam -
                                            GameConstants.MinimumForwardsInStartingTeam;

            var playersToSelect = playersNotYetSelected.Where(ps => ps.Player.Position != Position.Goalkeeper).OrderByDescending(ps => ps.PredictedScore).Take(PlayerCountRequired);
            foreach (var player in playersToSelect)
            {
                currentSelectedPlayers.Add(player.Player.Id, player);
            }

            return currentSelectedPlayers;
        }
Esempio n. 36
0
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters,
            int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //对服务端证书进行有效性检验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                ServicePointManager.ServerCertificateValidationCallback =
                    new System.Net.Security.RemoteCertificateValidationCallback(CheckValidateionResult);
                request.ProtocolVersion = HttpVersion.Version11;
            }
            request = WebRequest.Create(url) as HttpWebRequest;
            request.UserAgent = userAgent;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = timeout;

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            if (!(parameters == null) || parameters.Count() == 0)
            {
                StringBuilder buffer = new StringBuilder();
                bool flag = false;
                foreach (string key in parameters.Keys)
                {
                    if (flag)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        flag = true;
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                }
                byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            return request.GetResponse() as HttpWebResponse;
        }
Esempio n. 37
0
        public void AppendDictionary(OperatorInfo op, bool explode, IDictionary<string, string> dictionary)
        {
            foreach (string key in dictionary.Keys)
            {
                _Result.Append(Encode(key, op.AllowReserved));
                if (explode) _Result.Append('='); else _Result.Append(',');
                AppendValue(dictionary[key], 0, op.AllowReserved);

                if (explode)
                {
                    _Result.Append(op.Seperator);
                }
                else
                {
                    _Result.Append(',');
                }
            }
            if (dictionary.Count() > 0)
            {
                _Result.Remove(_Result.Length - 1, 1);
            }
        }
        internal static string CreateQueryString(IDictionary<string, string> args)
        {
            //Requires.NotNull(args, "args");

            if (!args.Any())
            {
                return string.Empty;
            }
            var sb = new StringBuilder(args.Count() * 10);

            foreach (var p in args)
            {
                ValidationHelper.VerifyArgument(!string.IsNullOrEmpty(p.Key), "Unexpected Null Or Empty Key");
                ValidationHelper.VerifyArgument(p.Value != null, "Unexpected Null Value", p.Key);
                sb.Append(EscapeUriDataStringRfc3986(p.Key));
                sb.Append('=');
                sb.Append(EscapeUriDataStringRfc3986(p.Value));
                sb.Append('&');
            }
            sb.Length--; // remove trailing &

            return sb.ToString();
        }
Esempio n. 39
0
        public void delete( DatabaseToken token, string table, IDictionary<string, object> constraints )
        {
            // Are there any binary columns in this table? If so, we need to pay attention
            // to eliminating the files from the file system too.
            IEnumerable<string> binaryCols = findBinaryColumns( table );
            if( binaryCols.Any() )
            {
            // Find the row we're going to delete.
            var results = selectRaw( MySqlToken.Crack( token ), table, constraints );
            if( !results.Any() )
                return;

            deleteBinaryColumns( table, binaryCols, results );
            }

            string sql =  CultureFree.Format( "delete from {0}", table );
            if( constraints.Count() > 0 )
            sql += makeWhereClause( constraints );

            // Add in the updated values, plus the ID for the where clause.
            MySqlCommand cmd = new MySqlCommand( sql, MySqlToken.Crack( token ) );
            insertQueryParameters( cmd, table, constraints );

            // Do the delete.
            cmd.ExecuteNonQuery();
        }
 /// <summary>
 /// 将多张图片组合成一个GIF动画
 /// </summary>
 /// <param name="image">底图</param>
 /// <param name="images">图片字典(Keys:图片集合;Values:帧延迟)</param>
 /// <param name="zoom">等比缩放</param>
 /// <param name="loopCount">GIF循环次数(0为无限循环)</param>
 /// <returns></returns>
 public static Image Combine(this Image image, IDictionary<Image, int> images, bool zoom = true, int loopCount = 0)
 {
     if (loopCount < 0)
         throw new ArgumentException("必须为非负整数值!", "loopCount");
     if (images != null && images.Count() > 0)
     {
         AnimatedGifEncoder animatedGifEncoder = new AnimatedGifEncoder();
         MemoryStream memoryStream = new MemoryStream();
         animatedGifEncoder.Start(memoryStream);
         animatedGifEncoder.SetRepeat(loopCount);
         animatedGifEncoder.SetDelay(0);
         animatedGifEncoder.AddFrame(image);
         foreach (Image img in images.Keys)
         {
             Image frame = Resize(img, image.Width, image.Height, zoom);
             animatedGifEncoder.SetDelay(images[img]);
             animatedGifEncoder.AddFrame(frame);
         }
         animatedGifEncoder.Finish();
         return Image.FromStream(memoryStream);
     }
     else
         return image;
 }
Esempio n. 41
0
 /// <summary>
 /// Generates srcML from a file
 /// </summary>
 /// <param name="fileNames">An enumerable of filenames</param>
 /// <param name="xmlFileName">the output file name</param>
 /// <param name="language">The language to use</param>
 /// <param name="namespaceArguments">additional arguments</param>
 /// <param name="extensionMapping">an extension mapping</param>
 public void GenerateSrcMLFromFiles(ICollection<string> fileNames, string xmlFileName, Language language, ICollection<UInt32> namespaceArguments, IDictionary<string, Language> extensionMapping) {
     UInt32 arguments = GenerateArguments(namespaceArguments);
     try {
         using (Archive srcmlArchive = new Archive()) {
             if (Convert.ToBoolean(extensionMapping.Count())) {
                 srcmlArchive.RegisterFileExtension(extensionMapping.ElementAt(0).Key, extensionMapping.ElementAt(0).Value.ToString());
             }
             foreach (string file in fileNames) {
                 using (Unit srcmlUnit = new Unit()) {
                     srcmlUnit.SetUnitFilename(file);
                     srcmlUnit.SetUnitLanguage(LibSrcMLRunner.SrcMLLanguages.SRCML_LANGUAGE_CXX);
                     srcmlArchive.AddUnit(srcmlUnit);
                 }
             }
             srcmlArchive.SetOutputFile(xmlFileName);
             RunSrcML(srcmlArchive, LibSrcMLRunner.SrcmlCreateArchiveFtF);
         }
     }
     catch (Exception e) {
         throw new SrcMLException(e.Message, e);
     }
 }
Esempio n. 42
0
 protected string GetStringsString(IDictionary<int, string> value)
 {
     if (value == null || value.Count() == 0)
     {
         return string.Empty;
     }
     StringBuilder sb = new StringBuilder();
     foreach (var val in value)
     {
         sb.Append(val.Key);
         sb.Append(";;;");
         sb.Append(val.Value);
         sb.Append(";;;");
     }
     var result = sb.ToString();
     return result;
 }
 private static void CloneStringParameters(string sourceName, string targetName, IDictionary<string, object> parameters)
 {
     List<string> keys = parameters.Keys.ToList();
     for (int idx = 0; idx < parameters.Count(); idx++)
     {
         if (parameters[keys[idx]] is string)
         {
             if ((parameters[keys[idx]] as string).Contains(sourceName))
             {
                 parameters[keys[idx]] = (parameters[keys[idx]] as string).Replace(sourceName, targetName);
             }
         }
     }
 }
 public static void RandomlyChange(int minPercentageOfSituation, int maxPercentageOfSituation, IDictionary<Situation, RobotAction> strategy)
 {
     int itemsToChange = (int)(strategy.Count() * random.Next(minPercentageOfSituation, maxPercentageOfSituation+1) / 100.0);
     for (int i = 0; i < itemsToChange; i++)
     {
         Situation situationToRandonlyChange = GetRandomSituation();
         RobotAction action = GetRandomAction();
         strategy[situationToRandonlyChange] = action;
     }
 }
        int LoadFileLists()
        {
            int trackCount = 0;
            try
            {
                _trackFileLists = new Dictionary<string, SortedList<int, string>>();

                DirectoryInfo rootdi = new DirectoryInfo(FileDirectory);
                int insertIdx = 0;
                foreach (var di in rootdi.GetDirectories())
                {
                    var trackFiles = new SortedList<int, string>();
                    foreach (var fi in di.GetFiles("*.*", SearchOption.AllDirectories).OrderBy((f) => Convert.ToInt32(f.Name.Split('-')[0])))
                    {
                        trackFiles.Add(insertIdx++, fi.FullName);
                    }
                    _trackFileLists.Add(di.Name, trackFiles);
                }
                trackCount = _trackFileLists.Count();
            }
            catch (Exception ex)
            {
                OnTcpServerError(ex);
            }
            return trackCount;
        }
Esempio n. 46
0
        private phosphoRS.PTMResultClass RunOnSource(string sourceFilepath, int currentSource, int totalSources, PhosphoRSConfig config, IDictionary<long, PhosphoPeptideAttestationRow> phosphoRows)
        {
            var msd = new pwiz.CLI.msdata.MSDataFile(sourceFilepath);
            var spectrumList = msd.run.spectrumList;

            int rowNumber = 0;
            int totalRows = phosphoRows.Count();
            items.Clear();

            var spectrumTypes = new Set<CVID>();

            foreach (var row in phosphoRows)
            {
                if (rowNumber == 0 || (rowNumber % 100) == 0)
                {
                    if (cancelAttestation.IsCancellationRequested)
                    {
                        this.progressBar.ProgressBar.Visible = false;
                        _bgWorkerCancelled = true;
                        setProgress(-1, "Cancelled.");
                        return null;
                    }
                    else
                    {
                        if (rowNumber == 0)
                            setStatus(String.Format("Reading peaks and creating PhosphoRS objects for source {0} of {1} ({2}): {3} spectra\r\n", currentSource, totalSources, Path.GetFileName(sourceFilepath), totalRows));
                        setProgress((rowNumber + 1) / totalRows * 100, String.Format("Reading peaks and creating PhosphoRS objects for source {0} of {1} ({2}): {3}/{4} spectra", currentSource, totalSources, Path.GetFileName(sourceFilepath), rowNumber + 1, totalRows));
                    }
                }

                var pwizSpectrum = spectrumList.spectrum(spectrumList.find(row.Value.SpectrumNativeID), true); //may create indexoutofrange error if no spectrum nativeID                   

                var OriginalMZs = pwizSpectrum.getMZArray().data; //getMZArray().data returns IList<double>
                var OriginalIntensities = pwizSpectrum.getIntensityArray().data;
                row.Value.Peaks = new phosphoRS.Peak[OriginalMZs.Count];
                for (int i = 0; i < OriginalMZs.Count; ++i)
                    row.Value.Peaks[i] = new phosphoRS.Peak(OriginalMZs[i], OriginalIntensities[i]);

                if (config.spectrumType == phosphoRS.SpectrumType.None)
                {
                    row.Value.SpectrumType = phosphoRS.SpectrumType.None;
                    foreach (var precursor in pwizSpectrum.precursors)
                        foreach (var method in precursor.activation.cvParamChildren(CVID.MS_dissociation_method))
                        {
                            // if dissociation method is set to "Auto" but could not be determined from the file, alert the user
                            if (!spectrumTypeByDissociationMethod.Contains(method.cvid))
                                throw new InvalidDataException("cannot handle unmapped dissociation method \"" + CV.cvTermInfo(method.cvid).shortName() + "\" for spectrum \"" + row.Value.SourceName + "/" + row.Value.SpectrumNativeID + "\"; please override the method manually");
                            else if (row.Value.SpectrumType != phosphoRS.SpectrumType.ECD_ETD) // don't override ETD (e.g. if there is also supplemental CID)
                            {
                                row.Value.SpectrumType = spectrumTypeByDissociationMethod[method.cvid];
                                spectrumTypes.Add(method.cvid);
                            }
                        }

                    if (row.Value.SpectrumType == phosphoRS.SpectrumType.None)
                        throw new InvalidDataException("cannot find a dissociation method for spectrum \"" + row.Value.SourceName + "/" + row.Value.SpectrumNativeID + "\"; please set the method manually");
                }
                else
                    row.Value.SpectrumType = config.spectrumType;

                var psm = getPhosphoRS_PSM(config, row.Value);

                // DEBUG
                //tbStatus.AppendText(PeptideToString(phosphoPeptide) + "," + AAS.ToOneLetterCodeString() + "," + ptmRepresentation.ToString() + "\n");
                // Init the mod map of original variant for this PSM.
                var id2ModMap = new List<System.Tuple<int, List<int>>> { new System.Tuple<int, List<int>>((int) row.Value.PSMId, row.Value.OriginalPhosphoSites.Keys.ToList<int>()) };

                items.Add(new System.Tuple<phosphoRS.PeptideSpectrumMatch, List<System.Tuple<int, List<int>>>>(psm, id2ModMap));

                ++rowNumber;
            }

            // report automatically found fragmentation method
            if (config.spectrumType == phosphoRS.SpectrumType.None)
                setStatus(String.Format("Found {0} fragmentation types: {1}\r\n", spectrumTypes.Count, String.Join(", ", spectrumTypes.Keys.Select(o => CV.cvTermInfo(o).shortName()))));

            setProgress(currentSource / totalSources * 100, String.Format("Running PhosphoRS on source {0} of {1} ({2})...", currentSource, totalSources, Path.GetFileName(sourceFilepath)));

            // Initialize the localization.
            currentNr = 0;
            var phosphoRS_Context = new phosphoRS.ThreadManagement(this, cancelAttestation, config.maxIsoformCount, config.maxPTMCount, config.scoreNLToo, config.fragmentMassTolerance, config.scoredAA, items.Count);

            // Start the site localization (takes advantage of multi-threading)
            try
            {
                phosphoRS_Context.StartPTMLocalisation();

                // Safety if the attestation module doesn't throw the exception.
                if (cancelAttestation.IsCancellationRequested)
                {
                    this.progressBar.ProgressBar.Visible = false;
                    _bgWorkerCancelled = true;
                    setProgress(-1, "Cancelled.");
                    return null;
                }

                return phosphoRS_Context.PTMResult;
            }
            catch (OperationCanceledException)
            {
                this.progressBar.ProgressBar.Visible = false;
                _bgWorkerCancelled = true;
                setProgress(-1, "Cancelled.");
                return null;
            }
            finally
            {
                msd.Dispose();
            }
        }
Esempio n. 47
0
 private void CheckFields(IDictionary<string, string> expected, IDictionary<string, string> actual)
 {
     foreach (var field in expected)
     {
         if (field.Value != null)
         {
             Assert.IsTrue(actual.ContainsKey(field.Key), string.Format("Record is not complete. Missing field \"{0}\".", field.Key));
             Assert.AreEqual(field.Value, actual[field.Key], string.Format("Wrong value for field \"{0}\".", field.Key));
         }
         else
         {
             Assert.IsFalse(actual.ContainsKey(field.Key), string.Format("Unexpected field \"{0}\" (value: \"{1}\").", field.Key, field.Value));
         }
     }
     Assert.AreEqual(expected.Count(f => f.Value != null), actual.Count, "Unexpected count of fields.");
 }
Esempio n. 48
0
        private async Task GetChannels()
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri(string.Format("https://{0}.slack.com", _team)),

            };
            var response = await
                client.GetAsync(new Uri(string.Format("api/channels.list?token={0}&pretty=1",
                    _userToken), UriKind.Relative));

            var content = await response.Content.ReadAsStringAsync();
            var json = JToken.Parse(content);
            if (!json["ok"].Value<bool>())
            {
                Logger.Warn("Could not fetch list of channels. You may find issues with mmbot not speaking in channels until messages have been posted there.");
                return;
            }
            
            _channelMapping = json["channels"].ToDictionary(c => c["name"].ToString(), c => c["id"].ToString());

            Logger.Info(string.Format("Discovered {0} Slack rooms", _channelMapping.Count()));
        }
Esempio n. 49
0
        // This does the actual select work, returning the rows in raw form from the
        // database. We do this separately because it's used in deletion below.
        IDictionary<ulong, IDictionary<string, object>> selectRaw( MySqlConnection conn, string table, IDictionary<string, object> constraints )
        {
            // Build a parameterized SQL query.
            string sql =  CultureFree.Format( "select * from {0}", table );
            if( constraints.Count() > 0 )
            sql += makeWhereClause( constraints );

            MySqlCommand cmd = new MySqlCommand( sql, conn );
            insertQueryParameters( cmd, table, constraints );

            var rv = new Dictionary<ulong, IDictionary<string, object>>();
            string pkName = _tableInfo.getIdColumn( table );
            using( MySqlDataReader rdr = cmd.ExecuteReader() )
            {
            string[] columnNames = null;
            while( rdr.Read() )
            {
                if( columnNames == null )
                {
                    columnNames = new string[rdr.FieldCount];
                    for( int i=0; i<rdr.FieldCount; ++i )
                        columnNames[i] = rdr.GetName( i );
                }

                ulong pkId = (ulong)rdr[pkName];
                var row = new Dictionary<string, object>();
                foreach( string col in columnNames )
                    row[col] = rdr[col];

                rv[pkId] = row;
            }
            }

            return rv;
        }
Esempio n. 50
0
 private ISnail pickRandomSnail(IDictionary<ISnail, List<int>> race)
 {
     return race.Keys.ElementAt(random.Next(race.Count()));
 }
 public static void RandomlyChange(float percentageOfSituations, IDictionary<Situation, RobotAction> strategy)
 {
     int itemsToChange = (int) (strategy.Count()*percentageOfSituations/100.0);
     for (int i = 0; i < itemsToChange; i++)
     {
         Situation situationToRandonlyChange = GetRandomSituation();
         RobotAction action = GetRandomAction();
         strategy[situationToRandonlyChange] = action;
     }
 }
        public async Task Get_Files(string basePath, IDictionary<string, string> files, string keyPrefix, bool recursive, IDictionary<string, ItemType> expectedFiles) {
            var provider = GetProvider(basePath);
            var config = GetConfig(basePath);

            foreach (var file in files) {
                var filePath = Path.Combine(basePath, file.Key);
                var fileData = new MockFileData(file.Value) {
                    LastWriteTime = DateTime.UtcNow
                };

                this.mockFileSystem.AddFile(filePath, fileData);
            }

            var actualFiles = await provider.GetItemsAsync(config, keyPrefix: keyPrefix, recursive: recursive);

            Assert.Equal(expectedFiles.Count, actualFiles.Count());
            Assert.Equal(expectedFiles.Count(f => f.Value == ItemType.File), actualFiles.Count(f => f.Type == ItemType.File));
            Assert.Equal(expectedFiles.Count(f => f.Value == ItemType.Directory), actualFiles.Count(f => f.Type == ItemType.Directory));
            Assert.Equal(expectedFiles.Keys, actualFiles.Select(a => a.Key));
        }
Esempio n. 53
0
        //查询条件
        public static List<string> GetCommonCondition(IDictionary[] conditions)
        {
            if (conditions != null && conditions.Count() > 0)
            {
                //var l1 = conditions.Where(d1 => !string.IsNullOrEmpty(Convert.ToString((object)d1["val"]))).ToList();
                //if (l1.Count > 0)
                //{
                //var l2 = from d1 in l1
                //         select string.Format((string)d1["format"], d1["val"]);
                //return l2.ToList();
                List<string> list = new List<string>();

                foreach (var item in conditions)
                {
                    //if (item.Count == 2)
                    //{
                    //    if (item["val"] != null && !string.IsNullOrEmpty(item["val"].ToString()))
                    //    {
                    //        if (item["val"].GetType().Name.ToLower() == "datetime")
                    //            list.Add(string.Format((string)item["format"], ((DateTime)item["val"]).ToString("yyyy-MM-dd")));
                    //        else if (item["val"].GetType().Name.ToLower() == "int32")
                    //            list.Add(string.Format((string)item["format"], ((Int32)item["val"]).ToString()));

                    //        else
                    //            list.Add(string.Format((string)item["format"], string.IsNullOrEmpty(((string)item["val"])) ? "" : ((string)item["val"]).Replace("&lt;", "<").Replace("&gt;", ">")));
                    //    }
                    //}

                    List<string> listCon = new List<string>();
                    int items = item.Count;
                    string sqlpara = string.Empty;
                    for (int i = 0; i < item.Count / 2; i++)
                    {

                        string fFormat = "format";
                        string fVal = "val";
                        if (i > 0)
                        {
                            fFormat = fFormat + i.ToString();
                            fVal = fVal + i.ToString();
                        }
                        if (item[fVal] != null)
                        {
                            if (!string.IsNullOrEmpty(item[fVal].ToString()))
                            {
                                if (item[fVal].GetType().Name.ToLower() == "datetime")
                                    listCon.Add(string.Format((string)item[fFormat], ((DateTime)item[fVal]).ToString("yyyy-MM-dd")));
                                else if (item[fVal].GetType().Name.ToLower() == "int32")
                                    listCon.Add(string.Format((string)item[fFormat], ((Int32)item[fVal]).ToString()));

                                else
                                    listCon.Add(string.Format((string)item[fFormat], string.IsNullOrEmpty(((string)item[fVal])) ? "" : ((string)item[fVal]).Replace("&lt;", "<").Replace("&gt;", ">").Trim()));
                            }
                        }
                    }
                    if (items > 2)
                    {
                        if (listCon.Count > 0)
                        {
                            sqlpara = sqlpara + string.Join(" or ", listCon);
                            sqlpara = "( " + sqlpara + ")";
                            list.Add(sqlpara);
                        }

                    }
                    else
                    {
                        if (listCon.Count > 0)
                            list.Add(listCon.First());
                    }

                }
                return list;
                //}
            }
            return new List<string>();
        }
 private void AssertCreation(IDictionary<string, string> dict)
 {
     Assert.AreEqual(2, dict.Count());
      var actual = dict
                 .Where(x => x.Key.EndsWith("Customer2.g.cs"))
                 .First()
                 .Value ;
      actual = StringUtilities.RemoveFileHeaderComments(actual);
      Assert.AreEqual(expected1, actual);
      actual = dict
                 .Where(x => x.Key.EndsWith("Customer.g.cs"))
                 .First()
                 .Value;
      actual = StringUtilities.RemoveFileHeaderComments(actual);
      Assert.AreEqual(expected2, actual);
 }
Esempio n. 55
0
        private void GetDataFields(Type type, IDictionary<string, IDataField> fields, INestedDataField parent)
        {
            var members =
                type.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetField | BindingFlags.SetProperty);
            var count = members.Length;

            Dictionary<MemberInfo, IGetterSetter> accessors;
            if (count < DynamicMaximumMembers && type.IsClass)
            {
                // only create dynamic accessors if there are less than x members
                accessors = AccessorMgr.GetOrCreateAccessors(type);
            }
            else
            {
                accessors = null;
            }

            foreach (var member in members)
            {
                if (member.IsReadonly())
                {
                    continue;
                }

                if (member.GetCustomAttributes<NotPersistentAttribute>().Length > 0)
                {
                    continue;
                }

                var dbAttrs = member.GetCustomAttributes<DBAttribute>();
                var persistentAttribute = dbAttrs.Where(attribute => attribute is PersistentAttribute).FirstOrDefault() as PersistentAttribute;
                if (persistentAttribute == null && m_Attribute.RequirePersistantAttr)
                {
                    // DataHolder only maps fields/properties with PersistantAttribute
                    continue;
                }

                var rawType = member.GetVariableType();
                var isArr = rawType.IsArray;

                string varName;
                IGetterSetter accessor;
                IFieldReader reader;
                Type memberType;
                if (persistentAttribute != null)
                {
                    // persistent attribute
                    memberType = persistentAttribute.ActualType ?? member.GetActualType();
                    varName = persistentAttribute.Name ?? member.Name;
                    if (persistentAttribute.AccessorType != null)
                    {
                        var accessorObj = Activator.CreateInstance(persistentAttribute.AccessorType);
                        if (!(accessorObj is IGetterSetter))
                        {
                            throw new DataHolderException("Accessor for Persistent members must be of type IGetterSetter - "
                                + "Found accessor of type {0} for member {1}", accessorObj.GetType(), member.GetFullMemberName());
                        }
                        accessor = (IGetterSetter)accessorObj;
                    }
                    else
                    {
                        accessor = accessors != null ? accessors[member] : new DefaultVariableAccessor(member);
                    }
                    reader = Converters.GetReader(persistentAttribute.ReadType ?? memberType);
                }
                else
                {
                    memberType = member.GetActualType();
                    varName = member.Name;
                    //accessor = new DefaultVariableAccessor(member);
                    accessor = (accessors != null ? accessors[member] : new DefaultVariableAccessor(member));
                    reader = Converters.GetReader(memberType);
                }

                // check array constraints
                if (isArr)
                {
                    if (rawType.GetArrayRank() > 1 || memberType.IsArray)
                    {
                        throw new DataHolderException("Cannot define Type {0} of {1} because its a multi-dimensional Array.", rawType,
                                                      member.GetFullMemberName());
                    }
                }

                IDataField field;
                if (reader == null)
                {
                    // create reader
                    if (type.IsAbstract)
                    {
                        throw new DataHolderException(
                            "Cannot define member \"{0}\" of DataHolder \"{1}\" because it's Type ({2}) is abstract.",
                            member.GetFullMemberName(), this, memberType.FullName);
                    }

                    IProducer producer;
                    if (memberType.IsClass)
                    {
                        producer = CreateProducer(memberType);
                    }
                    else
                    {
                        // value type does not need a producer
                        producer = null;
                    }

                    if (isArr)
                    {
                        // complex (nested) type
                        var length = GetArrayLengthByAttr(persistentAttribute, member);
                        var nestedField = new NestedArrayDataField(this, varName, accessor, member,
                                                                   producer, CreateArrayProducer(memberType, length), length, parent);

                        var dataFields = new Dictionary<string, IDataField>(StringComparer.InvariantCultureIgnoreCase);
                        //Console.WriteLine("Getting field for: " + nestedField);

                        GetDataFields(memberType, dataFields, nestedField);
                        foreach (var dataField in dataFields.Values)
                        {
                            for (var i = 0; i < nestedField.ArrayAccessors.Length; i++)
                            {
                                var arrAccessor = (NestedArrayAccessor)nestedField.ArrayAccessors[i];
                                var newField = ((DataFieldBase)dataField).Copy(arrAccessor);
                                arrAccessor.InnerFields.Add(newField.Name, newField);
                            }
                        }

                        field = nestedField;
                    }
                    else
                    {
                        // simple nested type
                        var nestedField = new NestedSimpleDataField(this, varName, accessor, member, producer, parent);
                        //Console.WriteLine("Getting field for: " + nestedField);

                        GetDataFields(memberType, nestedField.InnerFields, nestedField);
                        if (nestedField.InnerFields.Count == 0)
                        {
                            throw new DataHolderException("Cannot define " + member.GetFullMemberName() +
                                                          " as Nested because it does not have any inner fields.");
                        }
                        else
                        {
                            field = nestedField;
                        }
                    }
                }
                else
                {
                    if (isArr)
                    {
                        //var nestedField = new (this, varName, accessor, member, producer, parent);
                        var length = GetArrayLengthByAttr(persistentAttribute, member);
                        field = new FlatArrayDataField(this, varName, accessor,
                            member, length,
                            CreateArrayProducer(memberType, length),
                            parent);
                    }
                    else
                    {
                        field = new FlatSimpleDataField(this, varName, accessor, member, parent);
                        if (varName == m_DependingFieldName)
                        {
                            m_DependingField = (FlatSimpleDataField)field;
                        }
                    }
                }

                fields.Add(field.Name, field);
            }

            if (fields.Count() - count == 0)
            {
                throw new ArgumentException("Invalid data Type has no persistent members: " + type.FullName);
            }
        }
        protected void InvokeKvpOperation(IDictionary<String, Object> args, IDictionary<String, Object> data, String operationName)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (data.Count() == 0)
            {
                return;
            }

            var kvpItems = ToKvpItems(data);
            using (var vmMgmt = WMIHelper.GetFirstInstance(WMI_Namespace, WMI_Class_Msvm_VirtualSystemManagementService))
            using (var vm = WMIHelper.QueryFirstInstacne(WMI_Namespace, WMI_Class_Msvm_ComputerSystem, String.Format("Name='{0}'", args["VirtualMachineName"])))
            {
                if(batchMode)
                {
                    InvokeKvpOperation(vmMgmt, vm, operationName, kvpItems);
                }
                else
                {
                    foreach (var kvpItem in kvpItems)
                    {
                        InvokeKvpOperation(vmMgmt, vm, operationName, new String[] { kvpItem });
                    }
                }

            }
        }