public AttributeManager()
        {
            InitializeComponent();

            StepMapper = new Dictionary<string, Logic.Steps>
            {
                {"Create Temporary Attribute", Logic.Steps.CreateTemp},
                {"Migrate to Temporary Attribute", Logic.Steps.MigrateToTemp},
                {"Remove Existing Attribute", Logic.Steps.RemoveExistingAttribute},
                {"Create New Attribute", Logic.Steps.CreateNewAttribute},
                {"Migrate to New Attribute", Logic.Steps.MigrateToNewAttribute},
                {"Remove Temporary Attribute", Logic.Steps.RemoveTemp}
            };

            DefaultSteps = StepMapper.Keys.Cast<Object>().ToArray();

            RenameSteps = new Object[]
            {
                StepMapper.First(p => p.Value == Logic.Steps.CreateNewAttribute).Key,
                StepMapper.First(p => p.Value == Logic.Steps.MigrateToNewAttribute).Key,
                StepMapper.First(p => p.Value == Logic.Steps.RemoveExistingAttribute).Key
            };

            lblNewAttributeType.Visible = false;
            cmbNewAttributeType.Visible = false;
            tabAttributeType.Visible = false;
        }
Example #2
0
 public formAyuda(Conexion con, List<string> columnasMostrar, List<object> listaDatos, int ancho, int alto, Dictionary<string, string> valorDesactivado)
 {
     try
     {
         InitializeComponent();
         _listaDatos = new List<ElementoAyuda>();
         foreach (object e in listaDatos)
         {
             ElementoAyuda ea = new ElementoAyuda();
             ea.Elemento = (ElementoBase)e;
             foreach (string s in columnasMostrar)
             {
                 ea.Mostrar += e.GetType().GetProperty(s).GetValue(e, null).ToString() + " -- ";
             }
             ea.Habilitado = e.GetType().GetProperty(valorDesactivado.First().Key).GetValue(e, null).ToString() != valorDesactivado.First().Value;
             ea.Mostrar = ea.Mostrar.Remove(ea.Mostrar.Length - 3);
             lbDatos.Items.Add(ea);
             _listaDatos.Add(ea);
         }
         lbDatos.DisplayMember = "Mostrar";
         lbDatos.ValueMember = "Elemento";
         lbDatos.SelectedIndex = 0;
     }
     catch (Exception e)
     {
         throw e;
     }
     this.Width = ancho;
     this.Height = alto;
 }
        public AttributeManagerPlugin()
        {
            InitializeComponent();

            StepMapper = new Dictionary<string, Logic.Steps>
            {
                {"Create Temporary Attribute", Logic.Steps.CreateTemp},
                {"Migrate to Temporary Attribute", Logic.Steps.MigrateToTemp},
                {"Remove Existing Attribute", Logic.Steps.RemoveExistingAttribute},
                {"Create New Attribute", Logic.Steps.CreateNewAttribute},
                {"Migrate to New Attribute", Logic.Steps.MigrateToNewAttribute},
                {"Remove Temporary Attribute", Logic.Steps.RemoveTemp}
            };

            DefaultSteps = StepMapper.Keys.Cast<object>().ToArray();

            RenameSteps = new object[]
            {
                StepMapper.First(p => p.Value == Logic.Steps.CreateNewAttribute).Key,
                StepMapper.First(p => p.Value == Logic.Steps.MigrateToNewAttribute).Key,
                StepMapper.First(p => p.Value == Logic.Steps.RemoveExistingAttribute).Key
            };

            cmbNewAttributeType.Visible = false;
            SetTabVisible(tabStringAttribute, false);
            SetTabVisible(tabNumberAttribute, false);
            SetTabVisible(tabOptionSetAttribute, false);

            SetCurrencyNumberVisible(false);
            SetDecimalNumberVisible(false);
            SetWholeNumberVisible(false);
            SetFloatNumberVisible(false);
            numAttFormatCmb.SelectedIndex = 0;
        }
        public void StringJoinTestCase()
        {
            var dictionary = new Dictionary<String, String>
            {
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() },
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() }
            };

            var actual = dictionary.StringJoin();
            var expected = "{0}={1}{2}={3}".F( dictionary.First()
                                                         .Key,
                                               dictionary.First()
                                                         .Value,
                                               dictionary.Last()
                                                         .Key,
                                               dictionary.Last()
                                                         .Value );
            Assert.AreEqual( expected, actual );

            actual = dictionary.StringJoin( ",", ";" );
            expected = "{0},{1};{2},{3}".F( dictionary.First()
                                                      .Key,
                                            dictionary.First()
                                                      .Value,
                                            dictionary.Last()
                                                      .Key,
                                            dictionary.Last()
                                                      .Value );
            Assert.AreEqual( expected, actual );
        }
		/// <summary>
		/// Do the specified input and output.
		/// </summary>
		/// <param name="input">Input.</param>
		/// <param name="output">Output.</param>
        public void Do(BlockingCollection<ISkeleton> input, Action<IEnumerable<Result>> fireNewCommand)
        {
            var data = new Dictionary<JointType, InputVector>();
            foreach (var skeleton in input.GetConsumingEnumerable())
            {
                foreach (var joint in skeleton.Joints)
                {
                    if (!data.ContainsKey(joint.JointType))
                    {
                        data.Add(joint.JointType, new InputVector());
                    }
                    data[joint.JointType].Stream.Add(joint.Point);
                }
                if (data.First().Value.Stream.Count < 5)
                {
                    continue;
                }
                var results = Recognizer.Recognize(data);
                try
                {
                    fireNewCommand(results);
                }
                catch (Exception)
                {
                    if (data.First().Value.Stream.Count > 40)
                    {
                        data.Clear();
                    }
                    continue;
                }
                data.Clear();
            }
        }
Example #6
0
 /// <summary>
 /// Create an AnimationManager, animations are later added using the
 /// addAnimation method.
 /// </summary>
 /// <param name="animListingXML">XML document associating frames in a spritesheet with names.</param>
 public AnimationManager(string animListingXML)
 {
     animSource = AbyssGame.Assets.Load<Dictionary<string, Rectangle>>(animListingXML+"Ref");
     animSet = new Dictionary<string, Animation>();
     //Set the initial current frame to the first image in the sprite sheet.
     int h = animSource.First().Value.Height;
     int w = animSource.First().Value.Width;
     CurrentFrame = new Rectangle(0, 0, w, h);
 }
Example #7
0
 public FakeWorklistItem(Dictionary<string, Type> activityTypes, int maxRetries = 0, int currentRetries = 0) :
     base(9235, 
          new Guid(activityTypes.First().Value.Name.Substring(activityTypes.First().Value.Name.IndexOf("_", StringComparison.Ordinal) + 1, activityTypes.First().Value.Name.Length - 1 - activityTypes.First().Value.Name.IndexOf("_", System.StringComparison.Ordinal)).Replace("_", "-")),
          "Fake Activity", maxRetries, currentRetries)
 {
     var random = new Random();
     InstanceId = random.Next(1, 999999);
     KeyValue = random.Next(1, 999999);
 }
 public InstallSupplementalPackAction(Dictionary<Host, VDI> suppPackVdis, bool suppressHistory)
     : base(null, 
     suppPackVdis.Count > 1
         ? string.Format(Messages.UPDATES_WIZARD_APPLYING_UPDATE_MULTIPLE_HOSTS, suppPackVdis.Count) 
         : string.Format(Messages.UPDATES_WIZARD_APPLYING_UPDATE, suppPackVdis.First().Value, suppPackVdis.First().Key), 
     suppressHistory)
 {
     this.suppPackVdis = suppPackVdis;
 }
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var dict = new Dictionary<string, Dictionary<string, Dictionary<string, IndexSettings>>>();
			serializer.Populate(reader, dict);
			var response = new IndexSettingsResponse();
			if (!dict.HasAny() || !dict.First().Value.HasAny() || !dict.First().Value.First().Value.HasAny())
				return response;
			response.Nodes = dict.ToDictionary(k => k.Key, v => v.Value.First().Value.First().Value);
			return response;
		}
        /// <summary>
        /// Builds the necessary code containing the simple controller logic required for the controller class.
        /// </summary>
        /// <param name="columnlist"> Dictionery containg the list of column name as key and datatype as value.</param>
        /// <param name="moduleName">Module name.</param>
        /// <returns>Returns the methods codes required for the controller class.</returns>

        public static StringBuilder ControllerCode(Dictionary<string, string> columnlist, string moduleName)
        {
            StringBuilder code = new StringBuilder();
            string firstColumnName = columnlist.First().Key;
            string firstColumnDataType = columnlist.First().Value;
            code.Append(ExecuteNonQueryCode(moduleName, "Insert"));
            code.Append(ExecuteNonQueryCode(moduleName, "Update"));
            code.Append(SelectQuery(moduleName, "GetallData", true, firstColumnName, firstColumnDataType));
            code.Append(SelectQuery(moduleName, "GetByID", false, firstColumnName, firstColumnDataType));
            code.Append(DeleteQuery(moduleName, "DeleteByID", firstColumnName, firstColumnDataType));
            return code;
        }
        public void Transforming_keys_does_not_modify_original_dictionary()
        {
            var original = new Dictionary<string, int>
                {
                    { "Key 1", 1 }
                };

            original.TransformKeys(x => x.ToUpper());

            Assert.AreEqual("Key 1", original.First().Key);
            Assert.AreEqual(1, original.First().Value);
        }
Example #12
0
 /// <summary>метод который формирует данные для chart-а на основе колекции серий, 
 /// поинтов и их пересечений </summary>
 private SeriesCollection FillData(
     Dictionary<string, float> seriesDef, 
     Dictionary<string, float> pointDef,
     Dictionary<Intersection, float> intersections)
 {
     SeriesCollection result = new SeriesCollection();
     if (!subDiagramMode)
     {
         switch (this.DiagramType)
         {
             case DiagramTypeEnum.Graph:
                 result.Add(CreateDataForFullDiagram(seriesDef, pointDef, intersections, true));
                 break;
             case DiagramTypeEnum.ColumnDetail:
                 result.Add(CreateDataForFullDiagram(seriesDef, pointDef, intersections, false));
                 break;
             case DiagramTypeEnum.ColumnGeneral:
                 result.Add(CreateDataForColumnGeneral(seriesDef));
                 break;
             case DiagramTypeEnum.PieGeneral:
                 result.Add(CreateDataForPieGeneral(seriesDef));
                 break;
             case DiagramTypeEnum.Speedometer:
             case DiagramTypeEnum.TrafficLight:
                 if (seriesDef.Any( s => s.Key.Equals(defaultSeries)))
                     result.Add(FillSeriesData(seriesDef.First(s => s.Key.Equals(defaultSeries))));
                 break;
             case DiagramTypeEnum.PieDetail:
                 if (seriesDef.Any(s => s.Key.Equals(defaultSeries)))
                     result.Add(FillPointsData(seriesDef.First(s => s.Key.Equals(defaultSeries)),
                         pointDef, intersections, false));
                 break;
         }
     }
     else
     {
         if (string.IsNullOrEmpty(detalizedSeriesName)) detalizedSeriesName = this.defaultSeries;
         if (seriesDef.Any(s => s.Key.Equals(detalizedSeriesName)))
         {
             switch (this.SubDiagramType)
             {
                 case SubDiagramTypeEnum.Graph:
                 case SubDiagramTypeEnum.ColumnDetail:
                 case SubDiagramTypeEnum.PieDetail:
                     result.Add(FillPointsData(seriesDef.First(s => s.Key.Equals(detalizedSeriesName)),
                         pointDef, intersections, false));
                     break;
             }
         }
     }
     FillEmptyVisibleSeries(seriesDef.Keys.ToList());
     return result;
 }
    /// <summary>
    /// Returns true if the row is found. The LatestDate can still be null
    /// </summary>
    /// <param name="Table"></param>
    /// <param name="PrimaryKeys"></param>
    /// <param name="LatestDate"></param>
    /// <returns></returns>
    public bool TryGetLatestDate(JupiterTables Table, Dictionary<string, string> PrimaryKeys, out DateTime? LatestDate)
    {
      LatestDate = null;
      if (PrimaryKeys.Values.Any(var => var == ""))
        return false;

      string sql = "select INSERTDATE, UPDATEDATE from " + Table.ToString();

      switch (Table)
      {
        case JupiterTables.BOREHOLE:
          sql = sql + " WHERE " + PrimaryKeys.First().Key + " = '" + PrimaryKeys.First().Value + "'";
          break;
        case JupiterTables.SCREEN:
          sql = sql + " WHERE BOREHOLENO = '" + PrimaryKeys["BOREHOLENO"] + "' and SCREENNO = " + PrimaryKeys["SCREENNO"];
          break;
        case JupiterTables.DRWPLANTINTAKE:
          sql = sql + " WHERE " + PrimaryKeys.First().Key + " = " + PrimaryKeys.First().Value + "";
          break;
        default:
          break;
      }

      OleDbCommand command = new OleDbCommand(sql, odb);
      OleDbDataReader reader2;
      reader2 = command.ExecuteReader();
      reader2.Read();
      LatestDate = null;

      if (!reader2.HasRows)
        return false;

      DateTime UpdateDate;
     
      if (!reader2.IsDBNull(0))
      {
        LatestDate = reader2.GetDateTime(0);
      }
      if (!reader2.IsDBNull(1))
      {
          UpdateDate = reader2.GetDateTime(1);
        if (LatestDate.HasValue)
        {
          if (LatestDate.Value.CompareTo(UpdateDate)<0)
            LatestDate = UpdateDate;
        }
        else
          LatestDate = UpdateDate;
      }
      command.Dispose();
      reader2.Dispose();
      return true;
    }
 public void should_map_paremeters()
 {
     var dynRaml = new Dictionary<string, object>();
     dynRaml.Add("type", "string");
     dynRaml.Add("displayName", "ParameterName");
     dynRaml.Add("description", "this is the description");
     var parameters = new Dictionary<string, Parameter> {{"one", new ParameterBuilder().Build(dynRaml)}};
     var generatorParameters = ParametersMapper.Map(parameters);
     Assert.AreEqual(parameters.Count, generatorParameters.Count());
     Assert.AreEqual(parameters.First().Value.Type, generatorParameters.First().Type);
     Assert.AreEqual("one", generatorParameters.First().Name);
     Assert.AreEqual(parameters.First().Value.Description, generatorParameters.First().Description);
 }
        public bool MergeFiles(Dictionary<string, ReportContext> MergedFiles, string mergedFile, out string outputFile)
        {
            Excel.Workbook bookDest = null;
            try
            {
                bookDest = excel.Workbooks.Add(Missing.Value);

                //create a new work sheet
                Excel.Worksheet sheetDest = bookDest.Worksheets[1] as Excel.Worksheet;

                if (MergedFiles.Count > 0)
                {
                    this.Logger.Message("Merge " + MergedFiles.First().Key);
                    sourceBook = excel.Workbooks.Open(MergedFiles.First().Value.OutputFullName);
                    Excel.Worksheet sheet = sourceBook.Worksheets[1];
                    sheet.Name = "Summary";

                    sheet.Copy(Missing.Value, sheetDest);

                    Excel.Worksheet copysheet = bookDest.Worksheets["Summary"];

                    this.FormatSummary(copysheet);

                    FunnelReportHelper.CloseWorkingWorkbook(sourceBook);
                }

                foreach (var item in bookDest.Worksheets)
                {
                    Excel.Worksheet sheet = item as Excel.Worksheet;
                    if (sheet.Name != "Summary")
                        sheet.Delete();
                }

                //outputFile = "ChinaDash_" + DateTime.Now.ToString("yyyMMdd") + ".xls";
                outputFile = mergedFile.Replace(".xls", "_" + DateTime.Now.ToString("yyyMMdd") + ".xls");

                if (File.Exists(outputFile))
                {
                    File.Delete(outputFile);
                }

                bookDest.SaveAs(outputFile);
                bookDest.Close();
            }
            catch (Exception ex)
            {
                throw;
            }

            return true;
        }
Example #16
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
										JsonSerializer serializer)
        {
            var dict = new Dictionary<string, TemplateMapping>();
            serializer.Populate(reader, dict);
            if (dict.Count == 0)
                throw new DslException("Could not deserialize TemplateMapping1");

            return new TemplateResponse
            {
                Name = dict.First().Key,
                TemplateMapping = dict.First().Value
            };
        }
        public void CoursesCorrelation(List<string> callStack, Dictionary<string, decimal> coursesCatalog, List<string> coursesList)
        {
            while (coursesCatalog.Any(coursePointer => coursePointer.Value < 0))
            {
                callStack.Clear();
                var courseTarget = coursesCatalog.First(coursePointer => coursePointer.Value < 0).Key;
                while (courseTarget != "loop" && courseTarget != "base")
                {
                    courseTarget = recursiveInsight(courseTarget, callStack, coursesCatalog, coursesList);
                }

                if (courseTarget == "loop")
                {
                    foreach (var coursePointer in callStack)
                        coursesCatalog[coursePointer] = 0.1M;
                }
                if (courseTarget == "base")
                {
                    var courseLevelSetup = callStack.Count;

                    foreach (var coursePointer in callStack)
                    {
                        coursesCatalog[coursePointer] = courseLevelSetup;
                        courseLevelSetup--;
                    }
                }
            }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Dictionary<string, object> aggsDict = serializer.Deserialize<Dictionary<string, object>>(reader);

            List<IAggregation> aggGenerators = new List<IAggregation>();
            AggregationTypeEnum aggType = AggregationTypeEnum.DateHistogram;
            foreach (KeyValuePair<string, object> aggKvp in aggsDict)
            {
                Dictionary<string, object> aggDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(aggKvp.Value.ToString());
                KeyValuePair<string, object> aggTypeKvp = aggDict.First();

                // create a dictionary just for this one
                Dictionary<string, object> internalDict = new Dictionary<string, object>();
                internalDict.Add(aggKvp.Key, aggKvp.Value);
                Dictionary<string, object> aggTypeDict = new Dictionary<string, object>();
                aggTypeDict.Add("junk", internalDict);

                aggType = AggregationTypeEnum.Find(aggTypeKvp.Key);
                if (aggType == null)
                    throw new Exception(aggTypeKvp.Key + " is not a valid type of aggregation.");

                string facetTypeJsonStr = JsonConvert.SerializeObject(aggTypeDict.First().Value);
                aggGenerators.Add(JsonConvert.DeserializeObject(facetTypeJsonStr, aggType.ImplementationType) as IAggregation);
            }

            Aggregations aggs = new Aggregations(aggGenerators);

            return aggs;
        }
Example #19
0
        private static KeyValuePair<int, int> FindTopNumberInArray(int[] numbers)
        {
            var sequences = new Dictionary<int, int>();

            for (int i = 0; i < numbers.Length; i++)
            {
                if (sequences.ContainsKey(numbers[i]))
                {
                    sequences[numbers[i]]++;
                }
                else
                {
                    sequences[numbers[i]] = 1;
                }
            }

            var majorCandidate = sequences.First();

            foreach (var set in sequences)
            {
                if (majorCandidate.Value < set.Value)
                {
                    majorCandidate = set;
                }
            }
            return majorCandidate;
        }
Example #20
0
        public static Choice GetAiChoice()
        {
            if (PreviousChoices.Count() <= 2)
              {
            return Choice.rock;
              }

              //Find what the player choose last, and then figure out what they usually chose next
              Dictionary<Choice, int> choiceCount = new Dictionary<Choice, int>();
              choiceCount.Add(Choice.paper, 0);
              choiceCount.Add(Choice.rock, 0);
              choiceCount.Add(Choice.scissors, 0);
              char lastChoice = PreviousChoices[PreviousChoices.Length - 1];
              for (int index = PreviousChoices.Count() - 2; index >= 0; index--)
              {
            if (PreviousChoices[index] == lastChoice)
            {
              switch ((Choice)(int.Parse(PreviousChoices[index + 1].ToString())))
              {
            case Choice.rock:
              choiceCount[Choice.rock]++;
              break;
            case Choice.paper:
              choiceCount[Choice.paper]++;
              break;
            case Choice.scissors:
              choiceCount[Choice.scissors]++;
              break;
              }
            }
              }

              return GetWinner(choiceCount.First(choice => choice.Value == choiceCount.Values.Max()).Key);
        }
        /// <summary>
        /// Business or validation rule implementation.
        /// </summary>
        /// <param name="context">Rule context object.</param>
        protected override void Execute(RuleContext context)
        {
            var sections = (ProcessSections)context.InputPropertyValues[PrimaryProperty];

            if (sections == null || sections.Count == 0)
                return;

            //ignore parent
            var localSections = sections.Where(s => !s.IsBase).ToList();

            //duplicate section name check
            var duplicateSections = localSections.Where(x => localSections.Count(y => y.Name == x.Name) > 1);
            foreach (var section in duplicateSections)
                context.AddErrorResult(string.Format(LanguageService.Translate("Rule_UniqueSectionName"), section.Name));

            //duplicate field's system name check
            var fields = new Dictionary<string, string>();
            foreach (var section in sections.Where(s => s.FieldList != null))
                foreach (var field in section.FieldList.Where(f => !string.IsNullOrEmpty(f.SystemName)))
                    if (fields.Keys.Any(key => key.ToUpperInvariant().Equals(field.SystemName.ToUpperInvariant())))
                    {
                        var duplicate = fields.First(f => f.Key.Equals(field.SystemName, StringComparison.OrdinalIgnoreCase));
                        context.AddErrorResult(string.Format(LanguageService.Translate("Rule_UniqueFieldSystemNames"), field.SystemName, section.Name, duplicate.Value));
                    }
                    else
                        fields.Add(field.SystemName, section.Name);
        }
        /// <summary>
        /// Converts a DateTime into a Human Readable relative date. For example: 1/Feb/2011 => "1 month ago".
        /// Also see http://timeago.yarp.com/ for a clientside way to do this
        /// </summary>
        /// <seealso cref="http://timeago.yarp.com/"/>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToTimeAgo(this DateTime input)
        {
            TimeSpan span = DateTime.Now.Subtract(input);
            double totalMinutes = span.TotalMinutes;
            string suffix = " ago";

            if (totalMinutes < 0.0)
            {
                totalMinutes = Math.Abs(totalMinutes);
                suffix = " from now";
            }

            var aValue = new Dictionary<double, Func<string>>();
            aValue.Add(0.75, () => "less than a minute");
            aValue.Add(1.5, () => "about a minute");
            aValue.Add(45, () => string.Format("{0} minutes", Math.Round(totalMinutes)));
            aValue.Add(90, () => "about an hour");
            aValue.Add(1440, () => string.Format("about {0} hours", Math.Round(Math.Abs(span.TotalHours)))); // 60 * 24
            aValue.Add(2880, () => "a day"); // 60 * 48
            aValue.Add(43200, () => string.Format("{0} days", Math.Floor(Math.Abs(span.TotalDays)))); // 60 * 24 * 30
            aValue.Add(86400, () => "about a month"); // 60 * 24 * 60
            aValue.Add(525600, () => string.Format("{0} months", Math.Floor(Math.Abs(span.TotalDays / 30)))); // 60 * 24 * 365
            aValue.Add(1051200, () => "about a year"); // 60 * 24 * 365 * 2
            aValue.Add(double.MaxValue, () => string.Format("{0} years", Math.Floor(Math.Abs(span.TotalDays / 365))));

            return aValue.First(n => totalMinutes < n.Key).Value.Invoke() + suffix;
        }
 public TagCloudService(Dictionary<string, int> Tags, int Width, int Height)
 {
     _Increment = It => It + _SpiralRoom;
         _Decrement = It => It - _SpiralRoom;
         if (null == Tags || 0 == Tags.Count)
             _Die("Argument Exception, No Tags to disorganize");
         if (Width < 30 || Height < 30)
             _Die("Way too low Width or Height for the cloud to be useful");
         _Width = Width;
         _Height = Height;
         _MainArea = new RectangleF(0, 0, Width, Height);
         _MaxEdgeSize = Width >= Height ? Width : Height;
         /* Sentinel is a definitely out of bounds point that the spiral normally
          * should never reach. */
         _SpiralEndSentinel = new PointF(_MaxEdgeSize + 10, _MaxEdgeSize + 10);
         var Sorted = from Tag in Tags
                      orderby Tag.Value descending
                      select new {Tag.Key, Tag.Value};
         _TagsSorted = Sorted.ToDictionary(x => x.Key, x => x.Value);
         _LowestWeight = _TagsSorted.Last().Value;
         _HighestWeight = _TagsSorted.First().Value;
         _Occupied = new List<RectangleF>(_TagsSorted.Count + 4);
         WordsSkipped = new Dictionary<string, int>();
         ApplyDefaults();
 }
Example #24
0
        static void Main(string[] args)
        {
            int[] array = ArrayHelpers<int>.Build(20, -10, 5);
            Console.WriteLine("Original array");
            ArrayHelpers<int>.Print(array);

            // sort the array
            ArrayHelpers<int>.Quicksort(array, 0, array.Length - 1, true);

            Console.WriteLine("Sorted array");
            ArrayHelpers<int>.Print(array);

            Dictionary<int, int> counters = new Dictionary<int, int>();
            // go through every element and increment the counter in the dictionary for that element
            for (int i = 0; i < array.Length; i++) {
                if (counters.ContainsKey(array[i])) {
                    counters[array[i]] += 1;
                } else {
                    counters[array[i]] = 1;
                }
            }

            // sort the dictionary by occurence
            counters = counters.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

            Console.WriteLine("Element with the highest occurence is " + counters.First().Key);
        }
Example #25
0
 public static void Main()
 {
     var cmds = new Dictionary<string, Func<int, int>>{
         //Part1
         //{"turn on", x => 1},
         //{"turn off", x => 0},
         //{"toggle", x => 1-x},
         //Part2:
         {"turn on", x => x+1},
         {"turn off", x => Math.Max(0, x-1)},
         {"toggle", x => x+2},
     };
     // Idea of this solution:
     // make a lazy sequence of tuples (x, y, change), and apply them to bulbs map during the enumeration.
     var map = new int[1000,1000];
     var effects =
         from line in File.ReadLines("input.txt")
         let change = cmds.First(c => line.StartsWith(c.Key)).Value
         let splitted = line.Split(' ')
         let p1=splitted[splitted.Length-3].Split(',').Select(int.Parse).ToList()
         let p2=splitted[splitted.Length-1].Split(',').Select(int.Parse).ToList()
         from x in Enumerable.Range(p1[0], p2[0]-p1[0]+1)
         from y in Enumerable.Range(p1[1], p2[1]-p1[1]+1)
         select map[x,y]=change(map[x, y]);
     effects.Count(); //force to enumerate lazy sequence
     Console.WriteLine(map.Cast<int>().Sum()); //Cast converts int[,] to IEnumerable<int>
 }
        //        public TeamLeasingSearchController(IPortfolioLogic portfolioLogic) // PortfolioLogic
        //        {
        //            _portfolioLogic = portfolioLogic;
        //        }
        // GET: TeamLeasing/TeamLeasingSearch
        public ActionResult Index(TeamLeasingSearchModel model)
        {
            Dictionary<Func<TeamLeasingSearchModel, bool>, Func<TeamLeasingSearchModel, ActionResult>> IndexActionMap = new Dictionary<Func<TeamLeasingSearchModel, bool>, Func<TeamLeasingSearchModel, ActionResult>>
            {
                { (item) => item.Duch == "tadam", Duch },
                { (item) => item.Ksebal == "jaja", Ksebal },
                { (item) => item.Szyfrant == "haha", Szyfrant },
            };

            try
            {
                IndexActionMap.First(item => item.Key(model)).Value(model);

                // MOCK !!!!!!!!

               // IPortfolioBusinessModel result = _portfolioLogic.GetEmployeePortfolio(5);

                //result.Technologies
                //model.Confirm

                model.ViewDataResults = new List<TeamSearchResults>
                {
                    new TeamSearchResults { Name = "Patryk"},
                    new TeamSearchResults { Name = "Agata"},
                };
            }
            catch (Exception)
            {

            }

            return View(model);
        }
Example #27
0
        public override IEnumerable<string> Executar(Grafo grafo)
        {
            grafo.Direcionado = true;

            var retorno = new List<string>();
            Dictionary<string, Vertice> Q = new Dictionary<string, Vertice>();
            var primeiro = grafo.Vertices.First();
            Q.Add(primeiro.Key, primeiro.Value);
            while (Q.Any())
            {
                var U = Q.First();
                Q.Remove(Q.Keys.First());
                foreach (var vertice in grafo.GetAdj(U.Key))
                {
                    if (vertice.Value.Cor == CoresEnum.Branco)
                    {
                        vertice.Value.Descoberta = U.Value.Descoberta + 1;
                        vertice.Value.Pai = U.Value;
                        vertice.Value.Cor = CoresEnum.Cinza;
                        Q.Add(vertice.Key, vertice.Value);
                    }
                }
                retorno.Add(String.Format("{0} {1} {2}", grafo.Vertices.First().Key, U.Value.Id, U.Value.Descoberta));
                U.Value.Cor = CoresEnum.Preto;
            }

            return retorno;
        }
Example #28
0
        //----------------------------------------------Drawing_OnDraw----------------------------------------
        static void Drawing_OnDraw(EventArgs args)
        {
            if (!Player.IsDead)
            {
                if (Target != null)
                {
                    if (Target.IsValidTarget(1700))
                    {
                        if (Menu["UltiPos && Hits"].Cast<CheckBox>().CurrentValue && R.IsReady())
                        {
                            PosAndHits = GetBestRPos(Target.ServerPosition.To2D());

                            if (PosAndHits.First().Value >= Menu["Min Enemies R"].Cast<Slider>().CurrentValue)
                            {
                                Drawing.DrawCircle(PosAndHits.First().Key.To3D(), 70, Color.Yellow);
                                Drawing.DrawText(Drawing.WorldToScreen(Player.Position).X, Drawing.WorldToScreen(Player.Position).Y - 200, Color.Yellow, string.Format("R WILL HIT {0} ENEMIES", PosAndHits.First().Value));
                            }
                        }
                    }
                }

                if (Menu["DrawQ"].Cast<CheckBox>().CurrentValue)
                    Circle.Draw(Q.IsReady() ? Green : Red, Q.Range, Player.Position);

                if (Menu["DrawR"].Cast<CheckBox>().CurrentValue)
                    Circle.Draw(R.IsReady() ? Green : Red, R.Range, Player.Position);

                if (Smite != null)
                    if (Menu["DrawSmite"].Cast<CheckBox>().CurrentValue)
                        Circle.Draw(Smite.IsReady() ? Green : Red, Smite.Range, Player.Position);

            }

            return;
        }
 public EffectsPropertyModifiedUndoAction(Dictionary<Element, Tuple<Object, PropertyDescriptor>> effectPropertyValues)
 {
     if (effectPropertyValues == null) throw new ArgumentNullException("effectPropertyValues");
     ElementValues = effectPropertyValues;
     if (effectPropertyValues.Count > 0)
         DisplayName = effectPropertyValues.First().Value.Item2.DisplayName;
 }
Example #30
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Dictionary<string, object> suggestDict = serializer.Deserialize<Dictionary<string, object>>(reader);

            List<ISuggester> suggestors = new List<ISuggester>();
            SuggestTypeEnum suggestType = SuggestTypeEnum.Term;
            foreach (KeyValuePair<string, object> fieldKvp in suggestDict.Where(x => !x.Key.Equals(_TEXT)))
            {
                // dig down to get the type i am dealing with
                Dictionary<string, object> fieldSuggestDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(fieldKvp.Value.ToString());
                KeyValuePair<string, object> suggestTypeKvp = fieldSuggestDict.FirstOrDefault(x => !x.Key.Equals(_TEXT));

                // create a dictionary just for this one
                Dictionary<string, object> internalDict = new Dictionary<string, object>();
                internalDict.Add(fieldKvp.Key, fieldKvp.Value);
                Dictionary<string, object> suggestTypeDict = new Dictionary<string,object>();
                suggestTypeDict.Add("junk", internalDict);

                suggestType = SuggestTypeEnum.Find(suggestTypeKvp.Key);
                if (suggestType == null)
                    throw new Exception(suggestTypeKvp.Key + " is not a valid type of suggestor.");

                string suggestTypeJsonStr = JsonConvert.SerializeObject(suggestTypeDict.First().Value);
                suggestors.Add(JsonConvert.DeserializeObject(suggestTypeJsonStr, suggestType.ImplementationType) as ISuggester);
            }

            Suggest suggest = new Suggest(suggestors);
            suggest.Text = suggestDict.GetStringOrDefault(_TEXT);

            return suggest;
        }