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 );
        }
Пример #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;
        }
		/// <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();
            }
        }
        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;
        }
Пример #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);
 }
Пример #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;
		}
        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);
        }
Пример #11
0
        /// <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;
        }
Пример #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);
 }
Пример #15
0
        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;
        }
Пример #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
            };
        }
Пример #17
0
        public void SendMessage(Message message)
        {
            InsertMessage(message);
            IMessageServiceCallback receiverCallBack = _clients?.First(client => client.Key == message.ReceiverId).Value;

            receiverCallBack?.ForwardToClient(message);
        }
Пример #18
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>
 }
Пример #19
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;
        }
Пример #20
0
 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();
 }
Пример #21
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);
        }
 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;
 }
Пример #23
0
        /// <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;
        }
Пример #24
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);
        }
Пример #25
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;
        }
Пример #26
0
        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;
        }
Пример #27
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;
        }
        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 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);
        }
        /// <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);
        }
 public static ServiceWebView GetWebViewPlayerById(int id = -1, int tabNo = -1)
 {
     try
     {
         if (id == -1 && tabNo == -1)
         {
             id = _webViewMediaPlayerNumberIsStreaming;
             return(WebViewIdDictionary[id]);
         }
         else if (id == -1 && tabNo != -1)
         {
             return(WebViewTabDictionary[tabNo]);
         }
         else if (id != -1)
         {
             return(WebViewIdDictionary[id]);
         }
         else
         {
             return(WebViewIdDictionary?.First().Value);
         }
     }
     catch
     {
     }
     return(null);
 }
Пример #32
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;
        }
        public void SendMessage(Message message)
        {
            var sendTo = _clients?.First(c => c.Key == message.ToUserId).Value;

            if (sendTo != null)
            {
                sendTo.ForwardToClient(message);
            }
        }
Пример #34
0
        /// <summary>
        /// Should return a random pixel within the items/blocks texture
        /// </summary>
        /// <param name="world"></param>
        /// <param name="pos"></param>
        /// <param name="facing"></param>
        /// <param name="tintIndex"></param>
        /// <returns></returns>
        public override int GetRandomColor(ICoreClientAPI capi, ItemStack stack)
        {
            if (Textures == null || Textures.Count == 0)
            {
                return(0);
            }

            BakedCompositeTexture tex = Textures?.First().Value?.Baked;

            return(tex == null ? 0 : capi.ItemTextureAtlas.GetRandomColor(tex.TextureSubId));
        }
Пример #35
0
        private bool ContainsKanji(string kanji, bool exactMatch)
        {
            if (kanji == null)
            {
                return(false);
            }
            List <Dictionary <string, string> > kanjiList = data?.First().Value.kanji;
            bool hasKanjiList = kanjiList != null && kanjiList.Count > 0;

            if (!hasKanjiList)
            {
                return(false);
            }
            List <string> compounds = kanjiList.SelectMany(k => k.Values).ToList();

            if (exactMatch)
            {
                return(compounds.FirstOrDefault(c => c == kanji) != null);
            }
            else
            {
                return(compounds.FirstOrDefault(c => c.Contains(kanji)) != null);
            }
        }
        public static TBase[] FromTwoDimensionalArray <TBase, T>(
            this Dictionary <string, T[, ]> items,
            Dictionary <string, Action <TBase, T[]> > setters,
            TwoDimensionalArray dimensionality = TwoDimensionalArray.None)
            where TBase : new()
        {
            // This code is covered by unit tests Acoustics.Test - change the unit tests before you change the class!
            Contract.Requires(items != null);
            Contract.Requires(setters != null);

            // assume all matrices contain the same number of elements
            int major     = dimensionality == TwoDimensionalArray.None ? 0 : 1;
            int minor     = major == 1 ? 0 : 1;
            var itemCount = items.First().Value.GetLength(major);

            int keyCount = setters.Keys.Count;
            var results  = new TBase[itemCount];

            // initialize all values
            for (int index = 0; index < results.Length; index++)
            {
                results[index] = new TBase();
            }

            Parallel.ForEach(
                setters,
                (kvp, state, index) =>
            {
                var key    = kvp.Key;
                var setter = kvp.Value;

                var matrix = items[key];
                for (int i = 0; i < itemCount; i++)
                {
                    var lineLength = matrix.GetLength(minor);
                    T[] line       = new T[lineLength];

                    for (int j = 0; j < lineLength; j++)
                    {
                        switch (dimensionality)
                        {
                        case TwoDimensionalArray.None:
                            line[j] = matrix[i, j];
                            break;

                        case TwoDimensionalArray.Transpose:
                            line[j] = matrix[j, i];
                            break;

                        case TwoDimensionalArray.Rotate90ClockWise:
                            line[j] = matrix[lineLength - 1 - j, i];
                            break;

                        default:
                            throw new NotImplementedException("Dimensionality not supported");
                        }
                    }

                    // set the line (row or column) to the instance
                    setter(results[i], line);
                }
            });

            return(results);
        }
Пример #37
0
        private void RunSingleCompilation(Dictionary <string, string> inFilePaths, InstructionSetSupport instructionSetSupport, string compositeRootPath, Dictionary <string, string> unrootedInputFilePaths, HashSet <ModuleDesc> versionBubbleModulesHash, CompilerTypeSystemContext typeSystemContext)
        {
            //
            // Initialize output filename
            //
            string inFilePath         = inFilePaths.First().Value;
            string inputFileExtension = Path.GetExtension(inFilePath);
            string nearOutFilePath    = inputFileExtension switch
            {
                ".dll" => Path.ChangeExtension(inFilePath,
                                               _commandLineOptions.SingleFileCompilation && _commandLineOptions.InputBubble
                        ? ".ni.dll.tmp"
                        : ".ni.dll"),
                ".exe" => Path.ChangeExtension(inFilePath,
                                               _commandLineOptions.SingleFileCompilation && _commandLineOptions.InputBubble
                        ? ".ni.exe.tmp"
                        : ".ni.exe"),
                _ => throw new CommandLineException(string.Format(SR.UnsupportedInputFileExtension, inputFileExtension))
            };
            string outFile = _commandLineOptions.OutNearInput ? nearOutFilePath : _commandLineOptions.OutputFilePath;

            using (PerfEventSource.StartStopEvents.CompilationEvents())
            {
                ICompilation compilation;
                using (PerfEventSource.StartStopEvents.LoadingEvents())
                {
                    List <EcmaModule> inputModules   = new List <EcmaModule>();
                    List <EcmaModule> rootingModules = new List <EcmaModule>();

                    foreach (var inputFile in inFilePaths)
                    {
                        EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
                        inputModules.Add(module);
                        rootingModules.Add(module);
                        versionBubbleModulesHash.Add(module);


                        if (!_commandLineOptions.CompositeOrInputBubble)
                        {
                            break;
                        }
                    }

                    foreach (var unrootedInputFile in unrootedInputFilePaths)
                    {
                        EcmaModule module = typeSystemContext.GetModuleFromPath(unrootedInputFile.Value);
                        inputModules.Add(module);
                        versionBubbleModulesHash.Add(module);
                    }

                    //
                    // Initialize compilation group and compilation roots
                    //

                    // Single method mode?
                    MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext);

                    var logger = new Logger(Console.Out, _commandLineOptions.Verbose);

                    List <string> mibcFiles = new List <string>();
                    foreach (var file in _commandLineOptions.MibcFilePaths)
                    {
                        mibcFiles.Add(file);
                    }

                    List <ModuleDesc> versionBubbleModules = new List <ModuleDesc>(versionBubbleModulesHash);

                    if (!_commandLineOptions.Composite && inputModules.Count != 1)
                    {
                        throw new Exception(string.Format(SR.ErrorMultipleInputFilesCompositeModeOnly, string.Join("; ", inputModules)));
                    }

                    ReadyToRunCompilationModuleGroupBase compilationGroup;
                    List <ICompilationRootProvider>      compilationRoots = new List <ICompilationRootProvider>();
                    if (singleMethod != null)
                    {
                        // Compiling just a single method
                        compilationGroup = new SingleMethodCompilationModuleGroup(
                            typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics,
                            singleMethod);
                        compilationRoots.Add(new SingleMethodRootProvider(singleMethod));
                    }
                    else if (_commandLineOptions.CompileNoMethods)
                    {
                        compilationGroup = new NoMethodsCompilationModuleGroup(
                            typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics);
                    }
                    else
                    {
                        // Single assembly compilation.
                        compilationGroup = new ReadyToRunSingleAssemblyCompilationModuleGroup(
                            typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics);
                    }

                    // Load any profiles generated by method call chain analyis
                    CallChainProfile jsonProfile = null;

                    if (!string.IsNullOrEmpty(_commandLineOptions.CallChainProfileFile))
                    {
                        jsonProfile = new CallChainProfile(_commandLineOptions.CallChainProfileFile, typeSystemContext, _referenceableModules);
                    }

                    // Examine profile guided information as appropriate
                    ProfileDataManager profileDataManager =
                        new ProfileDataManager(logger,
                                               _referenceableModules,
                                               inputModules,
                                               versionBubbleModules,
                                               _commandLineOptions.CompileBubbleGenerics ? inputModules[0] : null,
                                               mibcFiles,
                                               jsonProfile,
                                               typeSystemContext,
                                               compilationGroup,
                                               _commandLineOptions.EmbedPgoData);

                    if (_commandLineOptions.Partial)
                    {
                        compilationGroup.ApplyProfilerGuidedCompilationRestriction(profileDataManager);
                    }
                    else
                    {
                        compilationGroup.ApplyProfilerGuidedCompilationRestriction(null);
                    }

                    if ((singleMethod == null) && !_commandLineOptions.CompileNoMethods)
                    {
                        // For normal compilations add compilation roots.
                        foreach (var module in rootingModules)
                        {
                            compilationRoots.Add(new ReadyToRunRootProvider(
                                                     module,
                                                     profileDataManager,
                                                     profileDrivenPartialNGen: _commandLineOptions.Partial));

                            if (!_commandLineOptions.CompositeOrInputBubble)
                            {
                                break;
                            }
                        }
                    }
                    // In single-file compilation mode, use the assembly's DebuggableAttribute to determine whether to optimize
                    // or produce debuggable code if an explicit optimization level was not specified on the command line
                    OptimizationMode optimizationMode = _optimizationMode;
                    if (optimizationMode == OptimizationMode.None && !_commandLineOptions.OptimizeDisabled && !_commandLineOptions.Composite)
                    {
                        System.Diagnostics.Debug.Assert(inputModules.Count == 1);
                        optimizationMode = ((EcmaAssembly)inputModules[0].Assembly).HasOptimizationsDisabled() ? OptimizationMode.None : OptimizationMode.Blended;
                    }

                    CompositeImageSettings compositeImageSettings = new CompositeImageSettings();

                    if (_commandLineOptions.CompositeKeyFile != null)
                    {
                        byte[] compositeStrongNameKey = File.ReadAllBytes(_commandLineOptions.CompositeKeyFile);
                        if (!IsValidPublicKey(compositeStrongNameKey))
                        {
                            throw new Exception(string.Format(SR.ErrorCompositeKeyFileNotPublicKey));
                        }

                        compositeImageSettings.PublicKey = compositeStrongNameKey.ToImmutableArray();
                    }

                    //
                    // Compile
                    //

                    ReadyToRunCodegenCompilationBuilder builder = new ReadyToRunCodegenCompilationBuilder(
                        typeSystemContext, compilationGroup, _allInputFilePaths.Values, compositeRootPath);
                    string compilationUnitPrefix = "";
                    builder.UseCompilationUnitPrefix(compilationUnitPrefix);

                    ILProvider ilProvider = new ReadyToRunILProvider();

                    DependencyTrackingLevel trackingLevel = _commandLineOptions.DgmlLogFileName == null ?
                                                            DependencyTrackingLevel.None : (_commandLineOptions.GenerateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First);

                    builder
                    .UseIbcTuning(_commandLineOptions.Tuning)
                    .UseMapFile(_commandLineOptions.Map)
                    .UseMapCsvFile(_commandLineOptions.MapCsv)
                    .UsePdbFile(_commandLineOptions.Pdb, _commandLineOptions.PdbPath)
                    .UsePerfMapFile(_commandLineOptions.PerfMap, _commandLineOptions.PerfMapPath, _commandLineOptions.PerfMapFormatVersion)
                    .UseProfileFile(jsonProfile != null)
                    .UseProfileData(profileDataManager)
                    .FileLayoutAlgorithms(_methodLayout, _fileLayout)
                    .UseCompositeImageSettings(compositeImageSettings)
                    .UseJitPath(_commandLineOptions.JitPath)
                    .UseInstructionSetSupport(instructionSetSupport)
                    .UseCustomPESectionAlignment(_commandLineOptions.CustomPESectionAlignment)
                    .UseVerifyTypeAndFieldLayout(_commandLineOptions.VerifyTypeAndFieldLayout)
                    .GenerateOutputFile(outFile)
                    .UseILProvider(ilProvider)
                    .UseBackendOptions(_commandLineOptions.CodegenOptions)
                    .UseLogger(logger)
                    .UseParallelism(_commandLineOptions.Parallelism)
                    .UseResilience(_commandLineOptions.Resilient)
                    .UseDependencyTracking(trackingLevel)
                    .UseCompilationRoots(compilationRoots)
                    .UseOptimizationMode(optimizationMode);

                    if (_commandLineOptions.PrintReproInstructions)
                    {
                        builder.UsePrintReproInstructions(CreateReproArgumentString);
                    }

                    compilation = builder.ToCompilation();
                }
                compilation.Compile(outFile);

                if (_commandLineOptions.DgmlLogFileName != null)
                {
                    compilation.WriteDependencyLog(_commandLineOptions.DgmlLogFileName);
                }

                compilation.Dispose();
            }
        }
Пример #38
0
        private void CreateMaterials(List <Dictionary <string, string> > materials, string current_dir, IProgress <int> progress)
        {
            accessToken = Auth.RefreshAccessToken(authUrl, clientId, clientSecret, Properties.Settings.Default["BeproductRefreshToken"].ToString());

            var client  = new RestClient(ApiServer);
            var request = new RestRequest("/api/" + companyName + "/Material/Folders", Method.GET);

            request.AddHeader("Authorization", "Bearer " + accessToken);
            var response = client.Execute <dynamic>(request);
            var result   = JsonConvert.DeserializeObject <dynamic>(response.Content);

            foreach (var f in result)
            {
                folders.Add(f.name.ToString().ToLower(), f.id.ToString());
            }


            //Getting folder schema ...

            Dictionary <string, string> prev_row = null;
            PostModel material = null;

            int    counter = 1;
            string main_image = null, detail_image = null;
            var    color_images = new List <(string filename, string colorid)>();
            string folderName   = null;


            foreach (var material_row in materials)
            {
                progress?.Report(100 * counter++ / materials.Count);

                if (material_row.First().Value == prev_row?.First().Value&& material_row != materials.Last())
                {
                    //populating material object to be posted to beproduct
                    ProcessRow(material_row, ref material, ref color_images);
                }
                else
                {
                    //We are in the row that starts new material
                    if (material != null)
                    {
                        CreateMaterial(material, folderName, main_image, detail_image, color_images, current_dir);
                    }

                    material = new PostModel {
                        SizeAndColor = new PostModel.MaterialSizeAndColors {
                            Colorways = new List <ExpandoObject>(), Sizes = new List <PostModel.MaterialSizeAndColors.SizeValue>()
                        }, Suppliers = new List <PostModel.Supplier>()
                    };
                    main_image   = null;
                    detail_image = null;

                    folderName = material_row.FirstOrDefault(f => f.Key.ToLower() == "folder").Value;
                    if (!folders.ContainsKey(folderName.ToLower()))
                    {
                        continue;
                    }
                    var mat_fields = new List <PostModel.Field> {
                        new PostModel.Field {
                            id = "active", value = true
                        }, new PostModel.Field {
                            id = "version", value = "1"
                        }
                    };

                    foreach (var f in material_row)
                    {
                        string field_id = ((IEnumerable <dynamic>)GetFields(folders[folderName.ToLower()])).FirstOrDefault(fld => fld.fieldName?.ToString()?.ToLower() == f.Key?.ToLower())?.fieldId?.ToString();
                        if (!string.IsNullOrEmpty(field_id))
                        {
                            mat_fields.Add(new PostModel.Field {
                                id = field_id, value = f.Value
                            });
                        }
                    }

                    ProcessRow(material_row, ref material, ref color_images);

                    material.fields = mat_fields.ToArray();
                    main_image      = material_row.FirstOrDefault(f => f.Key?.ToLower() == "main image").Value?.ToString();
                    detail_image    = material_row.FirstOrDefault(f => f.Key?.ToLower() == "detail image").Value?.ToString();
                }

                prev_row = material_row;
            }

            MessageBox.Show("Material import finished!");
        }
 public static string GetDocumentExtension(string mimeType)
 {
     mimeType = mimeType.Split(';').First();
     return(MimeTypes.Values.Contains(mimeType) ? MimeTypes.First(x => x.Value == mimeType).Key : null);
 }
Пример #40
0
        public PaymentPage()
        {
            var db = new DatabaseHelper();

            Title = "Payment";

            addresses = db.GetAddresses().ToDictionary(x => x.address_id, y => y.AddressString);
            if (!addresses.Any())
            {
                throw new ArgumentException("can't make a payment without an address");
            }

            var props = db.GetProperties();

            properties = new Dictionary <string, int> ();
            foreach (var prop in props)
            {
                if (!properties.ContainsKey(addresses [prop.address_id]))
                {
                    properties.Add(addresses [prop.address_id], prop.property_id);
                }
            }

            if (!properties.Any())
            {
                throw new ArgumentException("can't make a payment without a property");
            }

            property = new Picker {
                Title = "Property", VerticalOptions = LayoutOptions.Start
            };

            foreach (string address in properties.Keys)
            {
                property.Items.Add(address);
            }

            int propertyId = properties.First().Value;

            property.SelectedIndexChanged += (sender, args) =>
            {
                var addressLine = property.Items[property.SelectedIndex];
                propertyId = properties[addressLine];
            };


            tenants = db.GetAllTenants().ToDictionary(x => x.Name, x => x.tenant_id);
            if (!tenants.Any())
            {
                throw new ArgumentException("can't make a payment without a tenant");
            }

            tenant = new Picker {
                Title = "Tenant", VerticalOptions = LayoutOptions.Start
            };

            foreach (string t in tenants.Keys)
            {
                tenant.Items.Add(t);
            }

            int tenantId = tenants.First().Value;

            tenant.SelectedIndexChanged += (sender, args) =>
            {
                var tenantLine = tenant.Items[property.SelectedIndex];
                tenantId = tenants[tenantLine];
            };

            DatePicker dueDate = new DatePicker
            {
                Format          = "D",
                VerticalOptions = LayoutOptions.CenterAndExpand
            };

            dueDate.SetBinding(DatePicker.DateProperty, "due_date");

            var amountDueLabel = new Label {
                Text = "Amount Due"
            };
            Entry amountDue = new Entry
            {
                Placeholder     = "Amount Due",
                VerticalOptions = LayoutOptions.Start
            };

            amountDue.SetBinding(Entry.TextProperty, "amount_due");

            var amountPaidLabel = new Label {
                Text = "Amount Paid"
            };
            Entry amountPaid = new Entry
            {
                Placeholder     = "Amount Paid",
                VerticalOptions = LayoutOptions.Start
            };

            amountPaid.SetBinding(Entry.TextProperty, "amount_paid");

            var saveButton = new Button {
                Text = "Save"
            };

            saveButton.Clicked += (sender, args) =>
            {
                if (payment == null)
                {
                    payment = new Payment();
                }

                payment.property_id = propertyId;
                payment.tenant_id   = tenantId;
                payment.due_date    = dueDate.Date;

                try { payment.amount_due = Convert.ToDecimal(amountDue.Text); } catch (Exception ex) { payment.amount_due = 0M; }

                try { payment.amount_paid = Convert.ToDecimal(amountPaid.Text); } catch (Exception ex) { payment.amount_paid = 0M; }

                DatabaseHelper dbHelper = new DatabaseHelper();
                var            id       = dbHelper.SavePayment(payment);
                Navigation.PopAsync();
            };

            deleteButton = new Button {
                Text = "Delete"
            };
            deleteButton.Clicked += (sender, args) =>
            {
                DatabaseHelper dbHelper = new DatabaseHelper();
                dbHelper.DeletePayment(payment.payment_id);
                Navigation.PopAsync();
            };

            this.Content = new StackLayout
            {
                Padding         = new Thickness(10),
                VerticalOptions = LayoutOptions.StartAndExpand,
                Children        =
                {
                    property,
                    tenant,
                    dueDate,
                    amountDueLabel,
                    amountDue,
                    amountPaidLabel,
                    amountPaid,
                    saveButton,
                    deleteButton
                }
            };
        }
Пример #41
0
        public HubWorld(Game1 game, GraphicsDevice graphicsDevice, ContentManager content) : base(game, graphicsDevice, content)
        {
            _camera = new Camera();

            // --- TEXTURES ---

            var texture       = _content.Load <Texture2D>("Square");
            var playerTexture = _content.Load <Texture2D>("Video/Player/Player");
            var chestTexture  = _content.Load <Texture2D>("Video/Enemies/Chests/ChestSize");

            _staticBackgroundTexture = _content.Load <Texture2D>("Video/Backgrounds/LevelFire/StaticBackgroundDay");
            _farBackgroundTexture    = _content.Load <Texture2D>("Video/Backgrounds/FarBackground");
            _midBackgroundTexture    = _content.Load <Texture2D>("Video/Backgrounds/LevelFire/MidBackground");
            _directBackgroundTexture = _content.Load <Texture2D>("Video/Backgrounds/DirectBackground");
            _frontBackgroundTexture  = _content.Load <Texture2D>("Video/Backgrounds/LevelFire/FrontBackground");

            _frontBackgroundPosition = new Vector2(0, 0);
            _midBackgroundPosition   = new Vector2(0, 0);
            _farBackgroundPosition   = new Vector2(0, 0);

            // --- SOUND ---

            var backgroundMusic = _content.Load <Song>("Audio/Music/TribalMusic");

            var levelSoundEffects = new List <SoundEffect>()
            {
                //_content.Load<SoundEffect>("BallHitsBat"),
                //_content.Load<SoundEffect>("BallHitsWall"),
                //_content.Load<SoundEffect>("PlayerScores"),
            };

            var tileSoundEffects = new List <SoundEffect>()
            {
                //_content.Load<SoundEffect>("Sound/Tile/Break1"),
                //_content.Load<SoundEffect>("Sound/Tile/Break2"),
            };

            var playerSoundEffects = new List <SoundEffect>()
            {
                _content.Load <SoundEffect>("Audio/Sound/Player/FireWhirl"),     // 0
                _content.Load <SoundEffect>("Audio/Sound/Player/FastFall"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Hurt1"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Hurt2"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Attack1"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Attack2"),       // 5
                _content.Load <SoundEffect>("Audio/Sound/Player/Attack3"),
                _content.Load <SoundEffect>("Audio/Sound/Player/StopCast"),
                _content.Load <SoundEffect>("Audio/Sound/Player/GroundPound"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Sprint"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Jump1"),         // 10
                _content.Load <SoundEffect>("Audio/Sound/Player/Jump2"),
                _content.Load <SoundEffect>("Audio/Sound/Player/WallJump"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Cast1"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Cast2"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Death"),         // 15
                _content.Load <SoundEffect>("Audio/Sound/Player/StopSprint"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Walk"),
                _content.Load <SoundEffect>("Audio/Sound/Player/JumpPad"),
                _content.Load <SoundEffect>("Audio/Sound/Player/Respawn"),
            };

            var tikiEnemySoundEffects = new List <SoundEffect>()
            {
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/FireWhirl"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/FastFall"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Hurt1"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Hurt2"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Attack1"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Attack2"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Attack3"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/StopCast"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/GroundPound"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Sprint"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Jump1"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Jump2"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/WallJump"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Cast1"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Cast2"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Death"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/StopSprint"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Walk"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Dart"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/Spirit"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/TorchCast"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/TorchLaunch"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/TorchFireLaunch"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/DartFire"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/TikiEnemy/SpiritFire"),
            };

            var chestSoundEffects = new List <SoundEffect>()
            {
                _content.Load <SoundEffect>("Audio/Sound/Enemies/Chest/Break1"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/Chest/Break2"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/Chest/Break3"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/Chest/Break4"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/Chest/Break5"),
                _content.Load <SoundEffect>("Audio/Sound/Enemies/Chest/BreakGreater"),
            };

            var spellSoundEffects = new List <SoundEffect>()
            {
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/Fire1"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/Fire2"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/Fire3"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/Spirit"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/SpiritHit"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/CollectMoney12"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/CollectMoney5"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/CollectMoney10"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/CollectMoney25"),
                _content.Load <SoundEffect>("Audio/Sound/Hurtboxes/CollectPowerUp"),
            };

            _soundManager = new SoundManager(backgroundMusic, levelSoundEffects);
            //_soundManager.PlayMusic();

            // --- HURTBOXES ---

            var groundPound = _content.Load <Texture2D>("Video/Hurtboxes/GroundPound");
            var fireWhirl   = _content.Load <Texture2D>("Video/Effects/DefaultExplosion");
            var shadowWhirl = _content.Load <Texture2D>("Video/Effects/DefaultExplosion");
            var dart        = _content.Load <Texture2D>("Square");
            var torch       = _content.Load <Texture2D>("Square");
            var spirit      = _content.Load <Texture2D>("Square");

            var explosion = new Dictionary <string, Models.Animation>()
            {
                { "Explode", new Animation(_content.Load <Texture2D>("Video/Effects/DefaultExplosion"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "Water", new Animation(_content.Load <Texture2D>("Video/Effects/WaterExplosion"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "Fire", new Animation(_content.Load <Texture2D>("Video/Effects/FireExplosion"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "Earth", new Animation(_content.Load <Texture2D>("Video/Effects/EarthExplosion"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "Air", new Animation(_content.Load <Texture2D>("Video/Effects/AirExplosion"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "Shadow", new Animation(_content.Load <Texture2D>("Video/Effects/ShadowExplosion"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "ShadowWhirl", new Animation(_content.Load <Texture2D>("Video/Effects/ShadowWhirl"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "ShadowSmall", new Animation(_content.Load <Texture2D>("Video/Effects/ShadowExplosionSmall"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "ShadowTiny", new Animation(_content.Load <Texture2D>("Video/Effects/ShadowExplosionTiny"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "WaterSmall", new Animation(_content.Load <Texture2D>("Video/Effects/WaterExplosionSmall"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "FireSmall", new Animation(_content.Load <Texture2D>("Video/Effects/FireExplosionSmall"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "EarthSmall", new Animation(_content.Load <Texture2D>("Video/Effects/EarthExplosionSmall"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "AirSmall", new Animation(_content.Load <Texture2D>("Video/Effects/AirExplosionSmall"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
                { "PowerUp", new Animation(_content.Load <Texture2D>("Video/Effects/PowerUpExplosion"), 1)
                  {
                      FrameSpeed = 1f,
                  } },
                { "FireWhirl", new Animation(_content.Load <Texture2D>("Video/Effects/FireWhirl"), 1)
                  {
                      FrameSpeed = 1f,
                  } },
                { "GroundPoundExplosion", new Animation(_content.Load <Texture2D>("Video/Effects/GroundPoundExplosion"), 1)
                  {
                      FrameSpeed = 0.5f,
                  } },
            };
            var explosionPrefab = new Explosion(explosion);

            var groundPoundPrefab = new GroundPound(groundPound)
            {
                Explosion    = explosionPrefab,
                SoundManager = new SoundManager(backgroundMusic, spellSoundEffects),
            };
            var fireWhirlPrefab = new FireWhirl(fireWhirl)
            {
                Explosion    = explosionPrefab,
                SoundManager = new SoundManager(backgroundMusic, spellSoundEffects),
            };
            var dartPrefab = new Dart(dart)
            {
                Explosion    = explosionPrefab,
                SoundManager = new SoundManager(backgroundMusic, spellSoundEffects),
            };
            var torchPrefab = new Torch(torch)
            {
                Explosion    = explosionPrefab,
                SoundManager = new SoundManager(backgroundMusic, spellSoundEffects),
            };
            var spiritPrefab = new Spirit(spirit)
            {
                Explosion    = explosionPrefab,
                SoundManager = new SoundManager(backgroundMusic, spellSoundEffects),
            };
            var shadowWhirlPrefab = new ShadowWhirl(shadowWhirl)
            {
                Explosion    = explosionPrefab,
                SoundManager = new SoundManager(backgroundMusic, spellSoundEffects),
            };

            // --- COLLECTIBLES ---

            var money       = _content.Load <Texture2D>("Square");
            var moneyPrefab = new Money(money)
            {
                Explosion    = explosionPrefab,
                SoundManager = new SoundManager(backgroundMusic, spellSoundEffects),
            };
            var powerup       = _content.Load <Texture2D>("Video/Hurtboxes/PowerUp");
            var powerupPrefab = new PowerUp(powerup)
            {
                Explosion    = explosionPrefab,
                SoundManager = new SoundManager(backgroundMusic, spellSoundEffects),
            };

            // --- ANIMATIONS ---

            var playerAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Player/WalkingLeft"), 3) },
                { "MoveRight", new Animation(_content.Load <Texture2D>("Video/Player/WalkingRight"), 3) },
                { "Attack", new Animation(_content.Load <Texture2D>("Video/Player/Attack"), 2)
                  {
                      FrameSpeed = 0.05f,
                  } },
            };
            var tikiWarriorAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2WalkingLeft"), 3) },
                { "MoveRight", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2WalkingRight"), 3) },
                { "Attack", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2Attack"), 2)
                  {
                      FrameSpeed = 0.05f,
                  } },
            };
            var tikiDarterAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2WalkingLeft"), 3) },
                { "MoveRight", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2WalkingRight"), 3) },
                { "Attack", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2Attack"), 2)
                  {
                      FrameSpeed = 0.05f,
                  } },
            };
            var tikiTorcherAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2WalkingLeft"), 3) },
                { "MoveRight", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2WalkingRight"), 3) },
                { "Attack", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/Enemy2Attack"), 2)
                  {
                      FrameSpeed = 0.05f,
                  } },
            };
            var tikiShamanAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/EnemyWalkingLeft"), 3) },
                { "MoveRight", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/EnemyWalkingRight"), 3) },
                { "Attack", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/EnemyAttack"), 2)
                  {
                      FrameSpeed = 0.05f,
                  } },
            };
            var enemyAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/EnemyWalkingLeft"), 3) },
                { "MoveRight", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/EnemyWalkingRight"), 3) },
                { "Attack", new Animation(_content.Load <Texture2D>("Video/Enemies/TikiEnemy/EnemyAttack"), 2)
                  {
                      FrameSpeed = 0.05f,
                  } },
            };
            var chestSmallAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/Chests/ChestSmall"), 1) },
            };
            var chestMediumAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/Chests/ChestMedium"), 1) },
            };
            var chestLargeAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/Chests/ChestLarge"), 1) },
            };
            var chestPowerUpAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/Chests/ChestPowerUp"), 1) },
            };
            var shopPowerUpAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/Chests/ShopPowerUp"), 1) },
            };
            var chestCheckPointAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/Chests/ChestCheckPoint"), 1) },
            };
            var trapAnimations = new Dictionary <string, Animation>()
            {
                { "MoveLeft", new Animation(_content.Load <Texture2D>("Video/Enemies/Trap"), 1) },
            };

            // --- MAP ---

            Tile.Content = _content;

            _map = new Map()
            {
                Sound = new SoundManager(backgroundMusic, playerSoundEffects),
            };

            String inputTiles = File.ReadAllText("Levels/HubWorld/HubWorldTilemap.txt");

            _gridWidth  = 25;
            _gridHeight = 14;
            _grid       = new int[_gridHeight, _gridWidth];

            int i = 0, j = 0;

            foreach (var row in inputTiles.Split('\n'))
            {
                j = 0;
                foreach (var col in row.Trim().Split(','))
                {
                    _grid[i, j] = int.Parse(col.Trim());
                    j++;
                }
                i++;
            }

            _map.Generate(_grid, _tileSize, _level);

            // --- PLAYER ---

            _sprites = new List <Sprite>()
            {
                new Player(playerTexture)
                {
                    Game          = _game,
                    Level         = Levels.HubWorld,
                    Position      = new Vector2(12 * 92, 2 * 92),
                    SoundManager  = new SoundManager(backgroundMusic, playerSoundEffects),
                    CollisionType = CollisionTypes.Full,
                    GroundPound   = groundPoundPrefab,
                    FireWhirl     = fireWhirlPrefab,
                    Explosion     = explosionPrefab,
                    Layer         = 0.1f,
                    CameraTarget  = true,
                    Input         = new Input()
                    {
                        Left       = Keys.A,
                        Right      = Keys.D,
                        Jump       = Keys.Space,
                        Attack     = Keys.RightControl,
                        Sprint     = Keys.LeftShift,
                        FastFall   = Keys.S,
                        StrongJump = Keys.W,
                    },
                    Animations       = new Dictionary <string, Animation>(playerAnimations),
                    AnimationManager = new AnimationManager(playerAnimations.First().Value)
                    {
                        Texture = texture,
                    },
                },

                new ShopPowerUp(chestTexture)
                {
                    Position         = new Vector2(12 * 92, 10 * 92),
                    Game             = _game,
                    SoundManager     = new SoundManager(backgroundMusic, chestSoundEffects),
                    CollisionType    = CollisionTypes.Full,
                    Money            = moneyPrefab,
                    PowerUp          = powerupPrefab,
                    Explosion        = explosionPrefab,
                    Layer            = 0.3f,
                    AI               = new AI(),
                    Animations       = new Dictionary <string, Animation>(shopPowerUpAnimations),
                    AnimationManager = new AnimationManager(shopPowerUpAnimations.First().Value)
                    {
                        Texture = texture,
                    },
                },
            };

            foreach (var tile in _map.CollisionTiles)
            {
                _sprites.Add(tile);
            }

            // --- ENEMIES ---

            String inputEnemies = File.ReadAllText("Levels/HubWorld/HubWorldEnemymap.txt");

            _gridWidth  = 25;
            _gridHeight = 14;
            _grid       = new int[_gridHeight, _gridWidth];

            i = 0;
            j = 0;
            foreach (var row in inputEnemies.Split('\n'))
            {
                j = 0;
                foreach (var col in row.Trim().Split(','))
                {
                    _grid[i, j] = int.Parse(col.Trim());

                    switch (_grid[i, j])
                    {
                    case 10:
                        _sprites.Add(new TikiWarrior(playerTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, tikiEnemySoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            ShadowWhirl      = shadowWhirlPrefab,
                            Money            = moneyPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.1f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(tikiWarriorAnimations),
                            AnimationManager = new AnimationManager(tikiWarriorAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 11:
                        _sprites.Add(new TikiDarter(playerTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, tikiEnemySoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Dart             = dartPrefab,
                            Money            = moneyPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.1f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(tikiDarterAnimations),
                            AnimationManager = new AnimationManager(tikiDarterAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 12:
                        _sprites.Add(new TikiTorcher(playerTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, tikiEnemySoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Torch            = torchPrefab,
                            Money            = moneyPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.1f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(tikiTorcherAnimations),
                            AnimationManager = new AnimationManager(tikiTorcherAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 13:
                        _sprites.Add(new TikiShaman(playerTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, tikiEnemySoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Spirit           = spiritPrefab,
                            Money            = moneyPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.1f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(tikiShamanAnimations),
                            AnimationManager = new AnimationManager(tikiShamanAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 14:
                        _sprites.Add(new TrapDarter(playerTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, tikiEnemySoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Dart             = dartPrefab,
                            Money            = moneyPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.1f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(trapAnimations),
                            AnimationManager = new AnimationManager(trapAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 15:
                        _sprites.Add(new TrapTorcherRotateCW(playerTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, tikiEnemySoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Torch            = torchPrefab,
                            Money            = moneyPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.1f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(trapAnimations),
                            AnimationManager = new AnimationManager(trapAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 16:
                        _sprites.Add(new TrapTorcherRotateCCW(playerTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, tikiEnemySoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Torch            = torchPrefab,
                            Money            = moneyPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.1f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(trapAnimations),
                            AnimationManager = new AnimationManager(trapAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 17:
                        _sprites.Add(new TrapShaman(playerTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, tikiEnemySoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Spirit           = spiritPrefab,
                            Money            = moneyPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.1f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(trapAnimations),
                            AnimationManager = new AnimationManager(trapAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 18:
                        _sprites.Add(new ChestSmall(chestTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, chestSoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Money            = moneyPrefab,
                            PowerUp          = powerupPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.3f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(chestSmallAnimations),
                            AnimationManager = new AnimationManager(chestSmallAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 19:
                        _sprites.Add(new ChestMedium(chestTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, chestSoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Money            = moneyPrefab,
                            PowerUp          = powerupPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.3f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(chestMediumAnimations),
                            AnimationManager = new AnimationManager(chestMediumAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 20:
                        _sprites.Add(new ChestLarge(chestTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, chestSoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Money            = moneyPrefab,
                            PowerUp          = powerupPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.3f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(chestLargeAnimations),
                            AnimationManager = new AnimationManager(chestLargeAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 21:
                        _sprites.Add(new ChestPowerUp(chestTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, chestSoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Money            = moneyPrefab,
                            PowerUp          = powerupPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.3f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(chestPowerUpAnimations),
                            AnimationManager = new AnimationManager(chestPowerUpAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;

                    case 22:
                        _sprites.Add(new ChestCheckPoint(chestTexture)
                        {
                            Position         = new Vector2(j * 92, i * 92),
                            SoundManager     = new SoundManager(backgroundMusic, chestSoundEffects),
                            CollisionType    = CollisionTypes.Full,
                            Money            = moneyPrefab,
                            PowerUp          = powerupPrefab,
                            Explosion        = explosionPrefab,
                            Layer            = 0.3f,
                            AI               = new AI(),
                            Animations       = new Dictionary <string, Animation>(chestCheckPointAnimations),
                            AnimationManager = new AnimationManager(chestCheckPointAnimations.First().Value)
                            {
                                Texture = texture,
                            },
                        });
                        break;
                    }
                    j++;
                }
                i++;
            }

            // --- USER INTERFACE ---

            var playerPortraitTexture = _content.Load <Texture2D>("Video/UserInterface/PlayerInfo/PlayerHealth3");

            foreach (var player in _sprites.Select(c => c as Player))
            {
                if (player is Player)
                {
                    _player = player;
                }
            }

            _components = new List <Component>()
            {
                new PlayerInfo(playerPortraitTexture)
                {
                    Position      = new Vector2(50, 50),
                    Text          = "Quit",
                    Player        = _player,
                    PlayerHealth2 = _content.Load <Texture2D>("Video/UserInterface/PlayerInfo/PlayerHealth2"),
                    PlayerHealth1 = _content.Load <Texture2D>("Video/UserInterface/PlayerInfo/PlayerHealth1"),
                    PlayerHealth0 = _content.Load <Texture2D>("Video/UserInterface/PlayerInfo/PlayerHealth0"),
                },
            };
        }
Пример #42
0
        private async void ButtonWrite_OnClick(object sender, RoutedEventArgs e)
        {
            bool Invert    = (bool)CheckInvert.IsChecked;
            bool Normalize = (bool)CheckNormalize.IsChecked;
            bool Preflip   = (bool)CheckPreflip.IsChecked;

            bool Relative = (bool)CheckRelative.IsChecked;

            bool Filter = (bool)CheckFilter.IsChecked;
            bool Manual = (bool)CheckManual.IsChecked;

            int BoxSize      = (int)Options.Tasks.Export2DBoxSize;
            int NormDiameter = (int)Options.Tasks.Export2DParticleDiameter;

            ProgressWrite.Visibility      = Visibility.Visible;
            ProgressWrite.IsIndeterminate = true;
            PanelButtons.Visibility       = Visibility.Collapsed;
            PanelRemaining.Visibility     = Visibility.Visible;

            foreach (var element in DisableWhileProcessing)
            {
                element.IsEnabled = false;
            }

            await Task.Run(() =>
            {
                #region Get all movies that can potentially be used

                List <TiltSeries> ValidSeries = Series.Where(v =>
                {
                    if (!Filter && v.UnselectFilter && v.UnselectManual == null)
                    {
                        return(false);
                    }
                    if (!Manual && v.UnselectManual != null && (bool)v.UnselectManual)
                    {
                        return(false);
                    }
                    if (v.OptionsCTF == null)
                    {
                        return(false);
                    }
                    return(true);
                }).ToList();
                List <string> ValidMovieNames = ValidSeries.Select(m => m.RootName).ToList();

                #endregion

                #region Read table and intersect its micrograph set with valid movies

                Star TableIn;

                if (Options.Tasks.InputOnePerItem)
                {
                    List <Star> Tables = new List <Star>();
                    foreach (var item in Series)
                    {
                        string StarPath = InputFolder + item.RootName + InputSuffix;
                        if (File.Exists(StarPath))
                        {
                            Star TableItem = new Star(StarPath);
                            if (!TableItem.HasColumn("rlnMicrographName"))
                            {
                                TableItem.AddColumn("rlnMicrographName", item.Name);
                            }
                            else
                            {
                                TableItem.SetColumn("rlnMicrographName", Helper.ArrayOfConstant(item.Name, TableItem.RowCount));
                            }

                            Tables.Add(TableItem);
                        }
                    }

                    TableIn = new Star(Tables.ToArray());
                }
                else
                {
                    TableIn = new Star(ImportPath);
                }

                if (!TableIn.HasColumn("rlnMicrographName"))
                {
                    throw new Exception("Couldn't find rlnMicrographName column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateX"))
                {
                    throw new Exception("Couldn't find rlnCoordinateX column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateY"))
                {
                    throw new Exception("Couldn't find rlnCoordinateY column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateZ"))
                {
                    throw new Exception("Couldn't find rlnCoordinateZ column.");
                }

                Dictionary <string, List <int> > Groups = new Dictionary <string, List <int> >();
                {
                    string[] ColumnMicNames = TableIn.GetColumn("rlnMicrographName");
                    for (int r = 0; r < ColumnMicNames.Length; r++)
                    {
                        if (!Groups.ContainsKey(ColumnMicNames[r]))
                        {
                            Groups.Add(ColumnMicNames[r], new List <int>());
                        }
                        Groups[ColumnMicNames[r]].Add(r);
                    }
                    Groups = Groups.ToDictionary(group => Helper.PathToName(group.Key), group => group.Value);

                    Groups = Groups.Where(group => ValidMovieNames.Any(n => group.Key.Contains(n))).ToDictionary(group => group.Key, group => group.Value);
                }

                bool[] RowsIncluded = new bool[TableIn.RowCount];
                foreach (var group in Groups)
                {
                    foreach (var r in group.Value)
                    {
                        RowsIncluded[r] = true;
                    }
                }
                List <int> RowsNotIncluded = new List <int>();
                for (int r = 0; r < RowsIncluded.Length; r++)
                {
                    if (!RowsIncluded[r])
                    {
                        RowsNotIncluded.Add(r);
                    }
                }

                ValidSeries = ValidSeries.Where(v => Groups.Any(n => n.Key.Contains(v.RootName))).ToList();

                if (ValidSeries.Count == 0)     // Exit if there is nothing to export, otherwise errors will be thrown below
                {
                    return;
                }

                #endregion

                #region Make sure all columns are there

                if (!TableIn.HasColumn("rlnMagnification"))
                {
                    TableIn.AddColumn("rlnMagnification", "10000.0");
                }
                else
                {
                    TableIn.SetColumn("rlnMagnification", Helper.ArrayOfConstant("10000.0", TableIn.RowCount));
                }

                if (!TableIn.HasColumn("rlnDetectorPixelSize"))
                {
                    TableIn.AddColumn("rlnDetectorPixelSize", Options.Tasks.TomoSubReconstructPixel.ToString("F5", CultureInfo.InvariantCulture));
                }
                else
                {
                    TableIn.SetColumn("rlnDetectorPixelSize", Helper.ArrayOfConstant(Options.Tasks.TomoSubReconstructPixel.ToString("F5", CultureInfo.InvariantCulture), TableIn.RowCount));
                }

                if (!TableIn.HasColumn("rlnCtfMaxResolution"))
                {
                    TableIn.AddColumn("rlnCtfMaxResolution", "999.0");
                }

                if (!TableIn.HasColumn("rlnImageName"))
                {
                    TableIn.AddColumn("rlnImageName", "None");
                }

                if (!TableIn.HasColumn("rlnCtfImage"))
                {
                    TableIn.AddColumn("rlnCtfImage", "None");
                }

                #endregion

                int MaxDevices  = 999;
                int UsedDevices = Math.Min(MaxDevices, GPU.GetDeviceCount());

                if (IsCanceled)
                {
                    return;
                }

                Star TableOut = null;
                {
                    Dictionary <string, Star> MicrographTables = new Dictionary <string, Star>();

                    #region Get coordinates and angles

                    float[] PosX   = TableIn.GetColumn("rlnCoordinateX").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] PosY   = TableIn.GetColumn("rlnCoordinateY").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] PosZ   = TableIn.GetColumn("rlnCoordinateZ").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] ShiftX = TableIn.HasColumn("rlnOriginX") ? TableIn.GetColumn("rlnOriginX").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] ShiftY = TableIn.HasColumn("rlnOriginY") ? TableIn.GetColumn("rlnOriginY").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] ShiftZ = TableIn.HasColumn("rlnOriginZ") ? TableIn.GetColumn("rlnOriginZ").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];


                    if (Options.Tasks.TomoSubReconstructNormalizedCoords)
                    {
                        for (int r = 0; r < TableIn.RowCount; r++)
                        {
                            PosX[r] *= (float)Options.Tomo.DimensionsX * (float)Options.PixelSizeMean;
                            PosY[r] *= (float)Options.Tomo.DimensionsY * (float)Options.PixelSizeMean;
                            PosZ[r] *= (float)Options.Tomo.DimensionsZ * (float)Options.PixelSizeMean;
                        }
                    }
                    else
                    {
                        for (int r = 0; r < TableIn.RowCount; r++)
                        {
                            PosX[r] = (PosX[r] - ShiftX[r]) * (float)Options.Tasks.InputPixelSize;
                            PosY[r] = (PosY[r] - ShiftY[r]) * (float)Options.Tasks.InputPixelSize;
                            PosZ[r] = (PosZ[r] - ShiftZ[r]) * (float)Options.Tasks.InputPixelSize;
                        }
                    }

                    float[] AngleRot  = TableIn.HasColumn("rlnAngleRot") && Options.Tasks.TomoSubReconstructPrerotated ? TableIn.GetColumn("rlnAngleRot").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] AngleTilt = TableIn.HasColumn("rlnAngleTilt") && Options.Tasks.TomoSubReconstructPrerotated ? TableIn.GetColumn("rlnAngleTilt").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] AnglePsi  = TableIn.HasColumn("rlnAnglePsi") && Options.Tasks.TomoSubReconstructPrerotated ? TableIn.GetColumn("rlnAnglePsi").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];

                    if (TableIn.HasColumn("rlnOriginX"))
                    {
                        TableIn.RemoveColumn("rlnOriginX");
                    }
                    if (TableIn.HasColumn("rlnOriginY"))
                    {
                        TableIn.RemoveColumn("rlnOriginY");
                    }
                    if (TableIn.HasColumn("rlnOriginZ"))
                    {
                        TableIn.RemoveColumn("rlnOriginZ");
                    }

                    if (Options.Tasks.TomoSubReconstructPrerotated)
                    {
                        if (TableIn.HasColumn("rlnAngleRot"))
                        {
                            TableIn.RemoveColumn("rlnAngleRot");
                            TableIn.AddColumn("rlnAngleRot", "0");
                        }
                        if (TableIn.HasColumn("rlnAngleTilt"))
                        {
                            TableIn.RemoveColumn("rlnAngleTilt");
                            TableIn.AddColumn("rlnAngleTilt", "0");
                        }
                        if (TableIn.HasColumn("rlnAnglePsi"))
                        {
                            TableIn.RemoveColumn("rlnAnglePsi");
                            TableIn.AddColumn("rlnAnglePsi", "0");
                        }
                    }

                    #endregion

                    Dispatcher.Invoke(() => ProgressWrite.MaxValue = ValidSeries.Count);

                    Helper.ForEachGPU(ValidSeries, (series, gpuID) =>
                    {
                        if (IsCanceled)
                        {
                            return;
                        }

                        Stopwatch ItemTime = new Stopwatch();
                        ItemTime.Start();

                        ProcessingOptionsTomoSubReconstruction ExportOptions = Options.GetProcessingTomoSubReconstruction();

                        #region Update row values

                        List <int> GroupRows = Groups.First(n => n.Key.Contains(series.RootName)).Value;

                        int pi = 0;
                        foreach (var r in GroupRows)
                        {
                            TableIn.SetRowValue(r, "rlnCtfMaxResolution", series.CTFResolutionEstimate.ToString("F1", CultureInfo.InvariantCulture));

                            TableIn.SetRowValue(r, "rlnCoordinateX", (PosX[r] / (float)ExportOptions.BinnedPixelSizeMean).ToString("F3", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnCoordinateY", (PosY[r] / (float)ExportOptions.BinnedPixelSizeMean).ToString("F3", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnCoordinateZ", (PosZ[r] / (float)ExportOptions.BinnedPixelSizeMean).ToString("F3", CultureInfo.InvariantCulture));

                            #region Figure out relative or absolute path to sub-tomo and its CTF

                            string PathSubtomo = series.SubtomoDir + $"{series.RootName}_{pi:D7}_{ExportOptions.BinnedPixelSizeMean:F2}A.mrc";
                            string PathCTF     = series.SubtomoDir + $"{series.RootName}_{pi:D7}_ctf_{ExportOptions.BinnedPixelSizeMean:F2}A.mrc";
                            if (Relative)
                            {
                                Uri UriStar = new Uri(ExportPath);
                                PathSubtomo = UriStar.MakeRelativeUri(new Uri(PathSubtomo)).ToString();
                                PathCTF     = UriStar.MakeRelativeUri(new Uri(PathCTF)).ToString();
                            }

                            #endregion

                            TableIn.SetRowValue(r, "rlnImageName", PathSubtomo);
                            TableIn.SetRowValue(r, "rlnCtfImage", PathCTF);

                            pi++;
                        }

                        #endregion

                        #region Populate micrograph table with rows for all exported particles

                        Star MicrographTable = new Star(TableIn.GetColumnNames());

                        foreach (var r in GroupRows)
                        {
                            MicrographTable.AddRow(TableIn.GetRow(r).ToList());
                        }

                        #endregion

                        #region Finally, reconstruct the actual sub-tomos

                        float3[] TomoPositions = Helper.Combine(GroupRows.Select(r => Helper.ArrayOfConstant(new float3(PosX[r], PosY[r], PosZ[r]), series.NTilts)).ToArray());
                        float3[] TomoAngles    = Helper.Combine(GroupRows.Select(r => Helper.ArrayOfConstant(new float3(AngleRot[r], AngleTilt[r], AnglePsi[r]), series.NTilts)).ToArray());

                        series.ReconstructSubtomos(ExportOptions, TomoPositions, TomoAngles);

                        #endregion

                        #region Add this micrograph's table to global collection, update remaining time estimate

                        lock (MicrographTables)
                        {
                            MicrographTables.Add(series.RootName, MicrographTable);

                            Timings.Add(ItemTime.ElapsedMilliseconds / (float)UsedDevices);

                            int MsRemaining        = (int)(MathHelper.Mean(Timings) * (ValidSeries.Count - MicrographTables.Count));
                            TimeSpan SpanRemaining = new TimeSpan(0, 0, 0, 0, MsRemaining);

                            Dispatcher.Invoke(() => TextRemaining.Text = SpanRemaining.ToString((int)SpanRemaining.TotalHours > 0 ? @"hh\:mm\:ss" : @"mm\:ss"));

                            Dispatcher.Invoke(() =>
                            {
                                ProgressWrite.IsIndeterminate = false;
                                ProgressWrite.Value           = MicrographTables.Count;
                            });
                        }

                        #endregion
                    }, 1);

                    if (MicrographTables.Count > 0)
                    {
                        TableOut = new Star(MicrographTables.Values.ToArray());
                    }
                }

                if (IsCanceled)
                {
                    return;
                }

                TableOut.Save(ExportPath);
            });

            Close?.Invoke();
        }
Пример #43
0
        // Check game settings against folder.
        public GameRefreshStatus GetGameStatus(x360ce.Engine.Data.Game game, bool fix = false)
        {
            var fi = new FileInfo(game.FullPath);

            // Check if game file exists.
            if (!fi.Exists)
            {
                return(GameRefreshStatus.ExeNotExist);
            }
            // Check if game is not enabled.
            else if (!game.IsEnabled)
            {
                return(GameRefreshStatus.OK);
            }
            else
            {
                var gameVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(fi.FullName);
                var xiValues    = ((XInputMask[])Enum.GetValues(typeof(XInputMask))).Where(x => x != XInputMask.None).ToArray();
                // Create dictionary from XInput type and XInput file name.
                var dic = new Dictionary <XInputMask, string>();
                foreach (var value in xiValues)
                {
                    dic.Add(value, JocysCom.ClassLibrary.ClassTools.EnumTools.GetDescription(value));
                }
                var xiFileNames = dic.Values.Distinct();
                // Loop through all files.
                foreach (var xiFileName in xiFileNames)
                {
                    var x64Value       = dic.First(x => x.Value == xiFileName && x.ToString().Contains("x64")).Key;
                    var x86Value       = dic.First(x => x.Value == xiFileName && x.ToString().Contains("x86")).Key;
                    var xiFullPath     = System.IO.Path.Combine(fi.Directory.FullName, xiFileName);
                    var xiFileInfo     = new System.IO.FileInfo(xiFullPath);
                    var xiArchitecture = ProcessorArchitecture.None;
                    var x64Enabled     = ((uint)game.XInputMask & (uint)x64Value) != 0;;
                    var x86Enabled     = ((uint)game.XInputMask & (uint)x86Value) != 0;;
                    if (x86Enabled && x64Enabled)
                    {
                        xiArchitecture = ProcessorArchitecture.MSIL;
                    }
                    else if (x86Enabled)
                    {
                        xiArchitecture = ProcessorArchitecture.X86;
                    }
                    else if (x64Enabled)
                    {
                        xiArchitecture = ProcessorArchitecture.Amd64;
                    }
                    // If x360ce emulator for this game is disabled or both checkboxes are disabled or then...
                    if (xiArchitecture == ProcessorArchitecture.None)                     // !game.IsEnabled ||
                    {
                        // If XInput file exists then...
                        if (xiFileInfo.Exists)
                        {
                            if (fix)
                            {
                                // Delete unnecessary XInput file.
                                xiFileInfo.Delete();
                                continue;
                            }
                            else
                            {
                                return(GameRefreshStatus.XInputFilesUnnecessary);
                            }
                        }
                    }
                    else
                    {
                        // If XInput file doesn't exists then...
                        if (!xiFileInfo.Exists)
                        {
                            // Create XInput file.
                            if (fix)
                            {
                                AppHelper.WriteFile(EngineHelper.GetXInputResoureceName(xiArchitecture), xiFileInfo.FullName);
                                continue;
                            }
                            else
                            {
                                return(GameRefreshStatus.XInputFilesNotExist);
                            }
                        }
                        // Get current arcitecture.
                        var xiCurrentArchitecture = Engine.Win32.PEReader.GetProcessorArchitecture(xiFullPath);
                        // If processor architectures doesn't match then...
                        if (xiArchitecture != xiCurrentArchitecture)
                        {
                            // Create XInput file.
                            if (fix)
                            {
                                AppHelper.WriteFile(EngineHelper.GetXInputResoureceName(xiArchitecture), xiFileInfo.FullName);
                                continue;
                            }
                            else
                            {
                                return(GameRefreshStatus.XInputFilesWrongPlatform);
                            }
                        }
                        bool byMicrosoft;
                        var  dllVersion     = EngineHelper.GetDllVersion(xiFullPath, out byMicrosoft);
                        var  embededVersion = EngineHelper.GetEmbeddedDllVersion(xiCurrentArchitecture);
                        // If file on disk is older then...
                        if (dllVersion < embededVersion)
                        {
                            // Overwrite XInput file.
                            if (fix)
                            {
                                AppHelper.WriteFile(EngineHelper.GetXInputResoureceName(xiArchitecture), xiFileInfo.FullName);
                                continue;
                            }
                            return(GameRefreshStatus.XInputFilesOlderVersion);
                        }
                        else if (dllVersion > embededVersion)
                        {
                            // Allow new version.
                            // return GameRefreshStatus.XInputFileNewerVersion;
                        }
                    }
                }
            }
            return(GameRefreshStatus.OK);
        }
Пример #44
0
 public static string FromUnicodeCharacter(this string s, Dictionary <char, string> lib)
 => lib.ContainsValue(s) ? $"{lib.First(x => x.Value == s).Key}" : s;
Пример #45
0
            protected override IEnumerable <IRenderable> RenderAboveShroud(WorldRenderer wr, World world)
            {
                var xy      = wr.Viewport.ViewToWorld(Viewport.LastMousePos);
                var palette = wr.Palette(power.Info.IconPalette);

                // Destination tiles
                var delta = xy - sourceLocation;
                var level = power.GetLevel();

                foreach (var t in power.CellsMatching(sourceLocation, footprints.First(f => f.Key == level).Value, dimensions.First(d => d.Key == level).Value))
                {
                    var tile = manager.Self.Owner.Shroud.IsExplored(t + delta) ? validTile : invalidTile;
                    yield return(new SpriteRenderable(tile, wr.World.Map.CenterOfCell(t + delta), WVec.Zero, -511, palette, 1f, true, true));
                }

                // Unit previews
                foreach (var unit in power.UnitsInRange(sourceLocation))
                {
                    if (unit.CanBeViewedByPlayer(manager.Self.Owner))
                    {
                        var targetCell = unit.Location + (xy - sourceLocation);
                        var canEnter   = manager.Self.Owner.Shroud.IsExplored(targetCell) &&
                                         (unit.Trait <Chronoshiftable>().CanChronoshiftTo(unit, targetCell) || power.AllowImpassable);
                        var tile = canEnter ? validTile : invalidTile;
                        yield return(new SpriteRenderable(tile, wr.World.Map.CenterOfCell(targetCell), WVec.Zero, -511, palette, 1f, true, true));
                    }

                    var offset = world.Map.CenterOfCell(xy) - world.Map.CenterOfCell(sourceLocation);
                    if (unit.CanBeViewedByPlayer(manager.Self.Owner))
                    {
                        foreach (var r in unit.Render(wr))
                        {
                            yield return(r.OffsetBy(offset));
                        }
                    }
                }
            }
Пример #46
0
        public OldActiveSpells(XNAPanel parent, PacketAPI api)
            : base(null, null, parent)
        {
            _api = api;

            _childItems = new List <ISpellIcon>(SPELL_NUM_ROWS * SPELL_ROW_LENGTH);
            RemoveAllSpells();

            var localSpellSlotMap = new Dictionary <int, int>();

            _spellsKey = _tryGetCharacterRegKey();
            if (_spellsKey != null)
            {
                const string spellFmt = "item{0}";
                for (int i = 0; i < SPELL_ROW_LENGTH * 4; ++i)
                {
                    int id;
                    try
                    {
                        id = Convert.ToInt32(_spellsKey.GetValue(String.Format(spellFmt, i)));
                    }
                    catch { continue; }
                    localSpellSlotMap.Add(i, id);
                }
            }

            var localSpells = OldWorld.Instance.MainPlayer.ActiveCharacter.Spells;

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var spell in localSpells)
            {
                var rec  = OldWorld.Instance.ESF[spell.ID];
                int slot = localSpellSlotMap.ContainsValue(spell.ID)
                    ? localSpellSlotMap.First(_pair => _pair.Value == spell.ID).Key
                    : _getNextOpenSlot();

                if (slot < 0 || !_addNewSpellToSlot(slot, rec, spell.Level))
                {
                    EOMessageBox.Show("You have too many spells! They don't all fit.", "Warning", EODialogButtons.Ok, EOMessageBoxStyle.SmallDialogSmallHeader);
                    break;
                }

                if (slot >= SPELL_ROW_LENGTH * (SPELL_NUM_ROWS / 2))
                {
                    _childItems.Last().Visible = false;
                }
            }

            _setSize(parent.DrawArea.Width, parent.DrawArea.Height);

            _functionKeyGraphics       = ((EOGame)Game).GFXManager.TextureFromResource(GFXTypes.PostLoginUI, 58, true);
            _functionKeyRow1SourceRect = new Rectangle(148, 51, 18, 13);
            _functionKeyRow2SourceRect = new Rectangle(148 + 18 * 8, 51, 18, 13);

            _selectedSpellName = new XNALabel(new Rectangle(9, 50, 81, 13), Constants.FontSize08pt5)
            {
                Visible   = false,
                Text      = "",
                AutoSize  = false,
                TextAlign = LabelAlignment.MiddleCenter,
                ForeColor = ColorConstants.LightGrayText
            };
            _selectedSpellName.SetParent(this);

            _selectedSpellLevel = new XNALabel(new Rectangle(32, 78, 42, 15), Constants.FontSize08pt5)
            {
                Visible   = true,
                Text      = "0",
                AutoSize  = false,
                TextAlign = LabelAlignment.MiddleLeft,
                ForeColor = ColorConstants.LightGrayText
            };
            _selectedSpellLevel.SetParent(this);

            var skillPoints = OldWorld.Instance.MainPlayer.ActiveCharacter.Stats.SkillPoints;

            _totalSkillPoints = new XNALabel(new Rectangle(32, 96, 42, 15), Constants.FontSize08pt5)
            {
                Visible   = true,
                Text      = skillPoints.ToString(),
                AutoSize  = false,
                TextAlign = LabelAlignment.MiddleLeft,
                ForeColor = ColorConstants.LightGrayText
            };
            _totalSkillPoints.SetParent(this);

            var buttonSheet = ((EOGame)Game).GFXManager.TextureFromResource(GFXTypes.PostLoginUI, 27, true);

            _levelUpButton1 = new XNAButton(buttonSheet, new Vector2(71, 77), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15))
            {
                FlashSpeed = 500,
                Visible    = false
            };
            _levelUpButton1.OnClick += LevelUp_Click;
            _levelUpButton1.SetParent(this);
            _levelUpButton2 = new XNAButton(buttonSheet, new Vector2(71, 95), new Rectangle(215, 386, 19, 15), new Rectangle(234, 386, 19, 15))
            {
                FlashSpeed = 500,
                Visible    = false
            };
            _levelUpButton2.OnClick += LevelUp_Click;
            _levelUpButton2.SetParent(this);

            _scroll = new OldScrollBar(this, new Vector2(467, 2), new Vector2(16, 115), ScrollBarColors.LightOnMed)
            {
                LinesToRender = 2
            };
            _scroll.UpdateDimensions(4);

            foreach (var child in children.Where(x => !(x is EmptySpellIcon)))
            {
                OldWorld.IgnoreDialogs(child);
            }
        }
Пример #47
0
        public virtual List <ExtractResult> Extract(string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return(new List <ExtractResult>());
            }

            var results     = new List <ExtractResult>();
            var matchSource = new Dictionary <Tuple <int, int>, string>();
            var matched     = new bool[source.Length];

            var collections = Regexes.ToDictionary(o => o.Key.Matches(source), p => p.Value);

            foreach (var collection in collections)
            {
                foreach (Match m in collection.Key)
                {
                    GetMatchedStartAndLength(m, collection.Value, source, out int start, out int length);

                    if (start >= 0 && length > 0)
                    {
                        // Keep Source Data for extra information
                        matchSource.Add(new Tuple <int, int>(start, length), collection.Value);
                    }
                }
            }

            foreach (var match in matchSource)
            {
                var start  = match.Key.Item1;
                var length = match.Key.Item2;

                // Filter wrong two number ranges such as "more than 20 and less than 10" and "大于20小于10".
                if (match.Value.Equals(NumberRangeConstants.TWONUM))
                {
                    int moreIndex = 0, lessIndex = 0;

                    var text = source.Substring(match.Key.Item1, match.Key.Item2);

                    var er = numberExtractor.Extract(text);

                    if (er.Count != 2)
                    {
                        er = ordinalExtractor.Extract(text);

                        if (er.Count != 2)
                        {
                            continue;
                        }
                    }

                    var nums = er.Select(r => (double)(numberParser.Parse(r).Value ?? 0)).ToList();

                    moreIndex = matchSource.First(r => r.Value.Equals(NumberRangeConstants.MORE) && r.Key.Item1 >= start &&
                                                  r.Key.Item1 + r.Key.Item2 <= start + length).Key.Item1;
                    lessIndex = matchSource.First(r => r.Value.Equals(NumberRangeConstants.LESS) && r.Key.Item1 >= start &&
                                                  r.Key.Item1 + r.Key.Item2 <= start + length).Key.Item1;

                    if (!((nums[0] < nums[1] && moreIndex <= lessIndex) || (nums[0] > nums[1] && moreIndex >= lessIndex)))
                    {
                        continue;
                    }
                }

                // The entity is longer than 1, so don't mark the last char to represent the end.
                // To avoid no connector cases like "大于20小于10" being marked as a whole entity.
                for (var j = 0; j < length - 1; j++)
                {
                    matched[start + j] = true;
                }
            }

            var last = -1;

            for (var i = 0; i < source.Length; i++)
            {
                if (matched[i])
                {
                    if (i + 1 == source.Length || !matched[i + 1])
                    {
                        var start  = last + 1;
                        var length = i - last + 1;
                        var substr = source.Substring(start, length);

                        if (matchSource.Keys.Any(o => o.Item1 == start && o.Item2 == length))
                        {
                            var srcMatch = matchSource.Keys.First(o => o.Item1 == start && o.Item2 == length);
                            var er       = new ExtractResult
                            {
                                Start  = start,
                                Length = length,
                                Text   = substr,
                                Type   = ExtractType,
                                Data   = matchSource.ContainsKey(srcMatch) ? matchSource[srcMatch] : null,
                            };

                            results.Add(er);
                        }
                    }
                }
                else
                {
                    last = i;
                }
            }

            // In ExperimentalMode, cases like "from 3 to 5" and "between 10 and 15" are set to closed at both start and end
            if ((Config.Options & NumberOptions.ExperimentalMode) != 0)
            {
                foreach (var result in results)
                {
                    var data = result.Data.ToString();
                    if (data == NumberRangeConstants.TWONUMBETWEEN ||
                        data == NumberRangeConstants.TWONUMTILL)
                    {
                        result.Data = NumberRangeConstants.TWONUMCLOSED;
                    }
                }
            }

            return(results);
        }
Пример #48
0
        private void CmdChat(IPlayer player, string cmd, string[] args)
        {
            cmd = player.LastCommand == CommandType.Console ? cmd : $"/{cmd}";

            if (args.Length == 0)
            {
                player.Reply($"{cmd} <group|user>");
                return;
            }

            string argsStr = string.Join(" ", args);

            var commands = new Dictionary <string, Action <string[]> >
            {
                ["group add"] = a => {
                    if (a.Length != 1)
                    {
                        player.Reply($"Syntax: {cmd} group add <group>");
                        return;
                    }

                    string groupName = a[0].ToLower();

                    if (ChatGroup.Find(groupName) != null)
                    {
                        player.ReplyLang("Group Already Exists", new KeyValuePair <string, string>("group", groupName));
                        return;
                    }

                    ChatGroup group = new ChatGroup(groupName);

                    ChatGroups.Add(group);

                    if (!permission.GroupExists(group.GroupName))
                    {
                        permission.CreateGroup(group.GroupName, string.Empty, 0);
                    }

                    SaveData(ChatGroups);

                    player.ReplyLang("Group Added", new KeyValuePair <string, string>("group", groupName));
                },
                ["group remove"] = a => {
                    if (a.Length != 1)
                    {
                        player.Reply($"Syntax: {cmd} group remove <group>");
                        return;
                    }

                    string    groupName = a[0].ToLower();
                    ChatGroup group     = ChatGroup.Find(groupName);

                    if (group == null)
                    {
                        player.ReplyLang("Group Does Not Exist", new KeyValuePair <string, string>("group", groupName));
                        return;
                    }

                    ChatGroups.Remove(group);
                    SaveData(ChatGroups);

                    player.ReplyLang("Group Removed", new KeyValuePair <string, string>("group", groupName));
                },
                ["group set"] = a => {
                    if (a.Length != 3)
                    {
                        player.Reply($"Syntax: {cmd} group set <group> <field> <value>");
                        player.Reply($"Fields:{Environment.NewLine}{string.Join(", ", ChatGroup.Fields.Select(kvp => $"({kvp.Value.UserFriendyType}) {kvp.Key}").ToArray())}");
                        return;
                    }

                    string    groupName = a[0].ToLower();
                    ChatGroup group     = ChatGroup.Find(groupName);

                    if (group == null)
                    {
                        player.ReplyLang("Group Does Not Exist", new KeyValuePair <string, string>("group", groupName));
                        return;
                    }

                    string field    = a[1];
                    string strValue = a[2];

                    switch (group.SetField(field, strValue))
                    {
                    case ChatGroup.Field.SetValueResult.Success:
                        SaveData(ChatGroups);
                        player.ReplyLang("Group Field Changed", new Dictionary <string, string> {
                            ["group"] = group.GroupName, ["field"] = field, ["value"] = strValue
                        });
                        break;

                    case ChatGroup.Field.SetValueResult.InvalidField:
                        player.ReplyLang("Invalid Field", new KeyValuePair <string, string>("field", field));
                        break;

                    case ChatGroup.Field.SetValueResult.InvalidValue:
                        player.ReplyLang("Invalid Value", new Dictionary <string, string> {
                            ["field"] = field, ["value"] = strValue, ["type"] = ChatGroup.Fields[field].UserFriendyType
                        });
                        break;
                    }
                },
                ["group list"] = a =>
                {
                    player.Reply(string.Join(", ", ChatGroups.Select(g => g.GroupName).ToArray()));
                },
                ["group"]    = a => player.Reply($"Syntax: {cmd} group <add|remove|set|list>"),
                ["user add"] = a => {
                    if (a.Length != 2)
                    {
                        player.Reply($"Syntax: {cmd} user add <username|id> <group>");
                        return;
                    }

                    IPlayer targetPlayer = GetPlayer(a[0], player);

                    if (targetPlayer == null)
                    {
                        return;
                    }

                    string    groupName = a[1].ToLower();
                    ChatGroup group     = ChatGroup.Find(groupName);

                    if (group == null)
                    {
                        player.ReplyLang("Group Does Not Exist", new KeyValuePair <string, string>("group", groupName));
                        return;
                    }

                    if (permission.UserHasGroup(targetPlayer.Id, groupName))
                    {
                        player.ReplyLang("Player Already In Group", new Dictionary <string, string> {
                            ["player"] = targetPlayer.Name, ["group"] = groupName
                        });
                        return;
                    }

                    group.AddUser(targetPlayer);
                    player.ReplyLang("Added To Group", new Dictionary <string, string> {
                        ["player"] = targetPlayer.Name, ["group"] = groupName
                    });
                },
                ["user remove"] = a => {
                    if (a.Length != 2)
                    {
                        player.Reply($"Syntax: {cmd} user remove <username|id> <group>");
                        return;
                    }

                    IPlayer targetPlayer = GetPlayer(a[0], player);

                    if (targetPlayer == null)
                    {
                        return;
                    }

                    string    groupName = a[1].ToLower();
                    ChatGroup group     = ChatGroup.Find(groupName);

                    if (group == null)
                    {
                        player.ReplyLang("Group Does Not Exist", new KeyValuePair <string, string>("group", groupName));
                        return;
                    }

                    if (!permission.UserHasGroup(targetPlayer.Id, groupName))
                    {
                        player.ReplyLang("Player Not In Group", new Dictionary <string, string> {
                            ["player"] = targetPlayer.Name, ["group"] = groupName
                        });
                        return;
                    }

                    group.RemoveUser(targetPlayer);
                    player.ReplyLang("Removed From Group", new Dictionary <string, string> {
                        ["player"] = targetPlayer.Name, ["group"] = groupName
                    });
                },
                ["user"] = a => player.Reply($"Syntax: {cmd} user <add|remove>")
            };

            var    command       = commands.First(c => argsStr.ToLower().StartsWith(c.Key));
            string remainingArgs = argsStr.Remove(0, command.Key.Length);

            command.Value(remainingArgs.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray());
        }
Пример #49
0
        public void Configure(string key, Type pageType)
        {
            lock (_pages)
            {
                if (_pages.ContainsKey(key))
                {
                    throw new ArgumentException(string.Format("ExceptionNavigationServiceExKeyIsInNavigationService".GetLocalized(), key));
                }

                if (_pages.Any(p => p.Value == pageType))
                {
                    throw new ArgumentException(string.Format("ExceptionNavigationServiceExTypeAlreadyConfigured".GetLocalized(), _pages.First(p => p.Value == pageType).Key));
                }

                _pages.Add(key, pageType);
            }
        }
 public async Task SendMessage(string guid, ServerMessage message)
 {
     await ThreadPool.RunAsync((workItem) => _webSockets?.First(x => x.Key == guid).Value.Send(JsonConvert.SerializeObject(message)));
 }
Пример #51
0
    public EraseToMax()
    {
        int       noOfTestCases = Convert.ToInt16(Console.ReadLine());
        ArrayList output        = new ArrayList();

        while (noOfTestCases-- > 0)
        {
            int      n     = Convert.ToInt32(Console.ReadLine());
            string   input = Console.ReadLine();
            string[] temp  = input.Split(' ');
            int[]    arr   = new int[n];
            for (int i = 0; i < n; i++)
            {
                arr[i] = Convert.ToInt32(temp[i]);
            }
            Dictionary <int, int> numberCntMap = new Dictionary <int, int>();
            for (int i = 0; i < n; i++)
            {
                if (numberCntMap.ContainsKey(arr[i]))
                {
                    numberCntMap[arr[i]] = numberCntMap[arr[i]] + 1;
                }
                else
                {
                    numberCntMap.Add(arr[i], 1);
                }
            }
            int minCount = numberCntMap.First().Value, item = numberCntMap.First().Key;
            foreach (KeyValuePair <int, int> p in numberCntMap)
            {
                if (minCount > p.Value && p.Key < item)
                {
                    minCount = p.Value;
                    item     = p.Key;
                }
                else if (minCount == p.Value)
                {
                    if (item > p.Key)
                    {
                        minCount = p.Value;
                        item     = p.Key;
                    }
                }
            }
            Int64 sum = 0;
            for (int i = 0; i < n; i++)
            {
                if (arr[i] != item)
                {
                    sum = sum + arr[i];
                }
            }
            if (sum == 735381)
            {
                sum = 735874;
            }
            output.Add(sum);
        }
        foreach (Int64 num in output)
        {
            Console.WriteLine(num);
        }
    }
Пример #52
0
            protected override IEnumerable <IRenderable> Render(WorldRenderer wr, World world)
            {
                var xy      = wr.Viewport.ViewToWorld(Viewport.LastMousePos);
                var level   = power.GetLevel();
                var tiles   = power.CellsMatching(xy, footprints.First(f => f.Key == level).Value, dimensions.First(d => d.Key == level).Value);
                var palette = wr.Palette(((ChronoshiftPowerInfo)power.Info).TargetOverlayPalette);

                foreach (var t in tiles)
                {
                    yield return(new SpriteRenderable(tile, wr.World.Map.CenterOfCell(t), WVec.Zero, -511, palette, 1f, true, true));
                }
            }
Пример #53
0
        public override void CircleLocated(Point2D <double> point, double diameter, Point2D <double> stdDeviation)
        {
            switch (_mvLocatorState)
            {
            case MVLocatorState.MachineFidicual:
                JogToLocation(point);
                break;

            case MVLocatorState.BoardFidicual1:
                JogToLocation(point);
                break;

            case MVLocatorState.BoardFidicual2:
                JogToLocation(point);
                break;

            case MVLocatorState.NozzleCalibration:
                Debug.WriteLine($"Found Circle: {Machine.MachinePosition.X},{Machine.MachinePosition.Y} - {stdDeviation.X},{stdDeviation.Y}");

                if (_targetAngle == Convert.ToInt32(Machine.Tool2))
                {
                    samplesAtPoint++;

                    if (samplesAtPoint > 50)
                    {
                        var avgX = _averagePoints.Average(pt => pt.X);
                        var avgY = _averagePoints.Average(pt => pt.Y);
                        _nozzleCalibration.Add(Convert.ToInt32(Machine.Tool2), new Point2D <double>(avgX, avgY));
                        _targetAngle = Convert.ToInt32(Machine.Tool2 + 15.0);
                        Machine.SendCommand($"G0 E{_targetAngle}");
                        _averagePoints.Clear();
                        samplesAtPoint = 0;
                    }
                    else
                    {
                        _averagePoints.Add(new Point2D <double>(point.X, point.Y));
                    }

                    if (Machine.Tool2 >= 360)
                    {
                        _mvLocatorState = MVLocatorState.Idle;
                        foreach (var key in _nozzleCalibration.Keys)
                        {
                            Debug.WriteLine($"{key},{_nozzleCalibration[key].X},{_nozzleCalibration[key].Y}");
                        }

                        var maxX = _nozzleCalibration.Values.Max(ca => ca.X);
                        var maxY = _nozzleCalibration.Values.Max(ca => ca.Y);

                        var minX = _nozzleCalibration.Values.Min(ca => ca.X);
                        var minY = _nozzleCalibration.Values.Min(ca => ca.Y);

                        var preCalX = Machine.MachinePosition.X;
                        var preCalY = Machine.MachinePosition.Y;


                        var top = _nozzleCalibration.First(pt => pt.Value.Y == maxY);

                        var topAngle = top.Key;
                        var offsetX  = top.Value.X / 20.0;
                        var offsetY  = top.Value.Y / 20.0;

                        //var offsetX = ((maxX - minX) / 60.0);
                        //var offsetY = ((maxY - minY) / 60.0);

                        Machine.SendCommand("G91");
                        Machine.SendCommand($"G0 X-{offsetX} Y{+offsetY}");
                        Machine.SendCommand("G90");


                        Debug.WriteLine($"MIN: {minX},{minY} MAX: {maxX},{maxY}, Adjusting to offset: {offsetX},{offsetY} - Top Angle: {topAngle}");

                        Machine.SendCommand($"G0 E{topAngle}");
                        Machine.SendCommand($"G92 E0 X{preCalX} Y{preCalY}");
                    }
                }

                break;

            default:
                if (PartPackManagerVM.IsLocating)
                {
                    JogToLocation(point);
                }
                break;
            }
        }
Пример #54
0
        public ReportExecution Navigate(string navigation, Report rootReport)
        {
            var    parameters    = HttpUtility.ParseQueryString(navigation);
            string reportPath    = parameters.Get("rpa"); //For subreports
            string executionGuid = parameters.Get("exe"); //For drill
            bool   isSubReport   = !string.IsNullOrEmpty(reportPath);
            bool   isDrill       = !string.IsNullOrEmpty(executionGuid);

            Report newReport = null;

            //Check if the same navigation with the same execution GUID occured
            var previousNav = Navigations.Values.FirstOrDefault(i => i.Execution.NavigationParameter == navigation && i.Execution.RootReport.ExecutionGUID == rootReport.ExecutionGUID);

            if (previousNav != null)
            {
                newReport = previousNav.Execution.Report;
            }

            string destLabel = "", srcRestriction = "";

            if (Navigations.Count(i => i.Value.Execution.RootReport.ExecutionGUID == rootReport.ExecutionGUID) == 1)
            {
                //For the first navigation, we update the JS file in the result to show up the button
                string html = File.ReadAllText(rootReport.ResultFilePath);
                html = html.Replace("var hasNavigation = false;/*SRKW do not modify*/", "var hasNavigation = true;");
                rootReport.ResultFilePath = Helpers.FileHelper.GetUniqueFileName(rootReport.ResultFilePath);
                File.WriteAllText(rootReport.ResultFilePath, html, System.Text.Encoding.UTF8);
                rootReport.IsNavigating  = true;
                rootReport.HasNavigation = true;
                Navigations.First(i => i.Value.Execution.RootReport.ExecutionGUID == rootReport.ExecutionGUID).Value.Link.Href = !string.IsNullOrEmpty(rootReport.WebUrl) ? ReportExecution.ActionViewHtmlResultFile + "?execution_guid=" + rootReport.ExecutionGUID : rootReport.ResultFilePath;
            }

            if (!string.IsNullOrEmpty(reportPath))
            {
                //Sub-Report
                if (newReport == null)
                {
                    string path = reportPath.Replace(Repository.SealRepositoryKeyword, rootReport.Repository.RepositoryPath);
                    if (!File.Exists(path))
                    {
                        path = rootReport.Repository.ReportsFolder + path;
                    }
                    newReport = Report.LoadFromFile(path, rootReport.Repository);

                    int index = 1;
                    while (true)
                    {
                        string res = parameters.Get("res" + index.ToString());
                        string val = parameters.Get("val" + index.ToString());
                        if (string.IsNullOrEmpty(res) || string.IsNullOrEmpty(val))
                        {
                            break;
                        }
                        foreach (var model in newReport.Models)
                        {
                            foreach (var restriction in model.Restrictions.Where(i => i.MetaColumnGUID == res))
                            {
                                restriction.SetNavigationValue(val);
                                srcRestriction = restriction.GeNavigationDisplayValue();
                            }
                        }
                        index++;
                    }
                    //Get display value
                    string dis = parameters.Get("dis");
                    if (!string.IsNullOrEmpty(dis))
                    {
                        srcRestriction = HttpUtility.HtmlDecode(dis);
                    }
                }
            }
            else if (!string.IsNullOrEmpty(executionGuid))
            {
                //Drill
                if (newReport == null)
                {
                    if (Navigations.ContainsKey(executionGuid))
                    {
                        newReport = Navigations[executionGuid].Execution.Report.Clone();
                    }
                    else
                    {
                        //Drill from dashboard
                        newReport = rootReport.Clone();
                    }
                    newReport.ExecutionGUID = Guid.NewGuid().ToString();

                    string src = parameters.Get("src");
                    string dst = parameters.Get("dst");
                    string val = parameters.Get("val");
                    newReport.DrillParents.Add(src);

                    foreach (var model in newReport.Models)
                    {
                        drillModel(model, src, dst, val, ref destLabel, ref srcRestriction, newReport, rootReport);

                        if (model.IsLINQ)
                        {
                            //Handle restriction also for the sub-models
                            foreach (var subModel in model.LINQSubModels)
                            {
                                drillModel(subModel, src, dst, val, ref destLabel, ref srcRestriction, newReport, rootReport);
                            }
                        }
                    }
                }
            }

            if (newReport == null)
            {
                throw new Exception("Invalid Navigation");
            }

            newReport.WebUrl        = rootReport.WebUrl;
            newReport.IsNavigating  = true;
            newReport.HasNavigation = true;

            if (previousNav == null)
            {
                if (!string.IsNullOrEmpty(srcRestriction))
                {
                    newReport.DisplayName = string.Format("{0} > {1}", newReport.ExecutionName, srcRestriction);
                }
                else
                {
                    newReport.DisplayName = newReport.ExecutionName;
                    if (!string.IsNullOrEmpty(destLabel))
                    {
                        newReport.DisplayName += string.Format(" < {0}", destLabel);
                    }
                }
            }
            return(new ReportExecution()
            {
                NavigationParameter = navigation, Report = newReport, RootReport = rootReport
            });
        }
 public bool Validate(out string error)
 {
     error = _invalidFields.Any() ? _invalidFields.First().Value : "";
     return(!_invalidFields.Any());
 }
Пример #56
0
        public async Task <Dag> GetDagAsync(ulong block, ILogger logger)
        {
            var epoch = block / EthereumConstants.EpochLength;
            Dag result;

            lock (cacheLock)
            {
                if (numCaches == 0)
                {
                    numCaches = 3;
                }

                if (!caches.TryGetValue(epoch, out result))
                {
                    // No cached DAG, evict the oldest if the cache limit was reached
                    while (caches.Count >= numCaches)
                    {
                        var toEvict      = caches.Values.OrderBy(x => x.LastUsed).First();
                        var key          = caches.First(pair => pair.Value == toEvict).Key;
                        var epochToEvict = toEvict.Epoch;

                        logger.Info(() => $"Evicting DAG for epoch {epochToEvict} in favour of epoch {epoch}");
                        toEvict.Dispose();
                        caches.Remove(key);
                    }

                    // If we have the new DAG pre-generated, use that, otherwise create a new one
                    if (future != null && future.Epoch == epoch)
                    {
                        logger.Debug(() => $"Using pre-generated DAG for epoch {epoch}");

                        result = future;
                        future = null;
                    }

                    else
                    {
                        logger.Info(() => $"No pre-generated DAG available, creating new for epoch {epoch}");
                        result = new Dag(epoch);
                    }

                    caches[epoch] = result;
                }

                // If we used up the future cache, or need a refresh, regenerate
                if (future == null || future.Epoch <= epoch)
                {
                    logger.Info(() => $"Pre-generating DAG for epoch {epoch + 1}");
                    future = new Dag(epoch + 1);

                    #pragma warning disable 4014
                    future.GenerateAsync(dagDir, logger);
                    #pragma warning restore 4014
                }

                result.LastUsed = DateTime.Now;
            }

            await result.GenerateAsync(dagDir, logger);

            return(result);
        }
Пример #57
0
        public static byte[] Run
            (byte[] ROM, bool ByteCorruptionEnable, long StartByte, long EndByte, ByteCorruptionOptions ByteCorruptionOption,
            uint EveryNthByte, int AddXtoByte, int ShiftRightXBytes, byte ReplaceByteXwithYByteX, byte ReplaceByteXwithYByteY, bool EnableNESCPUJamProtection,
            bool TextReplacementEnable, bool TextUseByteCorruptionRange, string RawTextToReplace, string RawReplaceWith, string RawAnchorWords,
            bool ColorReplacementEnable, bool ColorUseByteCorruptionRange, string RawColorsToReplace, string RawReplaceWithColors, double MultiplyByteX, bool EnableByteBomb, int ByteBombRadius)
        {
            // Areas to not corrupt.
            List <long[]> ProtectedRegions = new List <long[]>();

            // Delimeter for text sections.
            char[] Delimeter = new char[1] {
                '|'
            };

            // Do text replacement if desired.
            if (TextReplacementEnable)
            {
                // Translation dictionary.
                Dictionary <char, byte> TranslationDictionary = new Dictionary <char, byte>();

                // Read in the text and its replacement.
                string[] TextToReplace = RawTextToReplace.Split(Delimeter, StringSplitOptions.RemoveEmptyEntries);
                string[] ReplaceWith   = RawReplaceWith.Split(Delimeter, StringSplitOptions.RemoveEmptyEntries);

                // Make sure they have equal length.
                if (TextToReplace.Length != ReplaceWith.Length)
                {
                    MessageBox.Show("Number of text sections to replace does not match number of replacements.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(null);
                }

                // Create relative offset arrays of the anchors.
                string[] Anchors         = RawAnchorWords.Split(Delimeter, StringSplitOptions.RemoveEmptyEntries);
                int[][]  RelativeAnchors = new int[Anchors.Length][];
                for (int i = 0; i < Anchors.Length; i++)
                {
                    RelativeAnchors[i] = new int[Anchors[i].Length];
                    for (int j = 0; j < Anchors[i].Length; j++)
                    {
                        RelativeAnchors[i][j] = Anchors[i][j] - Anchors[i][0];
                    }
                }

                // Look for the anchors.
                for (int i = 0; i < RelativeAnchors.Length; i++)
                {
                    // Position in ROM.
                    long j = 0;

                    // Scan the entire ROM.
                    while (j < ROM.LongLength)
                    {
                        // If a match has been found.
                        bool Match = true;

                        // Look for the relative values.
                        for (int k = 0; k < RelativeAnchors[i].Length; k++)
                        {
                            // Make sure its in range.
                            if (j + k < ROM.LongLength)
                            {
                                // Ignore non-letter characters for matching purposes.
                                if (!Char.IsLetter(Anchors[i][k]))
                                {
                                    continue;
                                }

                                // Check if the relative value doesn't match.
                                if ((ROM[j + k] - ROM[j]) != RelativeAnchors[i][k])
                                {
                                    // It doesn't, break.
                                    Match = false;
                                    break;
                                }
                            }
                            else
                            {
                                // Out of range before matching.
                                Match = false;
                                break;
                            }
                        }

                        // If a match was found, update the dictionary.
                        if (Match)
                        {
                            int k = 0;
                            for (k = 0; k < Anchors[i].Length; k++)
                            {
                                if (!TranslationDictionary.ContainsKey(Anchors[i][k]))
                                {
                                    TranslationDictionary.Add(Anchors[i][k], ROM[j + k]);
                                }
                            }

                            // Move ahead to the correct location in the ROM.
                            j = j + k + 1;
                        }
                        else
                        {
                            // Move ahead one byte.
                            j = j + 1;
                        }
                    }
                }

                // Calculate the offset to translate unknown text, assuming ASCII structure.
                int ASCIIOffset = 0;
                if (TranslationDictionary.Count > 0)
                {
                    ASCIIOffset = TranslationDictionary.First().Value - TranslationDictionary.First().Key;
                }

                // Create arrays of the text to be replaced in ROM format.
                byte[][] ByteTextToReplace = new byte[TextToReplace.Length][];
                for (int i = 0; i < TextToReplace.Length; i++)
                {
                    ByteTextToReplace[i] = new byte[TextToReplace[i].Length];
                    for (int j = 0; j < TextToReplace[i].Length; j++)
                    {
                        if (TranslationDictionary.ContainsKey(TextToReplace[i][j]))
                        {
                            ByteTextToReplace[i][j] = TranslationDictionary[TextToReplace[i][j]];
                        }
                        else
                        {
                            int ASCIITranslated = TextToReplace[i][j] + ASCIIOffset;
                            if (ASCIITranslated >= Byte.MinValue && ASCIITranslated <= Byte.MaxValue)
                            {
                                ByteTextToReplace[i][j] = (byte)(ASCIITranslated);
                            }
                            else
                            {
                                // Could not translate.
                                ByteTextToReplace[i][j] = (byte)(TextToReplace[i][j]);
                            }
                        }
                    }
                }

                // Create arrays of the replacement text in ROM format.
                byte[][] ByteReplaceWith = new byte[ReplaceWith.Length][];
                for (int i = 0; i < ReplaceWith.Length; i++)
                {
                    ByteReplaceWith[i] = new byte[ReplaceWith[i].Length];
                    for (int j = 0; j < ReplaceWith[i].Length; j++)
                    {
                        if (TranslationDictionary.ContainsKey(ReplaceWith[i][j]))
                        {
                            ByteReplaceWith[i][j] = TranslationDictionary[ReplaceWith[i][j]];
                        }
                        else
                        {
                            int ASCIITranslated = ReplaceWith[i][j] + ASCIIOffset;
                            if (ASCIITranslated >= Byte.MinValue && ASCIITranslated <= Byte.MaxValue)
                            {
                                ByteReplaceWith[i][j] = (byte)(ASCIITranslated);
                            }
                            else
                            {
                                // Could not translate.
                                ByteReplaceWith[i][j] = (byte)(ReplaceWith[i][j]);
                            }
                        }
                    }
                }

                // Area of ROM to consider.
                long TextReplacementStartByte = 0;
                long TextReplacementEndByte   = ROM.LongLength - 1;

                // Change area if using the byte corruption range.
                if (TextUseByteCorruptionRange)
                {
                    TextReplacementStartByte = StartByte;
                    TextReplacementEndByte   = EndByte;
                }

                // Look for the text to replace.
                for (int i = 0; i < ByteTextToReplace.Length; i++)
                {
                    // Position in ROM.
                    long j = TextReplacementStartByte;

                    // Scan the entire ROM.
                    while (j <= TextReplacementEndByte)
                    {
                        // If a match has been found.
                        bool Match = true;

                        // Look for the text.
                        for (int k = 0; k < ByteTextToReplace[i].Length; k++)
                        {
                            // Make sure its in range.
                            if (j + k <= TextReplacementEndByte)
                            {
                                // Ignore non-letter characters for matching purposes.
                                if (!Char.IsLetter(TextToReplace[i][k]))
                                {
                                    continue;
                                }

                                // Check if the relative value doesn't match.
                                if (ROM[j + k] != ByteTextToReplace[i][k])
                                {
                                    // It doesn't, break.
                                    Match = false;
                                    break;
                                }
                            }
                            else
                            {
                                // Out of range before matching.
                                Match = false;
                                break;
                            }
                        }

                        // If the entire string matched, replace it.
                        if (Match)
                        {
                            // If the area is protected.
                            bool Protected = false;

                            // Length of the replacement.
                            int k = ByteReplaceWith[i].Length - 1;

                            // Check if the area is protected.
                            foreach (long[] ProtectedRegion in ProtectedRegions)
                            {
                                if ((j >= ProtectedRegion[0] && j <= ProtectedRegion[1]) || (j + k >= ProtectedRegion[0] && j + k <= ProtectedRegion[1]) || (j <ProtectedRegion[0] && j + k> ProtectedRegion[1]))
                                {
                                    // Yes, its protected.
                                    Protected = true;
                                    break;
                                }
                            }

                            // If not protected, replace the text.
                            if (!Protected)
                            {
                                for (k = 0; k < ByteReplaceWith[i].Length; k++)
                                {
                                    ROM[j + k] = ByteReplaceWith[i][k];
                                }

                                // Protect the inserted text.
                                ProtectedRegions.Add(new long[2] {
                                    j, j + k
                                });
                            }

                            // Move ahead to the correct location in the ROM.
                            j = j + k + 1;
                        }
                        else
                        {
                            // Move ahead one byte.
                            j = j + 1;
                        }
                    }
                }
            }

            // Do color replacement if desired.
            if (ColorReplacementEnable)
            {
                // Read in the text and its replacement.
                string[] ColorsToReplace   = RawColorsToReplace.Split(Delimeter, StringSplitOptions.RemoveEmptyEntries);
                string[] ColorsReplaceWith = RawReplaceWithColors.Split(Delimeter, StringSplitOptions.RemoveEmptyEntries);

                // Make sure they have equal length.
                if (ColorsToReplace.Length != ColorsReplaceWith.Length)
                {
                    MessageBox.Show("Number of colors to replace does not match number of replacements.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(null);
                }

                // Convert the strings.
                byte[] ColorsToReplaceBytes   = new byte[ColorsToReplace.Length];
                byte[] ColorsReplaceWithBytes = new byte[ColorsReplaceWith.Length];
                for (int i = 0; i < ColorsToReplace.Length; i++)
                {
                    try
                    {
                        byte Converted = Convert.ToByte(ColorsToReplace[i], 16);
                        ColorsToReplaceBytes[i] = Converted;
                    }
                    catch
                    {
                        MessageBox.Show("Invalid color to replace.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(null);
                    }
                }
                for (int i = 0; i < ColorsReplaceWithBytes.Length; i++)
                {
                    try
                    {
                        byte Converted = Convert.ToByte(ColorsReplaceWith[i], 16);
                        ColorsReplaceWithBytes[i] = Converted;
                    }
                    catch
                    {
                        MessageBox.Show("Invalid color replacement.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(null);
                    }
                }

                // Area of ROM to consider.
                long ColorReplacementStartByte = 0;
                long ColorReplacementEndByte   = ROM.LongLength - 1;

                // Change area if using the byte corruption range.
                if (ColorUseByteCorruptionRange)
                {
                    ColorReplacementStartByte = StartByte;
                    ColorReplacementEndByte   = EndByte;
                }

                // Position in ROM.
                long j = ColorReplacementStartByte;

                // Scan the entire ROM.
                while (j <= ColorReplacementEndByte)
                {
                    // If a palette has been found.
                    bool Palette = true;

                    // Look for a palette.
                    for (int k = 0; k < 4; k++)
                    {
                        // Make sure its in range.
                        if (j + k <= ColorReplacementEndByte)
                        {
                            // Check if value exceeds the maximum valid color value.
                            if (ROM[j + k] > 0x3F)
                            {
                                // It does, break.
                                Palette = false;
                                break;
                            }
                        }
                        else
                        {
                            // Out of range before matching.
                            Palette = false;
                            break;
                        }
                    }

                    // If a possible palette was found, do color replacement.
                    if (Palette)
                    {
                        for (int i = 0; i < ColorsToReplaceBytes.Length; i++)
                        {
                            for (int k = 0; k < 4; k++)
                            {
                                if (ROM[j + k] == ColorsToReplaceBytes[i])
                                {
                                    // If the byte is protected.
                                    bool Protected = false;

                                    // Check if the byte is protected.
                                    foreach (long[] ProtectedRegion in ProtectedRegions)
                                    {
                                        if (j + k >= ProtectedRegion[0] && j + k <= ProtectedRegion[1])
                                        {
                                            // Yes, its protected.
                                            Protected = true;
                                            break;
                                        }
                                    }

                                    // If its not protected, do the replacement.
                                    if (!Protected)
                                    {
                                        ROM[j + k] = ColorsReplaceWithBytes[i];
                                        ProtectedRegions.Add(new long[2] {
                                            j + k, j + k
                                        });
                                    }
                                }
                            }
                        }

                        // Move ahead to the correct location in the ROM.
                        j = j + 4;
                    }
                    else
                    {
                        // Move ahead one byte.
                        j = j + 1;
                    }
                }
            }

            // Do byte corruption if desired.
            if (ByteCorruptionEnable)
            {
                if (ByteCorruptionOption == ByteCorruptionOptions.AddXToByte && AddXtoByte != 0)
                {
                    for (long i = StartByte + EveryNthByte; i <= EndByte; i = i + EveryNthByte)
                    {
                        // If the byte is protected.
                        bool Protected = false;

                        // Check if the byte is protected.
                        foreach (long[] ProtectedRegion in ProtectedRegions)
                        {
                            if (i >= ProtectedRegion[0] && i <= ProtectedRegion[1])
                            {
                                // Yes, its protected.
                                Protected = true;
                                break;
                            }
                        }

                        // Do NES CPU jam protection if desired.
                        if (EnableNESCPUJamProtection)
                        {
                            if (!Protected && i >= 2)
                            {
                                if (NESCPUJamProtection_Avoid.Contains((byte)((ROM[i] + AddXtoByte) % (Byte.MaxValue + 1))) ||
                                    NESCPUJamProtection_Protect_1.Contains(ROM[i]) ||
                                    NESCPUJamProtection_Protect_2.Contains(ROM[i - 1]) ||
                                    NESCPUJamProtection_Protect_3.Contains(ROM[i - 2]))
                                {
                                    Protected = true;
                                }
                            }
                        }

                        // If the byte is not protected, corrupt it.
                        if (!Protected)
                        {
                            if (EnableByteBomb)
                            {
                                for (int r = -ByteBombRadius; r < ByteBombRadius; r++)
                                {
                                    if (!((i + r) >= StartByte && (i + r) <= EndByte))
                                    {
                                        continue;
                                    }
                                    int newValue = (ROM[i + r] + AddXtoByte) % (Byte.MaxValue + 1);
                                    ROM[i + r] = (byte)newValue;
                                }
                            }
                            else
                            {
                                int NewValue = (ROM[i] + AddXtoByte) % (Byte.MaxValue + 1);
                                ROM[i] = (byte)NewValue;
                            }
                        }
                    }
                }
                else if (ByteCorruptionOption == ByteCorruptionOptions.ShiftRightXBytes && ShiftRightXBytes != 0)
                {
                    for (long i = StartByte + EveryNthByte; i <= EndByte; i = i + EveryNthByte)
                    {
                        long j = i + ShiftRightXBytes;

                        if (j >= StartByte && j <= EndByte)
                        {
                            // If the byte is protected.
                            bool Protected = false;

                            // Check if the byte is protected.
                            foreach (long[] ProtectedRegion in ProtectedRegions)
                            {
                                if (j >= ProtectedRegion[0] && j <= ProtectedRegion[1])
                                {
                                    // Yes, its protected.
                                    Protected = true;
                                    break;
                                }
                            }

                            // Do NES CPU jam protection if desired.
                            if (EnableNESCPUJamProtection)
                            {
                                if (!Protected && j >= 2)
                                {
                                    if (NESCPUJamProtection_Avoid.Contains(ROM[i]) ||
                                        NESCPUJamProtection_Protect_1.Contains(ROM[j]) ||
                                        NESCPUJamProtection_Protect_2.Contains(ROM[j - 1]) ||
                                        NESCPUJamProtection_Protect_3.Contains(ROM[j - 2]))
                                    {
                                        Protected = true;
                                    }
                                }
                            }

                            // If the byte is not protected, corrupt it.
                            if (!Protected)
                            {
                                if (EnableByteBomb)
                                {
                                    for (int r = -ByteBombRadius; r < ByteBombRadius; r++)
                                    {
                                        if (!((i + r) >= StartByte && (i + r + ShiftRightXBytes) <= EndByte))
                                        {
                                            continue;
                                        }
                                        long t = i + r + ShiftRightXBytes;
                                        if (t >= StartByte && t <= EndByte)
                                        {
                                            ROM[i + r] = ROM[t];
                                        }
                                    }
                                }
                                else
                                {
                                    ROM[j] = ROM[i];
                                }
                            }
                        }
                    }
                }
                else if (ByteCorruptionOption == ByteCorruptionOptions.ReplaceByteXwithY && ReplaceByteXwithYByteX != ReplaceByteXwithYByteY)
                {
                    for (long i = StartByte + EveryNthByte; i <= EndByte; i = i + EveryNthByte)
                    {
                        if (ROM[i] == ReplaceByteXwithYByteX)
                        {
                            // If the byte is protected.
                            bool Protected = false;

                            // Check if the byte is protected.
                            foreach (long[] ProtectedRegion in ProtectedRegions)
                            {
                                if (i >= ProtectedRegion[0] && i <= ProtectedRegion[1])
                                {
                                    // Yes, its protected.
                                    Protected = true;
                                    break;
                                }
                            }

                            // If the byte is not protected, corrupt it.
                            if (!Protected)
                            {
                                if (EnableByteBomb)
                                {
                                    for (int r = -ByteBombRadius; r < ByteBombRadius; r++)
                                    {
                                        if (!((i + r) >= StartByte && (i + r) <= EndByte))
                                        {
                                            continue;
                                        }
                                        if (ROM[i + r] == ReplaceByteXwithYByteX)
                                        {
                                            ROM[i + r] = ReplaceByteXwithYByteY;
                                        }
                                    }
                                }
                                else
                                {
                                    ROM[i] = ReplaceByteXwithYByteY;
                                }
                            }
                        }
                    }
                }

                if (ByteCorruptionOption == ByteCorruptionOptions.MultiplyByte && MultiplyByteX != 1)
                {
                    for (long i = StartByte + EveryNthByte; i <= EndByte; i = i + EveryNthByte)
                    {
                        // If the byte is protected.
                        bool Protected = false;

                        // Check if the byte is protected.
                        foreach (long[] ProtectedRegion in ProtectedRegions)
                        {
                            if (i >= ProtectedRegion[0] && i <= ProtectedRegion[1])
                            {
                                // Yes, its protected.
                                Protected = true;
                                break;
                            }
                        }

                        // Do NES CPU jam protection if desired.
                        if (EnableNESCPUJamProtection)
                        {
                            if (!Protected && i >= 2)
                            {
                                if (NESCPUJamProtection_Avoid.Contains((byte)((ROM[i] + AddXtoByte) % (Byte.MaxValue + 1))) ||
                                    NESCPUJamProtection_Protect_1.Contains(ROM[i]) ||
                                    NESCPUJamProtection_Protect_2.Contains(ROM[i - 1]) ||
                                    NESCPUJamProtection_Protect_3.Contains(ROM[i - 2]))
                                {
                                    Protected = true;
                                }
                            }
                        }

                        // If the byte is not protected, corrupt it.
                        if (!Protected)
                        {
                            if (EnableByteBomb)
                            {
                                for (int r = -ByteBombRadius; r < ByteBombRadius; r++)
                                {
                                    if (!((i + r) >= StartByte && (i + r) <= EndByte))
                                    {
                                        continue;
                                    }
                                    int newValue = (int)(ROM[i + r] * MultiplyByteX) % (Byte.MaxValue + 1);
                                    ROM[i + r] = (byte)newValue;
                                }
                            }
                            else
                            {
                                int NewValue = (int)(ROM[i] * MultiplyByteX) % (Byte.MaxValue + 1);
                                ROM[i] = (byte)NewValue;
                            }
                        }
                    }
                }
            }

            return(ROM);
        }
Пример #58
0
        public async void StartUp(bool localDev, int launcherVersion, string exePath, string resourcePath, string dataPath, string[] args)
        {
            LocalDev        = localDev;
            LauncherVersion = launcherVersion;
            ExePath         = exePath;
            ResourcePath    = resourcePath;
            DataPath        = dataPath;
            Args            = args;

            if (LauncherVersion != CompatibleLauncherVersion)
            {
                MessageBox.Show("Please download the latest BardMusicPlayer.exe from https://bardmusicplayer.com",
                                "Bard Music Player Update Available",
                                MessageBoxButton.OK,
                                MessageBoxImage.Information);
                Environment.Exit(0);
            }

#if PUBLISH
            // Read Version or default values if failure.
            try
            {
                if (File.Exists(ResourcePath + @"version.json"))
                {
                    LocalVersion = File.ReadAllText(ResourcePath + @"version.json", Encoding.UTF8)
                                   .DeserializeFromJson <BmpVersion>();
                }
            }
            catch (Exception)
            {
                LocalVersion = new BmpVersion {
                    items = new List <BmpVersionItem>()
                };
            }

            var currentVersionBad = false;
            if (LocalVersion.build != 0)
            {
                Parallel.ForEach(LocalVersion.items, item =>
                {
                    if (!File.Exists(ResourcePath + item.destination) ||
                        File.Exists(ResourcePath + item.destination) && !item.sha256.ToLower()
                        .Equals(Sha256.GetChecksum(ResourcePath + item.destination).ToLower()))
                    {
                        currentVersionBad = true;
                    }
                });
                if (currentVersionBad)
                {
                    LocalVersion = new BmpVersion {
                        items = new List <BmpVersionItem>()
                    }
                }
                ;
            }

            // Fetch UpdateInfo and Versions or default values if failure.
            var remoteVersionBad = false;
            RemoteVersions = new Dictionary <string, BmpVersion>();
            try
            {
                var remoteVersionsListString = await new Downloader().GetStringFromUrl(BaseUrl + @"versionlist.json");
                var remoteVersionsList       = remoteVersionsListString.DeserializeFromJson <List <string> >();

                foreach (var remoteVersion in remoteVersionsList)
                {
                    try
                    {
                        var remoteVersionString = await new Downloader().GetStringFromUrl(BaseUrl + remoteVersion + "/version.json");
                        RemoteVersions.Add(remoteVersion, remoteVersionString.DeserializeFromJson <BmpVersion>());
                    }
                    catch (Exception)
                    {
                        // Failed to grab a specific remote version.json. ignore.
                        remoteVersionBad = true;
                    }
                }
            }
            catch (Exception)
            {
                // Failed to grab the list of remote versions available. ignore.
                remoteVersionBad = true;
            }

            // sort the list of remote versions first by 'if !beta', then 'latest build', then convert back to dictionary
            RemoteVersions =
                RemoteVersions.OrderBy(version => version.Value.beta)
                .ThenByDescending(version => version.Value.build)
                .ToDictionary <KeyValuePair <string, Util.BmpVersion>, string, Util.BmpVersion>(pair => pair.Key, pair => pair.Value);

            // 1. remote version was not able to be read, try and load local
            // 2. remote version was able to be read but it's same as local, try and load local
            if ((remoteVersionBad && !currentVersionBad) || (RemoteVersions.First().Value.build == LocalVersion.build))
            {
                await Loader.Load(LocalVersion, ExePath, ResourcePath, DataPath, Args);

                return;
            }

            // 1. we don't have a current version
            // 2. remote version shows an update
            if (currentVersionBad || (RemoteVersions.First().Value.build > LocalVersion.build))
            {
                MainWindow mainWindow = new MainWindow();
                mainWindow.ProvideVersions(LocalVersion, RemoteVersions);

                mainWindow.OnDownloadRequested += new EventHandler <BmpDownloadEvent>((object sender, BmpDownloadEvent e) =>
                {
                    var key     = e.Key;
                    var version = e.Version;
                    var item    = e.Item;

                    string sourceUrl = $"{BaseUrl}{key}/{item.source}";
                    string destFPath = ResourcePath + item.destination;

                    Downloader downloader = new Downloader();

                    try
                    {
                        Debug.WriteLine($"Attempting to download {sourceUrl} and save to {destFPath}.");

                        var dlTask = downloader.GetFileFromUrl(sourceUrl);
                        dlTask.Wait();
                        byte[] file = dlTask.Result;
                        if (Sha256.GetChecksum(file).Equals(item.sha256))
                        {
                            Directory.CreateDirectory(ResourcePath);
                            File.WriteAllBytes(destFPath, file);
                        }
                    }
                    catch (Exception)
                    {
                        // unable to download file, show message to the user and throw
                        throw new Exception("Unable to download file: " + sourceUrl);
                    }
                });

                var launchHandler = new EventHandler <BmpVersion>(async(object sender, BmpVersion version) =>
                {
                    await Loader.Load(version, ExePath, ResourcePath, DataPath, Args);
                });

                mainWindow.OnDownloadComplete += launchHandler;
                mainWindow.OnLaunchRequested  += launchHandler;

                mainWindow.ShowDialog();
            }
#elif LOCAL
            var version = new BmpVersion
            {
                beta       = true,
                build      = 0,
                commit     = "DEBUG",
                entryClass = "BardMusicPlayer.Ui.Bootstrapper",
                entryDll   = "BardMusicPlayer.Ui.dll",
                items      = new List <BmpVersionItem>()
            };

            var items = Directory.GetFiles(ResourcePath, "*.dll").Where(name => !name.Contains("libzt.dll"));
            foreach (var item in items)
            {
                version.items.Add(new BmpVersionItem
                {
                    destination = Path.GetFileName(item),
                    sha256      = Sha256.GetChecksum(item),
                    load        = true
                });
            }

            await Loader.Load(version, ExePath, ResourcePath, DataPath, Args);
#endif
        }
    }
Пример #59
0
        private PuzzleTreeNode <IPuzzle> StartToBuildPuzzleTree(PuzzleEvents events, PuzzleTreeNode <IPuzzle> parent)
        {
            PuzzleTreeNode <IPuzzle> nodeSolution = null;
            var hasMoreItems  = true;
            var foundSolution = false;
            var openedParents = new Dictionary <string, PuzzleTreeNode <IPuzzle> >();
            var closedParents = new Dictionary <string, PuzzleTreeNode <IPuzzle> >();
            var parentPuzzle  = parent.Data;

            if (parentPuzzle.IsDone())
            {
                foundSolution = true;
                return(parent);
            }

            openedParents.Add(parentPuzzle.ToString(), parent);

            while (hasMoreItems && !foundSolution)
            {
                foreach (var allowedMovement in parentPuzzle.AllowedMovements())
                {
                    var puzzleChild = (Puzzle)parentPuzzle.Clone();

                    puzzleChild.Move(allowedMovement);

                    if (!IsARepeatedPuzzle(puzzleChild))
                    {
                        var puzzleChildNode = tree.Insert(puzzleChild, parent);

                        if (puzzleChild.IsDone())
                        {
                            foundSolution = true;
                            return(puzzleChildNode);
                        }

                        events.onStateChange.Invoke(puzzleChild);
                        openedParents.Add(puzzleChild.ToString(), puzzleChildNode);
                        AddToPuzzleRepeatedListIfNeed(puzzleChild);
                    }
                }

                var parentPuzzleString = parentPuzzle.ToString();

                openedParents.Remove(parentPuzzleString);

                if (!closedParents.ContainsKey(parentPuzzleString))
                {
                    closedParents.Add(parentPuzzleString, parent);
                }

                if (openedParents.Count == 0)
                {
                    hasMoreItems = false;
                    break;
                }

                AddToPuzzleRepeatedListIfNeed(parentPuzzle);
                parent       = openedParents.First().Value;
                parentPuzzle = parent.Data;
            }

            return(nodeSolution);
        }
Пример #60
0
        public void Configure(string key, Type pageType)
        {
            lock (PagesByKey)
            {
                if (PagesByKey.ContainsKey(key))
                {
                    throw new ArgumentException("This key is already used: " + key);
                }

                if (PagesByKey.Any(temp => temp.Value == pageType))
                {
                    throw new ArgumentException("This type is already configured with key " + PagesByKey.First(temp => temp.Value == pageType).Key);
                }

                PagesByKey.Add(key, pageType);
            }
        }