private RiskRateDetail getRiskRateDetail(int actualSumAssured, OrderedDictionary dictionary) { RiskRateDetail riskRateDetail = null; for (var index = 0; index < dictionary.Keys.Count; index++) { int lowerBandSumAssured = (int)dictionary.Cast <DictionaryEntry>().ElementAt(index).Key; decimal lowerBandRiskRate = (decimal)dictionary[index]; int nextIndex = index + 1; int upperBandSumAssured = (int)dictionary.Cast <DictionaryEntry>().ElementAt(nextIndex).Key; decimal upperBandRiskRate = (decimal)dictionary[nextIndex]; if (actualSumAssured >= lowerBandSumAssured && actualSumAssured <= upperBandSumAssured) { riskRateDetail = new RiskRateDetail( actualSumAssured, lowerBandSumAssured, lowerBandRiskRate, upperBandSumAssured, upperBandRiskRate ); break; } } return(riskRateDetail); }
public IEnumerator <KeyValuePair <object, object> > GetEnumerator() { return(elements .Cast <DictionaryEntry>() .Select(entry => new KeyValuePair <object, object>(entry.Key, entry.Value)) .GetEnumerator()); }
static void CollectMessageOptions(OrderedDictionary messageOptions, int i) { string message = messageOptions.Cast <DictionaryEntry>().ElementAt(i).Key.ToString(); int indexFirstOpenBracket = message.IndexOf('('); int indexSecondOpenBracket = message.IndexOf('(', indexFirstOpenBracket + 1); int indexFirstClosedBracket = message.IndexOf(')'); // Check for nested brackets (i.e.: if there is a second open bracket before the first closed bracket). // The expression within the inner brackets should be dissolved first while (indexSecondOpenBracket < indexFirstClosedBracket && indexSecondOpenBracket != -1) { indexFirstOpenBracket = indexSecondOpenBracket; indexSecondOpenBracket = message.IndexOf('(', indexFirstOpenBracket + 1); } // If the inner expression is found, get the substring string messageSubstring = message.Substring(indexFirstOpenBracket, (indexFirstClosedBracket - indexFirstOpenBracket + 1)); // Remove the brackets and split the substring per option (|) string[] messageSubstringArr = messageSubstring.Replace("(", string.Empty).Replace(")", string.Empty).Split("|"); // Add new options to the dictionary of valid messages foreach (string substring in messageSubstringArr) { string result = message.Substring(0, indexFirstOpenBracket) + substring + message.Substring(indexFirstClosedBracket + 1); if (!messageOptions.Contains(result)) { messageOptions.Add(result, 0); } } // Remove checked index in the dictionary messageOptions.RemoveAt(i); }
internal static IDictionary <string, string> GenerateSampleData(IDataView dataView, ColumnInferenceResults columnInference) { var featureColumns = dataView.Schema.ToList().FindAll( col => col.Name != columnInference.ColumnInformation.LabelColumnName && !columnInference.ColumnInformation.IgnoredColumnNames.Contains(col.Name)); var rowCursor = dataView.GetRowCursor(featureColumns); OrderedDictionary sampleData = new OrderedDictionary(); // Get normalized and unique column names. If there are duplicate column names, the // differentiator suffix '_col_x' will be added to each column name, where 'x' is // the load order for a given column. List <string> normalizedColumnNames = GenerateColumnNames(featureColumns.Select(column => column.Name).ToList()); foreach (string columnName in normalizedColumnNames) { sampleData[columnName] = null; } if (rowCursor.MoveNext()) { var getGetGetterMethod = typeof(Utils).GetMethod(nameof(Utils.GetValueFromColumn), BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); // Access each feature column name through its index in featureColumns // as there may exist duplicate column names. In this case, sampleData // column names may have the differentiator suffix of '_col_x' added, // which requires access to each column name in through its index. for (int i = 0; i < featureColumns.Count(); i++) { var getGenericGetGetterMethod = getGetGetterMethod.MakeGenericMethod(featureColumns[i].Type.RawType); string val = getGenericGetGetterMethod.Invoke(null, new object[] { rowCursor, featureColumns[i] }) as string; sampleData[i] = val; } } return(sampleData.Cast <DictionaryEntry>().ToDictionary(k => (string)k.Key, v => (string)v.Value)); }
public void Update() { if (m_bDemo) { m_fTimeElapsed += Time.deltaTime; if (m_fTimeElapsed >= NM_EVENT_TIMEOUT) { System.Random ran = new System.Random(); int nPos = ran.Next(m_dicPenLight.Keys.Count - 1); string strID = (string)m_dicPenLight.Cast <DictionaryEntry>().ElementAt(nPos).Key; UserObject uo = GetUserObject(strID); StartVolumetricLine(uo); m_fTimeElapsed = 0.0f; } } foreach (string strJson in m_listJsonQueue) { MessageEvent(strJson); } m_listJsonQueue.Clear(); foreach (UserObject uo in m_dicPenLight.Values) { UpdateVolumetricLine(uo); UpdatePopup(uo); } }
public SaveMatchupEventsToDB(OrderedDictionary combinedEventTimings, int matchupId) { using (var context = new SportsSimulatorDBEntities()) { for (int i = 0; i < combinedEventTimings.Count; i++) { var _eventTiming = (TimeSpan)combinedEventTimings.Cast <DictionaryEntry>().ElementAt(i).Key; var _events = (List <Event>)combinedEventTimings.Cast <DictionaryEntry>().ElementAt(i).Value; for (int j = 0; j < _events.Count; j++) { context.spEventTimings_Insert(matchupId, _eventTiming, _events[j].id); } } } }
public IEnumerator <IGrouping <string, string> > GetEnumerator() { var pairs = from pair in headers.Cast <DictionaryEntry>() from value in (List <string>)pair.Value group value by(string) pair.Key; return(pairs.GetEnumerator()); }
public static object KeyFromIndex(this OrderedDictionary dictionary, int index) { if (index == -1) { return(null); } return((dictionary.Count > index) ? dictionary.Cast <DictionaryEntry>().ElementAt(index).Key : null); }
public void CheckCats() { //mock json for generation of cats data structure //adding sarah string mockJson = File.ReadAllText(Environment.CurrentDirectory + "\\Resources\\MockJSON.txt"); CatFinder.Filters.Cats catFactory = new CatFinder.Filters.Cats(); ExtractCats cats = catFactory.getCats; //4 left empty to test null values OrderedDictionary catTable = cats.ExtractCatsFromJson(mockJson); // should be two entries Assert.IsTrue(catTable.Count == 2); //check that the keys are correct Assert.IsTrue(catTable.Cast <DictionaryEntry>().ElementAt(0).Key.ToString() == "Male"); Assert.IsTrue(catTable.Cast <DictionaryEntry>().ElementAt(1).Key.ToString() == "Female"); Console.WriteLine(catTable[0]); //should be 4 male owned cats and 3 female owned cats Assert.IsTrue(((IList)catTable[0]).Count == 4); Assert.IsTrue(((IList)catTable[1]).Count == 3); //create array of cat names in expected order string[] mNameList = new string[] { "Garfield", "Jim", "Max", "Tom" }; string[] fNameList = new string[] { "Garfield", "Simba", "Tabby" }; //check all male-owned cats are present in the correct order for (int i = 0; i < ((IList)catTable[0]).Count; i++) { JObject cat = (JObject)((IList)catTable[0])[i]; Assert.IsTrue(cat["name"].ToString() == mNameList[i]); } //check all female-owned cats are in the correct order for (int i = 0; i < ((IList)catTable[1]).Count; i++) { JObject cat = (JObject)((IList)catTable[1])[i]; Assert.IsTrue(cat["name"].ToString() == fNameList[i]); } //as we have confirmed that the length of all lists is correct, //and each of the values, the result has the right data //if the test passes }
public PropertyValueApplier Apply(OrderedDictionary propertyValues) { return(Apply( propertyValues.Cast <DictionaryEntry>() .ToDictionary( x => (string)x.Key, x => x.Value ) )); }
public static object GetKeyFromFirstElementWithValue(this OrderedDictionary dictionary, object value) { for (int i = 0; i < dictionary.Count; ++i) { if (dictionary[i].Equals(value)) { return(dictionary.Cast <DictionaryEntry>().ElementAt(i).Key); } } return(null); }
private static string htmlToPlainText(string html) { const string emptyString = ""; const string singleSpace = " "; // Maintains insert-order. Sadly, is not generic. var regexToReplacements = new OrderedDictionary { { "(\r\n|\r|\n)+", singleSpace }, { "\t", emptyString }, { @"/\*.*\*/", emptyString }, { @"<!--.*-->", emptyString }, { @"\s+", singleSpace }, { @"<\s*head([^>])*>.*(<\s*(/)\s*head\s*>)", emptyString }, { @"<\s*script([^>])*>.*(<\s*(/)\s*script\s*>)", emptyString }, { @"<\s*style([^>])*>.*(<\s*(/)\s*style\s*>)", emptyString }, { @"<\s*td([^>])*>", "\t" }, { @"<\s*br\s*/?>", Environment.NewLine }, { @"<\s*li\s*>", Environment.NewLine }, { @"<\s*div([^>])*>", Environment.NewLine + Environment.NewLine }, { @"<\s*tr([^>])*>", Environment.NewLine + Environment.NewLine }, { @"<\s*p([^>])*>", Environment.NewLine + Environment.NewLine }, { RegularExpressions.HtmlTag, emptyString }, { @"<![^>]*>", emptyString }, { @"•", " * " }, { @"‹", "<" }, { @"›", ">" }, { @"™", "(tm)" }, { @"⁄", "/" }, { @"<", "<" }, { @">", ">" }, { @"©", "(c)" }, { @"®", "(r)" }, { @"&(.{2,6});", emptyString }, { Environment.NewLine + @"\s+" + Environment.NewLine, Environment.NewLine + Environment.NewLine }, { @"\t\s+\t", "\t\t" }, { @"\t\s+" + Environment.NewLine, "\t" + Environment.NewLine }, { Environment.NewLine + @"\s+\t", Environment.NewLine + "\t" }, { Environment.NewLine + @"\t+" + Environment.NewLine, Environment.NewLine + Environment.NewLine }, { Environment.NewLine + @"\t+", Environment.NewLine + "\t" } }; return(regexToReplacements.Cast <DictionaryEntry>() .Aggregate( html, (current, regexToReplacement) => Regex.Replace( current, (string)regexToReplacement.Key, (string)regexToReplacement.Value, RegexOptions.IgnoreCase)) .Trim()); }
void CalculateStart(int width, int height) { this.width = width; this.height = height; AvailablePositions = new OrderedDictionary(); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { if (StartImage.Art.GetPixel(x, y).A != 0) { AvailablePositions.Add((x, y), (x, y)); } if (x == 0 && y % 10 == 0) { ClearLine(); Console.WriteLine("Calculating Start Image Pixels... " + y + " / " + Height); } } } Available2 = new bool[width, height]; var i = 0; foreach (DictionaryEntry p2 in AvailablePositions) { var p = ((int, int))p2.Key; Available2[p.Item1, p.Item2] = true; if (i % (AvailablePositions.Count / 100) == 0) { ClearLine(); Console.WriteLine("Re-calculating Start Image Pixels... " + i + " / " + AvailablePositions.Count); } i++; } var r = new Random(); var two = AvailablePositions.Cast <DictionaryEntry>() .OrderBy(x => r.Next()) .ToDictionary(c => c.Key, d => d.Value); AvailablePositions = new OrderedDictionary(); foreach (var two2 in two) { AvailablePositions.Add(two2.Key, two2.Value); } }
// NOTE: // The code below first collects all message options before comparing them to the received messages. // This method works with the test input, but it requires too much time and memory with the real input. // Therefore, the puzzle remains unsolved. // An alternative would be to review all received messages per character and to decide for each substring if the message could still be valid or not. // This is something to look into later. static void Main() { // Divide input in rules and messages string[] input = File.ReadAllText("input.txt").Replace("\\", string.Empty).Replace("\"", string.Empty).Split($"{Environment.NewLine}{Environment.NewLine}"); Dictionary <int, string[]> rules = GetRules(input); string[] receivedMessages = input[1].Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); // For each key, transform the value to the message. Continue doing this until key 0 only contains a message char[] validChars = new char[] { '|', '(', ')', ' ' }; while (rules[0].Any(value => value.Any(c => !char.IsLetter(c) && !validChars.Contains(c)))) { TransformRulesToMessages(rules, validChars, 0); } // Start an ordered dictionary with rule 0 OrderedDictionary messageOptions = new OrderedDictionary { { string.Join("", rules[0]), 0 } }; // Collect all message options int i = 0; while (i < messageOptions.Count) { if (messageOptions.Cast <DictionaryEntry>().ElementAt(i).Key.ToString().Contains("(")) { CollectMessageOptions(messageOptions, i); } else { i++; } } // Check how many received messages are valid int counter = 0; foreach (string message in receivedMessages) { if (messageOptions.Contains(message)) { counter++; } } Console.WriteLine($"{counter} received messages are valid"); }
public static T GetKey <T>(this OrderedDictionary dictionary, int index) { if (dictionary == null) { return(default(T)); } try { return((T)dictionary.Cast <DictionaryEntry>().ElementAt(index).Key); } catch (Exception) { return(default(T)); } }
public static String ToRoman(int arabic) { string convertedResult = ""; // OrderedDictionary allows us to go through the dictionary sequentially; necessary for this method. var arabicTranslation = new OrderedDictionary { { 1000, "M" }, { 900, "CM" }, { 500, "D" }, { 400, "CD" }, { 100, "C" }, { 90, "XC" }, { 50, "L" }, { 40, "XL" }, { 10, "X" }, { 9, "IX" }, { 5, "V" }, { 4, "IV" }, { 1, "I" } }; if (0 >= arabic || arabic > 3999) { throw new InvalidOperationException(); } int arabicIndex = 0; // We subtract from arabic, adding Roman numerals as we do, until arabic is equal to 0. while (arabic > 0) { // arabicKeyValue is how we get the key itself (the value of a particular numeral); we can't grab the key in an OrderedDictionary through any built-in method. int arabicKeyValue = Int32.Parse(arabicTranslation.Cast <DictionaryEntry>().ElementAt(arabicIndex).Key.ToString()); // We see if our current Roman numeral fits into our number. if (arabic - arabicKeyValue >= 0) { arabic -= arabicKeyValue; convertedResult += arabicTranslation[arabicIndex]; } else { // We go down arabicTranslation, to the next lowest key. arabicIndex += 1; } } return(convertedResult); }
public void UpdateScoreboard() { var scores = playerScores.Cast <DictionaryEntry>().ToDictionary(k => (string)k.Key, v => (Text)v.Value).ToList(); scores.Sort((p1, p2) => int.Parse(p1.Value.text).CompareTo(int.Parse(p2.Value.text))); for (int i = 0; i < scoreboard.Count; i++) { if (i >= scores.Count) { Destroy(scoreboard[i].name.transform.parent.gameObject); continue; } scoreboard[i].name.text = scores[i].Key; scoreboard[i].score.text = scores[i].Value.text; } }
private void RunCurrentDialogue() { currentAudioSource = (AudioSource)pendingDialogues.Cast <System.Collections.DictionaryEntry>().ElementAt(0).Key; string text = (string)pendingDialogues[0]; if (currentAudioSource != null) { currentAudioSource.Play(); } if (text != null) { messageController.DisplayText(text); } pendingDialogues.RemoveAt(0); }
/// <summary> /// Sorts the list of Gambler objects and outputs a string back with the result. /// </summary> /// <param name="gamblers">The list of Gambler objects that needs to be sorted.</param> /// <param name="output">The message that will be sent to the channel.</param> /// <returns>The output with the top 5 gamblers from the given list.</returns> private string SortGamblers(List <Gambler> gamblers, string output) { IOrderedDictionary allGamblers = new OrderedDictionary(); //Throw all gamblers in there. foreach (Gambler g in gamblers) { allGamblers.Add(g.GetName(), g.GetCash()); } //Sort it and throw it in a normal dictionary. (ADDING ANYTHING AFTER THIS WILL MAKE IT UNORDERED AGAIN.) var topGamblers = allGamblers.Cast <DictionaryEntry>() .OrderBy(r => r.Value) .ToDictionary(c => c.Key, d => d.Value); //Output the top 5 gamblers. int count = 0; //Reverse dictionary to order descending. foreach (var entry in topGamblers.Reverse()) { if (count >= 5) { break; } else { output += String.Format("{0} - {1}", entry.Key, entry.Value) + "\n"; count++; } } output += "```"; return(output); }
protected override void SolveInstance(IGH_DataAccess DA) { _DA = DA; this.Message = "JobQueue: " + JobQueue.Count; if (mySender == null) { return; } DA.SetData(0, Log); DA.SetData(1, mySender.StreamId); if (!mySender.IsConnected) { return; } if (JobQueue.Count == 0) { return; } if (!solutionPrepared) { System.Collections.DictionaryEntry t = JobQueue.Cast <DictionaryEntry>().ElementAt(0); CurrentJobClient = ( string )t.Key; PrepareSolution(( IEnumerable )t.Value); solutionPrepared = true; return; } else { solutionPrepared = false; var BucketObjects = GetData(); var convertedObjects = Converter.Serialise(BucketObjects).Select(obj => { if (ObjectCache.ContainsKey(obj.Hash)) { return new SpeckleObjectPlaceholder() { Hash = obj.Hash, DatabaseId = ObjectCache[obj.Hash].DatabaseId } } ; return(obj); }); List <SpeckleInputParam> inputControllers = null; List <SpeckleOutputParam> outputControllers = null; GetDefinitionIO(ref inputControllers, ref outputControllers); List <ISpeckleControllerParam> measures = new List <ISpeckleControllerParam>(); foreach (var x in inputControllers) { measures.Add(x); } foreach (var x in outputControllers) { measures.Add(x); } PayloadStreamCreate myNewStreamPayload = new PayloadStreamCreate { IsComputed = true, Parent = mySender.StreamId, GlobalMeasures = measures, Name = this.NickName, Layers = GetLayers(), Objects = convertedObjects }; mySender.StreamCreateAsync(myNewStreamPayload).ContinueWith(tres => { Dictionary <string, object> args = new Dictionary <string, object>(); args["eventType"] = "computation-result"; args["streamId"] = tres.Result.Stream.StreamId; args["outputRef"] = outputControllers; mySender.SendMessage(CurrentJobClient, args); int k = 0; foreach (var obj in convertedObjects) { obj.DatabaseId = tres.Result.Stream.Objects[k++]; ObjectCache[obj.Hash] = obj; } }); JobQueue.RemoveAt(0); this.Message = "JobQueue: " + JobQueue.Count; if (JobQueue.Count != 0) { Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction); } } }
private OrderedDictionary CreatePayeTable(string YearSelected, out decimal personalAllowance, out string taxCodeLetter) { OrderedDictionary payetable = new OrderedDictionary(); personalAllowance = 0m; taxCodeLetter = ""; decimal numericAmount = 0m; List <string> TaxCodes = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/BandCodes//@letter"); List <string> TaxCodesEndLetters = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/BandEndLetters/Letter"); List <string> TaxCodesStartLetters = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/BandStartLetters/Letter"); //If no Tax code was enter, use default and call method again. if (TaxCode.Text == "") { TaxCode.Text = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Default").First(); payetable = CreatePayeTable(YearSelected, out personalAllowance, out taxCodeLetter); } else if (TaxCodes.Contains(TaxCode.Text)) //Checks for single rate NT, BR, D0 etc. { payetable = ReadRatesXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/BandCodes/code[@letter='" + TaxCode.Text + "']"); } //The case for the L (and related) codes is complex. We need to take into consideration that the personal Allowance //reduces by 2 after the salary goes past £100,000 (the adjusted level). //To do this, the rate will be increased by 1.5 post £100,000 until the personal allowance reaches 0. //This threshold will be 100,000 + 2 * personal allowance. else if (TaxCodesEndLetters.Contains(TaxCode.Text.Substring(TaxCode.Text.Length - 1, 1))) { if (decimal.TryParse(TaxCode.Text.Substring(0, TaxCode.Text.Length - 1), out numericAmount)) { personalAllowance = numericAmount * 10 + 9; OrderedDictionary payetableRate = new OrderedDictionary(); payetableRate = ReadRatesXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Bands", personalAllowance); decimal Adjusted = 0; if (ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Adjusted").Count == 1) { Adjusted = Convert.ToDecimal(ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Adjusted").First()); } if (Adjusted != 0) { decimal AdjustedUpper = Adjusted + 2 * (personalAllowance - 9); int i = 0; decimal Bound = 0; decimal Rate = 0; decimal RateAdjusted = 0; int NumberOfEntries = payetableRate.Count; payetable.Add(Bound, Rate); //3 stages here //i. Add thresholds below the Adjusted level //ii. Add thresholds between Adjusted level and Adjusted level + 2 * personal allowance //iii. Add thresholds post Adjusted level + 2 * personal allowance //Stage i while (true) //infinite loop but breaking when either of two conditions are met { Bound = Convert.ToDecimal(payetableRate.Cast <DictionaryEntry>().ElementAt(i).Key); Rate = Convert.ToDecimal(payetableRate[i]); if (Bound < Adjusted) { payetable.Add(Bound, Rate); } else //break when Adjusted level is reached { RateAdjusted = Convert.ToDecimal(payetableRate[i - 1]) * 1.5m; payetable.Add(Adjusted, RateAdjusted); break; } if (i < NumberOfEntries - 1) { i++; } else //break also when end of table is reached { RateAdjusted = Convert.ToDecimal(payetableRate[i]) * 1.5m; payetable.Add(Adjusted, RateAdjusted); break; } } //Stage ii decimal BoundAdjusted = 0; while (AdjustedUpper > Bound - personalAllowance) { Bound = Convert.ToDecimal(payetableRate.Cast <DictionaryEntry>().ElementAt(i).Key); if (Bound < Adjusted) { Rate = Convert.ToDecimal(payetableRate[i]); payetable.Add(AdjustedUpper, Rate); break; } if (Bound - personalAllowance < AdjustedUpper) { BoundAdjusted = AdjustedUpper / 3 + 2 * (Bound - personalAllowance) / 3; RateAdjusted = Convert.ToDecimal(payetableRate[i]) * 1.5m; payetable.Add(BoundAdjusted, RateAdjusted); } else { Rate = Convert.ToDecimal(payetableRate[i - 1]); payetable.Add(AdjustedUpper, Rate); break; } if (i < NumberOfEntries - 1) { i++; } else { Rate = Convert.ToDecimal(payetableRate[i]); payetable.Add(AdjustedUpper, Rate); break; } } //Stage iii while (true)//infinite loop but breaking when either of two conditions are met { Bound = Convert.ToDecimal(payetableRate.Cast <DictionaryEntry>().ElementAt(i).Key); Rate = Convert.ToDecimal(payetableRate[i]); if (Bound - personalAllowance > AdjustedUpper) { payetable.Add(Bound - personalAllowance, Rate); } else { break; } //breaks if this threshold is last in table if (i < NumberOfEntries - 1) { i++; } //breaks when end of table is reached else { break; } } } else //Case when there is no adjusted level { int i = 0; decimal Bound = 0; decimal Rate = 0; int NumberOfEntries = payetableRate.Count; while (i < NumberOfEntries) { payetable.Add(Bound, Rate); Bound = Convert.ToDecimal(payetableRate.Cast <DictionaryEntry>().ElementAt(i).Key); Rate = Convert.ToDecimal(payetableRate[i]); i++; } } taxCodeLetter = TaxCode.Text.Substring(TaxCode.Text.Length - 1, 1); } } else if (TaxCodesStartLetters.Contains(TaxCode.Text.Substring(0, 1))) //Case for K codes { if (decimal.TryParse(TaxCode.Text.Substring(1, TaxCode.Text.Length - 1), out numericAmount)) { personalAllowance = -numericAmount * 10; payetable = ReadRatesXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Bands", personalAllowance); taxCodeLetter = TaxCode.Text.Substring(0, 1); } } else //Case for invalid tax code enter. Then use default and call method again { TaxCode.Text = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Default").First(); payetable = CreatePayeTable(YearSelected, out personalAllowance, out taxCodeLetter); } return(payetable); }
protected override void ComputeVelocity() { directorTime = director.GetComponent <PlayerLoopDirector>().currentLoopTime; //When detected that there are moves in queue split for 1 operation if (moveCount < movementQueue.Count) { // Likes to throw errors if buttons are pressed too fast try { currKey = (float)movementQueue.Cast <DictionaryEntry>().ElementAt(moveCount).Key; } catch { } if (directorTime >= currKey) { moveCommand = movementQueue[moveCount].ToString(); IssueMoveCommand(moveCommand); moveCount++; } } Vector2 move = Vector2.zero; //move.x = Input.GetAxis("Horizontal"); //Check to see if left or right is true and accelerate clone by player X gravity //THIS F*****G AWFUL MESS emulates the acceleration of an InputAxis. Not perfect. if (left == 1 || right == 1) { dir = Math.Sign(velX); velX = Mathf.Clamp(velX + ((right - left) * moveGravity * Time.deltaTime), -1, 1); if ((right == 1 && dir == -1) || (left == 1 && dir == 1)) { if (!(right == 1 && left == 1)) { velX += moveGravity * Time.deltaTime * -dir; } } } else if (velX > deadZone || velX < -deadZone) { velX += moveGravity * Time.deltaTime * -Math.Sign(velX); } move.x = velX; if (jumpDown && grounded) { velocity.y = jumpTakeOffSpeed; } else if (jumpUp) { if (velocity.y > 0) { velocity.y *= 0.5f; } } jumpDown = jumpUp = false; if (move.x > 0.01f) { if (spriteRenderer.flipX == true) { spriteRenderer.flipX = false; } } else if (move.x < -0.01f) { if (spriteRenderer.flipX == false) { spriteRenderer.flipX = true; } } animator.SetBool("grounded", grounded); animator.SetFloat("velocityX", Mathf.Abs(velocity.x) / maxSpeed); targetVelocity = move * maxSpeed; }
/// <summary> /// Gets the associated Rate and calculates the monthly estimates for the specified Meter details /// </summary> /// <param name="meterCategory">Meter Category of the Meter</param> /// <param name="meterSubCategory">Meter SubCategory of the Meter</param> /// <param name="meterName">Meter Name of the Meter</param> /// <param name="region">Azure Location as per Pricing Specs</param> /// <param name="quantity">Quantity of the resource usage in a month</param> /// <param name="rate">Rate will be set based on the associated meter in CSP Rate Card</param> /// <param name="log">The object that will contain the exception messages</param> /// <param name="nameOfResource">Name of the Azure resource</param> /// <returns> Returns the Monthly Cost for the resource</returns> private static double GetResourceRate(string meterCategory, string meterSubCategory, string meterName, string region, double quantity, out double rate, ref StringBuilder log, string nameOfResource) { double totalCost = 0; rate = 0; try { // If any meter fields are missing throw an exception if (meterCategory == null) { throw new Exception(ExceptionLogger.GenerateLoggerTextForMeterRateFetchFailed("MeterCategory is null", nameOfResource)); } if (meterSubCategory == null) { throw new Exception(ExceptionLogger.GenerateLoggerTextForMeterRateFetchFailed("MeterSubCategory is null", nameOfResource)); } if (meterName == null) { throw new Exception(ExceptionLogger.GenerateLoggerTextForMeterRateFetchFailed("MeterName is null", nameOfResource)); } if (region == null) { throw new Exception(ExceptionLogger.GenerateLoggerTextForMeterRateFetchFailed("Region is null", nameOfResource)); } // Fetch the rate for the resource component by matching the meter fields provided Meter ratesForComponent = meterList.Find(x => meterCategory.Equals(x.MeterCategory, StringComparison.OrdinalIgnoreCase) && meterSubCategory.Equals(x.MeterSubCategory, StringComparison.OrdinalIgnoreCase) && meterName.Equals(x.MeterName, StringComparison.OrdinalIgnoreCase) && region.Equals(x.MeterRegion, StringComparison.OrdinalIgnoreCase)); // If the Meter is missing in CSP Rate Card, check if there is a global rate (Rate without region specified) if (ratesForComponent == null) { ratesForComponent = meterList.Find(x => meterCategory.Equals(x.MeterCategory, StringComparison.OrdinalIgnoreCase) && meterSubCategory.Equals(x.MeterSubCategory, StringComparison.OrdinalIgnoreCase) && meterName.Equals(x.MeterName, StringComparison.OrdinalIgnoreCase) && x.MeterRegion.Equals(string.Empty, StringComparison.OrdinalIgnoreCase)); } // Check if Meter found if (ratesForComponent != null) { // Fetch the Rates from the meter found OrderedDictionary meterRates = ratesForComponent.MeterRates; // If consumed quantity if less that included quantity, set rate and cost to zero if (quantity <= ratesForComponent.IncludedQuantity) { totalCost = 0; rate = 0; } else if (meterRates.Count == 1) { // If linear rating, Calculate Monthly Cost as quantity x rate rate = (double)meterRates[0]; totalCost = (quantity - ratesForComponent.IncludedQuantity) * rate; } else { // If tiered rating, calculate Monthly Cost based on tiered pricing double quantitytobeRated = quantity - ratesForComponent.IncludedQuantity; totalCost = 0; for (int i = 1; i < meterRates.Count; i++) { string currentKeyString = (string)meterRates.Cast <DictionaryEntry>().ElementAt(i).Key; string previousKeyString = (string)meterRates.Cast <DictionaryEntry>().ElementAt(i - 1).Key; double currentKey = double.Parse(currentKeyString); double previousKey = double.Parse(previousKeyString); if (quantitytobeRated <= currentKey) { totalCost = totalCost + ((quantitytobeRated - previousKey) * (double)meterRates[i - 1]); rate = (double)meterRates[i - 1]; break; } else { totalCost = totalCost + ((currentKey - previousKey) * (double)meterRates[i - 1]); if (i == meterRates.Count - 1) { totalCost = totalCost + ((quantitytobeRated - currentKey) * (double)meterRates[i]); rate = (double)meterRates[i]; } } } } } else { // Meter for specified parameters not found, Throw an exception throw new Exception(ExceptionLogger.GenerateLoggerTextForMeterRateFetchFailed(string.Format("Meter not found in Rate Card. MeterCategory:{0},MeterSubCategory:{1},MeterName:{2},Region:{3} ", meterCategory, meterSubCategory, meterName, region), nameOfResource)); } } catch (Exception ex) { totalCost = 0; log.AppendLine(ex.Message); } return(totalCost); }
protected override void SolveInstance(IGH_DataAccess DA) { if (mySender == null) { return; } if (this.EnableRemoteControl) { this.Message = "JobQueue: " + JobQueue.Count; } StreamId = mySender.StreamId; DA.SetData(0, Log); DA.SetData(1, mySender.StreamId); if (!mySender.IsConnected) { return; } if (WasSerialised && FirstSendUpdate) { FirstSendUpdate = false; return; } this.State = "Expired"; // All flags are good to start an update if (!this.EnableRemoteControl && !this.ManualMode) { UpdateData(); return; } // else if (!this.EnableRemoteControl && this.ManualMode) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "State is expired, update push is required."); return; } #region RemoteControl // Code below deals with the remote control functionality. // Proceed at your own risk. if (JobQueue.Count == 0) { SetDefaultState(); AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Updated default state for remote control."); return; } // prepare solution and exit if (!SolutionPrepared && JobQueue.Count != 0) { System.Collections.DictionaryEntry t = JobQueue.Cast <DictionaryEntry>().ElementAt(0); Document.ScheduleSolution(1, PrepareSolution); return; } // send out solution and exit if (SolutionPrepared) { SolutionPrepared = false; var BucketObjects = GetData(); var BucketLayers = GetLayers(); var convertedObjects = Converter.Serialise(BucketObjects).Select(obj => { if (ObjectCache.ContainsKey(obj.Hash)) { return new SpecklePlaceholder() { Hash = obj.Hash, _id = ObjectCache[obj.Hash]._id } } ; return(obj); }); // theoretically this should go through the same flow as in DataSenderElapsed(), ie creating // buckets for staggered updates, etc. but we're lazy to untangle that logic for now var responseClone = mySender.StreamCloneAsync(this.StreamId).Result; var responseStream = new SpeckleStream(); responseStream.IsComputedResult = true; responseStream.Objects = convertedObjects.ToList(); responseStream.Layers = BucketLayers; List <SpeckleInput> speckleInputs = null; List <SpeckleOutput> speckleOutputs = null; GetSpeckleParams(ref speckleInputs, ref speckleOutputs); responseStream.GlobalMeasures = new { input = speckleInputs, output = speckleOutputs }; // go unblocking var responseCloneUpdate = mySender.StreamUpdateAsync(responseClone.Clone.StreamId, responseStream).ContinueWith(tres => { mySender.SendMessage(CurrentJobClient, new { eventType = "compute-response", streamId = responseClone.Clone.StreamId }); }); JobQueue.RemoveAt(0); this.Message = "JobQueue: " + JobQueue.Count; if (JobQueue.Count != 0) { Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction); } } #endregion }
private void Initialize(QuestBookmarkWindow.JSON_Item[] bookmarkItems) { GameManager instance = MonoSingleton <GameManager> .Instance; PlayerData player = instance.Player; SectionParam[] sections = instance.Sections; List <string> stringList1 = new List <string>(); List <string> stringList2 = new List <string>(); long serverTime = Network.GetServerTime(); foreach (QuestParam availableQuest in player.AvailableQuests) { if (this.IsAvailableQuest(availableQuest, serverTime) && !stringList1.Contains(availableQuest.ChapterID)) { stringList1.Add(availableQuest.ChapterID); } } using (List <string> .Enumerator enumerator = stringList1.GetEnumerator()) { while (enumerator.MoveNext()) { string current = enumerator.Current; ChapterParam area = instance.FindArea(current); if (area != null && !stringList2.Contains(area.section)) { stringList2.Add(area.section); } } } this.mAvailableSections = stringList2.ToArray(); Dictionary <string, List <QuestParam> > dictionary = new Dictionary <string, List <QuestParam> >(); foreach (QuestParam questParam in ((IEnumerable <QuestParam>)MonoSingleton <GameManager> .Instance.Quests).Where <QuestParam>((Func <QuestParam, bool>)(q => q.type == QuestTypes.Free))) { List <QuestParam> questParamList; if (!dictionary.TryGetValue(questParam.world, out questParamList)) { questParamList = new List <QuestParam>(); dictionary[questParam.world] = questParamList; } questParamList.Add(questParam); } int index1 = 0; if (bookmarkItems != null && bookmarkItems.Length > 0) { foreach (QuestBookmarkWindow.JSON_Item bookmarkItem in bookmarkItems) { ItemParam itemParam = MonoSingleton <GameManager> .Instance.MasterParam.GetItemParam(bookmarkItem.iname); List <QuestParam> itemDropQuestList = QuestDropParam.Instance.GetItemDropQuestList(itemParam, GlobalVars.GetDropTableGeneratedDateTime()); this.mBookmarkedPiecesOrigin.Add(new QuestBookmarkWindow.ItemAndQuests() { itemName = itemParam.iname, quests = itemDropQuestList }); } this.mBookmarkedPieces = this.mBookmarkedPiecesOrigin.ToList <QuestBookmarkWindow.ItemAndQuests>(); } this.mSectionToPieces[this.BookmarkSectionName] = this.mBookmarkedPieces; if (index1 < this.ButtonSections.Length) { DataSource.Bind <string>(((Component)this.ButtonSections[index1]).get_gameObject(), this.BookmarkSectionName); } int index2; for (index2 = index1 + 1; index2 < this.ButtonSections.Length; ++index2) { if (index2 - 1 < sections.Length) { SectionParam sectionParam = sections[index2 - 1]; if (sectionParam.IsDateUnlock() && stringList2.Contains(sectionParam.iname)) { SRPG_Button buttonSection = this.ButtonSections[index2]; DataSource.Bind <string>(((Component)buttonSection).get_gameObject(), sectionParam.iname); ((BookmarkToggleButton)((Component)buttonSection).GetComponent <BookmarkToggleButton>()).EnableShadow(false); List <QuestParam> questParamList1 = dictionary[sectionParam.iname]; OrderedDictionary source = new OrderedDictionary(); using (List <QuestParam> .Enumerator enumerator = questParamList1.GetEnumerator()) { while (enumerator.MoveNext()) { QuestParam current = enumerator.Current; ItemParam hardDropPiece = QuestDropParam.Instance.GetHardDropPiece(current.iname, GlobalVars.GetDropTableGeneratedDateTime()); List <QuestParam> questParamList2; if (source.Contains((object)hardDropPiece.iname)) { questParamList2 = source[(object)hardDropPiece.iname] as List <QuestParam>; } else { questParamList2 = new List <QuestParam>(); source[(object)hardDropPiece.iname] = (object)questParamList2; } questParamList2.Add(current); } } this.mSectionToPieces[sectionParam.iname] = source.Cast <DictionaryEntry>().Select <DictionaryEntry, QuestBookmarkWindow.ItemAndQuests>((Func <DictionaryEntry, QuestBookmarkWindow.ItemAndQuests>)(kv => new QuestBookmarkWindow.ItemAndQuests() { itemName = kv.Key as string, quests = kv.Value as List <QuestParam> })).ToList <QuestBookmarkWindow.ItemAndQuests>(); } else { ((BookmarkToggleButton)((Component)this.ButtonSections[index2]).GetComponent <BookmarkToggleButton>()).EnableShadow(true); } } else { ((BookmarkToggleButton)((Component)this.ButtonSections[index2]).GetComponent <BookmarkToggleButton>()).EnableShadow(true); } } foreach (SectionParam sectionParam in sections) { if (sectionParam.IsDateUnlock() && stringList2.Contains(sectionParam.iname) && index2 < this.ButtonSections.Length) { DataSource.Bind <string>(((Component)this.ButtonSections[index2]).get_gameObject(), sectionParam.iname); List <QuestParam> questParamList1 = dictionary[sectionParam.iname]; OrderedDictionary source = new OrderedDictionary(); using (List <QuestParam> .Enumerator enumerator = questParamList1.GetEnumerator()) { while (enumerator.MoveNext()) { QuestParam current = enumerator.Current; ItemParam hardDropPiece = QuestDropParam.Instance.GetHardDropPiece(current.iname, GlobalVars.GetDropTableGeneratedDateTime()); List <QuestParam> questParamList2; if (source.Contains((object)hardDropPiece.iname)) { questParamList2 = source[(object)hardDropPiece.iname] as List <QuestParam>; } else { questParamList2 = new List <QuestParam>(); source[(object)hardDropPiece.iname] = (object)questParamList2; } questParamList2.Add(current); } } this.mSectionToPieces[sectionParam.iname] = source.Cast <DictionaryEntry>().Select <DictionaryEntry, QuestBookmarkWindow.ItemAndQuests>((Func <DictionaryEntry, QuestBookmarkWindow.ItemAndQuests>)(kv => new QuestBookmarkWindow.ItemAndQuests() { itemName = kv.Key as string, quests = kv.Value as List <QuestParam> })).ToList <QuestBookmarkWindow.ItemAndQuests>(); } } foreach (SRPG_Button buttonSection in this.ButtonSections) { buttonSection.AddListener(new SRPG_Button.ButtonClickEvent(this.OnSectionSelect)); } if (UnityEngine.Object.op_Inequality((UnityEngine.Object) this.TitleText, (UnityEngine.Object)null)) { this.TitleText.set_text(LocalizedText.Get(this.BookmarkTitle)); } if (UnityEngine.Object.op_Inequality((UnityEngine.Object) this.DescriptionText, (UnityEngine.Object)null)) { this.DescriptionText.set_text(LocalizedText.Get(this.BookmarkDescription)); } this.RefreshSection(0); }
/// <summary> /// returns the name of the column at <paramref name="columnIndex"/>. /// </summary> /// <param name="columnIndex"></param> /// <returns> /// name of the column at <paramref name="columnIndex"/> /// </returns> /// <exception cref="ColumnIndexOutOfRangeException"> /// <seealso cref="assertColumnIndexWithinRange(int)"/> /// </exception> public string GetColumnName(int columnIndex) { assertColumnIndexWithinRange(columnIndex); return(columnNameToColumnValue.Cast <DictionaryEntry>() .ElementAt(columnIndex).Key.ToString()); }
static void Main(string[] args) { #if TEST_DICTIONARY var dicLongLong = new Dictionary <long, long> { { 1L, 1L }, { 2L, 2L }, { 3L, 3L } }; //lock (dicLongLong[2L]) // Error CS0185 'long' is not a reference type as required by the lock statement //{} var dicIntVictim = new Dictionary <int, Victim> { { 0, new Victim { FString = "0" } }, { 1, new Victim { FString = "1" } }, { 2, new Victim { FString = "2" } } }; foreach (var k in dicIntVictim.Keys) { dicIntVictim[k].FString = dicIntVictim[k].FString + dicIntVictim[k].FString; } var dicIntInt = new Dictionary <int, int> { { 0, 0 }, { 1, 1 }, { 2, 2 } }; try { foreach (var k in dicIntInt.Keys) { dicIntInt[k] = dicIntInt[k] + dicIntInt[k]; } } catch (InvalidOperationException eInvalidOperationException) { WriteLine(eInvalidOperationException.Message); } Dictionary <string, string> dic = null; try { foreach (var kvp in dic) { WriteLine("\"{0}\" = \"{1}\"", kvp.Key, kvp.Value); } } catch (NullReferenceException eNullReferenceException) { WriteLine(eNullReferenceException.Message); } dic = new Dictionary <string, string>(); foreach (var kvp in dic) { WriteLine("\"{0}\" = \"{1}\"", kvp.Key, kvp.Value); } dic.Add("3rd", "3rd"); dic.Add("2nd", "2nd"); dic.Add("1st", "1st"); dic["4th"] = "4th"; dic["5th"] = "5th"; try { if (dic["6th"] != "6th") { WriteLine("Tampax"); } } catch (KeyNotFoundException eKeyNotFoundException) { WriteLine(eKeyNotFoundException.Message); } foreach (KeyValuePair <string, string> v in dic) { WriteLine("{0} {1}", v.Key, v.Value); } WriteLine(); foreach (string k in dic.Keys) { WriteLine("{0} {1}", k, dic[k]); } WriteLine(); try { foreach (string k in dic.Keys) { dic[k] = dic[k] + dic[k]; } } catch (InvalidOperationException eInvalidOperationException) { WriteLine(eInvalidOperationException.Message); } Dictionary <string, string> .Enumerator e = dic.GetEnumerator(); while (e.MoveNext()) { WriteLine("{0} {1}", e.Current.Key, e.Current.Value); //e.Current.Value += "3rd"; // Error CS0200 Property or indexer 'KeyValuePair<string, string>.Value' cannot be assigned to --it is read only } e.Dispose(); WriteLine(); Dictionary <string, string> .KeyCollection.Enumerator ek = dic.Keys.GetEnumerator(); try { while (ek.MoveNext()) { WriteLine("{0} {1}", ek.Current, dic[ek.Current]); if (ek.Current == "3rd") { dic[ek.Current] = dic[ek.Current] + dic[ek.Current]; } } } catch (InvalidOperationException eInvalidOperationException) { WriteLine(eInvalidOperationException.Message); } finally { ek.Dispose(); } WriteLine(); #region ReadOnlyDictionary ReadOnlyDictionary <string, string> roDic = new ReadOnlyDictionary <string, string>(dic); foreach (var kvp in roDic) { WriteLine($"[\"{kvp.Key}\"] = \"{kvp.Value}\""); } WriteLine(); //roDic["3rd"] = "3rd"; // Error CS0200 Property or indexer 'ReadOnlyDictionary<string, string>.this[string]' cannot be assigned to --it is read only dic["6th"] = "6th"; dic["7th"] = "7th"; dic["3rd"] = "3rd"; foreach (var kvp in roDic) { WriteLine($"[\"{kvp.Key}\"] = \"{kvp.Value}\""); } WriteLine(); #endregion #region OrderedDictionary OrderedDictionary oDic = new OrderedDictionary(); oDic.Add("3rd", "3rd"); oDic.Add("2nd", "2nd"); oDic.Add("1st", "1st"); oDic["4th"] = "4th"; oDic["5th"] = "5th"; foreach (DictionaryEntry v in oDic) { Console.WriteLine("{0} {1}", v.Key, v.Value); } Console.WriteLine(); IDictionaryEnumerator oe = oDic.GetEnumerator(); while (oe.MoveNext()) { Console.WriteLine("{0} {1}", oe.Key, oe.Value); } Console.WriteLine(); IEnumerator oek = oDic.Keys.GetEnumerator(); while (oek.MoveNext()) { Console.WriteLine("{0} {1}", oek.Current, oDic[oek.Current]); } Console.WriteLine(); oDic = new OrderedDictionary(); oDic.Add("3rd", "3rd (value)"); oDic.Add("2nd", "2nd (value)"); oDic.Insert(0, "1st", "1st (value)"); for (var i = 0; i < oDic.Count; ++i) { Console.WriteLine("{0}", oDic[i]); } Console.WriteLine(); foreach (DictionaryEntry v in oDic) { Console.WriteLine("{0} {1}", v.Key, v.Value); } Console.WriteLine(); oe = oDic.GetEnumerator(); while (oe.MoveNext()) { Console.WriteLine("{0} {1}", oe.Key, oe.Value); } Console.WriteLine(); oek = oDic.Keys.GetEnumerator(); while (oek.MoveNext()) { Console.WriteLine("{0} {1}", oek.Current, oDic[oek.Current]); } Console.WriteLine(); IList a = oDic.Cast <DictionaryEntry>().Select(de => de.Value).ToList(); IList aa = oDic.Keys.Cast <string>().ToList(); Console.WriteLine(); #endregion #endif #if TEST_LIST List <StringStringPair> listOfStringStringPair = new List <StringStringPair>(new StringStringPair[] { new StringStringPair("aa", "bb") }); StringStringPair stringStringPair = new StringStringPair("aa", "bb"); if (listOfStringStringPair.Contains(stringStringPair)) { Console.WriteLine("Already exists!"); } stringStringPair = new StringStringPair("bb", "aa"); if (listOfStringStringPair.Contains(stringStringPair)) { Console.WriteLine("Already exists!"); } stringStringPair = new StringStringPair("bb", "cc"); if (listOfStringStringPair.Contains(stringStringPair)) { Console.WriteLine("Already exists!"); } listOfStringStringPair.Add(new StringStringPair("bb", "aa")); listOfStringStringPair.Add(new StringStringPair("bb", "cc")); var tmp = listOfStringStringPair.Distinct().ToArray(); tmp = listOfStringStringPair.Distinct(new StringStringPairComparer()).ToArray(); List <int> listOfIntI = new List <int>(new int[] { 1, 2, 3, 4, 5 }), listOfIntII = new List <int>(new int[] { 1, 3, 5 }); listOfIntI.RemoveAll(listOfIntII.Contains); A a = new A(13); List <A> listOfAI = new List <A>(new A[] { a, new A(1), new A(2), new A(3), new A(4), new A(5), null }), listOfAII = new List <A>(new A[] { a, new A(1), new A(3), new A(5) }); listOfAI.RemoveAll(listOfAII.Contains); listOfIntI = new List <int>(new int[] { 1, 2, 3, 4, 5 }); foreach (var i in listOfIntI.ToArray()) { if (i % 2 == 0) { listOfIntI.Remove(i); } } #endif }