Beispiel #1
0
        public List<Problem> Build()
        {
            var digits = new[] { 2, 3, 4, 5, 6, 7, 8, 9 };
              var signs = new[] { "×", "÷" };
              var seed = DateTime.Now.Millisecond;
              var rand = new Random(seed);

              var data = new Dictionary<string, HashSet<Problem>>();
              data[signs[0]] = new HashSet<Problem>();
              data[signs[1]] = new HashSet<Problem>();
              var maxvalue = digits.Max() * digits.Max();
              var minvalue = 0;

              foreach (var digit1 in digits)
              {
            foreach (var digit2 in digits)
            {
              var sum = digit1 * digit2;
              if (sum <= maxvalue && sum >= minvalue)
              {
            data["×"].Add(new Problem(digit1, "×", digit2));
            data["×"].Add(new Problem(digit2, "×", digit1));
            data["÷"].Add(new Problem(sum, "÷", digit1));
            data["÷"].Add(new Problem(sum, "÷", digit2));
              }
            }
              }

              return (from v in data.Values
              from vv in v
              select vv).ToList();
        }
        static void Main()
        {
            IEnumerable <int> intArr =new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            IEnumerable<double> dblArr =new[] { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };

            Console.WriteLine("Sum of: ");
            Console.WriteLine("Integer array: {0}", intArr.Sum());
            Console.WriteLine("Double array: {0}", dblArr.Sum());

            Console.WriteLine();
            Console.WriteLine("Product of: ");
            Console.WriteLine("Integer array: {0}", intArr.Product());
            Console.WriteLine("Double array: {0}", dblArr.Product());

            Console.WriteLine();
            Console.WriteLine("Average of: ");
            Console.WriteLine("Integer array: {0}", intArr.Average());
            Console.WriteLine("Double array: {0}", dblArr.Average());

            Console.WriteLine();
            Console.WriteLine("Min of: ");
            Console.WriteLine("Integer array: {0}", intArr.Min());
            Console.WriteLine("Double array: {0}", dblArr.Min());

            Console.WriteLine();
            Console.WriteLine("Max of: ");
            Console.WriteLine("Integer array: {0}", intArr.Max());
            Console.WriteLine("Double array: {0}", dblArr.Max());
        }
        private Dictionary<DateTime, decimal> Calculate(DateTime fromDate)
        {
            DataPoints lastDatapoints = null;
            var ranges = new Dictionary<DateTime, decimal>();

            foreach (var datapoints in this.dataPointsList)
            {
                if (lastDatapoints == null)
                {
                    lastDatapoints = datapoints;
                    continue;
                }

                var possibleRanges = new[]
                    {
                        Math.Abs(datapoints.High - lastDatapoints.Close),
                        Math.Abs(lastDatapoints.Close - datapoints.Low),
                        datapoints.High.Difference(datapoints.Low),
                    };

                ranges.Add(datapoints.Date, possibleRanges.Max());
                lastDatapoints = datapoints;
            }

            return ranges.Where(r => r.Key > fromDate).ToDictionary(d => d.Key, d => d.Value);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Console.WriteLine(new string('-', 15));
            // IEnumerableExtensions test1 = new IEnumerableExtensions(); << can`t applay instance.
            var test1 = new[] { 1, 2, 7, 5, 3 };
            var r = test1.Max();
            Console.WriteLine(r);

            // test SUM
            var result1 = test1.Apply(Sum, 0);
            Console.WriteLine(result1);
            //testing
            var result1b = test1.Apply(Sum, test1[0]);
            Console.WriteLine(result1b);

            // test PRODUCT
            var result2 = test1.Apply(Product, 1);
            Console.WriteLine(result2);

            // test MIN
            var result3 = test1.Apply(Min, test1[0]);
            Console.WriteLine(result3);

            // test MAX
            var result4 = test1.Apply(Max, test1[0]);
            Console.WriteLine(result4);

            // test AVERAGE
            Console.WriteLine(test1.Average());
            Console.WriteLine(test1.Apply(Count, 0));
        }
Beispiel #5
0
 public override void UpdateWatch()
 {
     var threadValues = new[] { "Thread values:" }.Concat(ThreadValues.Select((s, i) => (s is string ? @"{{0}}: ""{0}""".Fmt(((string) s).CLiteralEscape()) : @"{{0}}: {0}".Fmt(s)).Fmt(i))).ToArray();
     var stackValues = new[] { "Stack:" }.Concat(Stack.Select(s => s is string ? @"""{0}""".Fmt(((string) s).CLiteralEscape()) : s.ToString())).ToArray();
     var width = stackValues.Max(v => v.Length);
     _txtWatch.Text = Enumerable.Range(0, Math.Max(threadValues.Length, stackValues.Length))
         .Select(l => "{{0,{0}}}  {{1}}".Fmt(width).Fmt(l < stackValues.Length ? stackValues[l] : "", l < threadValues.Length ? threadValues[l] : ""))
         .JoinString(Environment.NewLine);
 }
Beispiel #6
0
 public void MaxTest()
 {
     var original = new[] {1.0, 1.1, 2.3, -1.23, 3.14, -9.0};
     var actual = Utility.Max(original);
     const int maxIndex = 4;
     var expected = new Tuple<double, int>(original.Max(), maxIndex);
     Assert.IsTrue(Math.Abs(expected.Item1 - actual.Item1) < 0.001);
     Assert.IsTrue(actual.Item2 == expected.Item2);
 }
		public Rect TransformBounds (Rect rect)
		{
			var inverse = this;
			var points = new [] {
				inverse.TransformPoint (rect.TopLeft),
				inverse.TransformPoint (rect.TopRight),
				inverse.TransformPoint (rect.BottomLeft) ,
				inverse.TransformPoint (rect.BottomRight)
			};

			var x1 = points.Min (p => p.X);
			var y1 = points.Min (p => p.Y);

			var x2 = points.Max (p => p.X);
			var y2 = points.Max (p => p.Y);

			return new Rect (x1, y1, x2 - x1, y2 - y1);
		}
Beispiel #8
0
        public static double SmiteDamage()
        {
            var damage = new[]
                             {
                                 20 * Entry.Player.Level + 370, 30 * Entry.Player.Level + 330,
                                 40 * +Entry.Player.Level + 240, 50 * Entry.Player.Level + 100
                             };

            return Entry.Player.Spellbook.CanUseSpell(smite.Slot) == SpellState.Ready ? damage.Max() : 0;
        }
Beispiel #9
0
 private static double SmiteDamage()
 {
     if(smite == null) return 0d;
     var damage = new[]
     {
         20*_Player.Level + 370, 30*_Player.Level + 330, 40*+_Player.Level + 240,
         50*_Player.Level + 100
     };
     return _Player.Spellbook.CanUseSpell(smite.Slot) == SpellState.Ready ? damage.Max() : 0;
 }
Beispiel #10
0
 static void Main()
 {
     var elements = new[] {  "a",  "b" };
     Console.WriteLine(elements.Average());
     Console.WriteLine(elements.Min());
     Console.WriteLine(elements.Max());
     Console.WriteLine(elements.Sum());
     string a = "a";
     string b = "b";
     Console.WriteLine(a * b);
 }
 public byte FindRfAddress(System.Collections.Generic.IList<byte> exisitingRfAddresses)
 {
     if (!exisitingRfAddresses.Any ())
         return (byte)1;
     var maxExisting = exisitingRfAddresses.Max ();
     var holes = Enumerable.Range(1, maxExisting).Select(i => (byte)i).Where (i => !exisitingRfAddresses.Contains(i)).ToList ();
     if (holes.Count >= MaxSupportedConcurrentRequest) {
         return (byte)holes [_rnd.Next(holes.Count - 1)];
     }
     return (byte)(_rnd.Next(maxExisting+1, Math.Min(maxExisting+1+MaxSupportedConcurrentRequest, 250)));
 }
Beispiel #12
0
    static void Main()
    {
        var numbers = new[] { 3, 5, 12, 15, 30, 35 };

        Console.WriteLine("Sum: {0}", numbers.Sum());
        Console.WriteLine("Product: {0}", numbers.Product());
        Console.WriteLine("Min: {0}", numbers.Min());
        Console.WriteLine("Max: {0}", numbers.Max());
        Console.WriteLine("Average: {0}", numbers.Average());

        Console.WriteLine();
    }
Beispiel #13
0
        private static void Main()
        {
            var strBldr = new StringBuilder("Some test string");
            Console.WriteLine(strBldr.Substring(6, 4));

            IEnumerable<int> testEnum = new[] { 2, 5, 6, 8 };
            Console.WriteLine(testEnum.Average());

            Console.WriteLine(testEnum.Max());

            Console.WriteLine(testEnum.Min());
        }
 public int GetTargetIndex(System.Collections.Generic.List<WorldObject> availableTargets)
 {
     for (int i = 0; i < availableTargets.Count; i++)
     {
         if (availableTargets[i].Owner != this.Owner && availableTargets[i].Owner != 0
             && availableTargets[i].HitPoints == availableTargets.Max(x => x.HitPoints))
         {
             return i;
         }
     }
     return -1;
 }
        public override string WriteTable(out int itemCount)
        {
            itemCount = -1;
            if (!_exportDateInitialized)
                throw new Exception("Sales export date was not initialized.");
            if (Rows.Count < 1)
                return "no data";

            _progress.StartTask("Parsing data", "items", null, Rows.Count);

            var iPId = _rules.Fields.GetHeaderIndex(FieldName.OrderProductId);
            var iCId = _rules.Fields.GetHeaderIndex(FieldName.OrderCustomerId);
            var iQuan = _rules.Fields.GetHeaderIndex(FieldName.OrderQuantity);
            var iDate = _rules.Fields.GetHeaderIndex(FieldName.OrderDate);
            var indexes = new[] { iPId, iCId, iQuan, iDate };
            if (indexes.Min<int>() < 0)
                return string.Format("bad header: {0}", Header.Aggregate((w, j) => string.Format("{0},{1}", w, j)));
            var minCols = indexes.Max<int>();

            var sales = new List<SalesRecord>();
            try
            {
                sales.AddRange(from cols in Rows
                                             where (cols.Count > 0 && cols.Count > minCols)
                                                 select new SalesRecord
                                                 {
                                                     ProductId = cols[iPId],
                                                     CustomerId = cols[iCId],
                                                     Quantity = cols[iQuan],
                                                     Date = cols[iDate],
                                                 });
                DateTime testDate;
                sales = sales.Where(s => !Input.TryGetDate(out testDate, s.Date, _rules.OrderDateReversed)
                                            || (testDate.Year.Equals(_exportDate.Year) && testDate.Month.Equals(_exportDate.Month)))
                                            .ToList();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            if (sales.Count < 1)
                return "no data";

            //Migration slaves need to map each product id in sales to its replacement id
            _cart.MigrateSlaveOrders(ref sales);

            itemCount = sales.Count;
            var filename = String.Format(CartExtractor.SalesFilenameFormat, _exportDate.ToString("yyyy-MM"));
            _progress.UpdateTable(itemCount, -1, "Writing table");
            return TableAccess.Instance.WriteTable(_rules.Alias, filename, sales);
        }
        public static float AnalyzeToFloat(float curX, float curY, float curZ, float prevX, float prevY, float prevZ)
        {
            if (curX > 1 || curX < -1 || curY > 1 || curY < -1 || curZ > 1 || curZ < -1)
                return -1;
            if (prevX > 1 || prevX < -1 || prevY > 1 || prevY < -1 || prevZ > 1 || prevZ < -1)
                return -1;

            var xD = Math.Abs(prevX - curX);
            var yD = Math.Abs(prevY - curY);
            var zD = Math.Abs(prevZ - curZ);

            var dArr = new[] { xD, yD, zD };
            return dArr.Max();
        }
        public void In_IntNotInCollection_ReturnFalse()
        {
            var col = new[] { 1, 2, 3, 4, 5 };

            Assert.AreEqual(false, 0.In(col), "Testing 0");
            Assert.AreEqual(false, 9.In(col), "Testing 9");

            foreach (var i in col.Select(c => c + col.Max()))
                Assert.AreEqual(false, i.In(col), "Testing " + i);

            var odd = Enumerable.Range(1, 201).Where(i => i % 2 == 1).ToArray();

            for (var i = 0; i < odd.Length; i ++)
                Assert.AreEqual(i % 2 == 1, i.In(odd));
        }
 /// <summary>
 /// Calculates area of right trangle square
 /// </summary>
 /// <param name="side1Length">length of first side</param>
 /// <param name="side2Length">length of second side</param>
 /// <param name="side3Length">length of third side</param>
 public static Double Area(Double side1Length, Double side2Length, Double side3Length)
 {
     var sidesLength = new[] { side1Length, side2Length, side3Length };
     var hypotenuse = sidesLength.Max();
     try
     {
         sidesLength.Single(l => DoubleEquals(l, hypotenuse));//checks if there is only one side with maximum length
     }
     catch (System.InvalidOperationException)
     {
         throw new ArgumentException("Wrong sides length");
     }
     if (!DoubleEquals(hypotenuse, Math.Sqrt(sidesLength.Where(l => l != hypotenuse).Select(l => Math.Pow(l, 2)).Sum())))//checks Pythagorean theorem
         throw new ArgumentException("Wrong sides length, does not satisfy the Pythagorean theorem");
     return 0.5 * sidesLength.Where(l => !DoubleEquals(l, hypotenuse)).Aggregate((cathetus1, cathetus2) => cathetus1 * cathetus2);
 }
Beispiel #19
0
        public void CompareTest()
        {
            var p1 = new Prefix(_prefixConfig, "DEV", "iphone");
            var p2 = new Prefix(_prefixConfig, "DEV");
            var p3 = new Prefix(_prefixConfig, "stageB");
            var p4 = new Prefix(_prefixConfig, "DEV", "iphone");
            var p5 = new Prefix(_prefixConfig, "ios", "iphone");

            var prefixes = new [] {p1, p2, p3, p4, p5};
            var max = prefixes.Max();
            var min = prefixes.Min();

            Assert.AreEqual(max, p1);
            Assert.AreEqual(min, p3);
            Assert.IsTrue(p2.CompareTo(p5) < 0);
        }
Beispiel #20
0
        static HexEncoder()
        {
            var hexDigits = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
                                                                                  'A', 'B', 'C', 'D', 'E', 'F' };
            var hexValues = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                                                                   10, 11, 12, 13, 14, 15};

            var max = hexDigits.Max();
            HexValueArray = new int[max + 1];
            for (var i = 0; i < HexValueArray.Length; i++)
            {
                var idx = Array.IndexOf(hexDigits, (char)i);
                var value = -1;
                if (idx != -1)
                    value = hexValues[idx];
                HexValueArray[i] = value;
            }
        }
        public void ExampleTest()
        {
            int[] a = new[] {0, 0, 4, 2, 4, 5};
            //Throwing possible exceptions
            if (a == null)
                throw new ArgumentNullException();
            if(a.Min()<0)
                throw new ArgumentOutOfRangeException();
            if(a.Length==0)
                throw new ArgumentException();

            //Looking for max value and create array
            int maxValue = a.Max();
            int[] result = new int[maxValue + 1];

            // And now the counting operation
            foreach (int i1 in a)
            {
                result[i1]++;
            }
            Assert.AreEqual(new[] {2, 0, 1, 0, 2, 1}, result);
            int[] a1 = new[] {5, 0, 2, 4, 0, 4};
            //Throwing possible exceptions
            if (a1 == null)
                throw new ArgumentNullException();
            if(a1.Min()<0)
                throw new ArgumentOutOfRangeException();
            if(a1.Length==0)
                throw new ArgumentException();

            //Looking for max value and create array
            int maxValue1 = a1.Max();
            int[] result1 = new int[maxValue1 + 1];

            // And now the counting operation
            foreach (int i2 in a1)
            {
                result1[i2]++;
            }
            Assert.AreEqual(new[] {2, 0, 1, 0, 2, 1}, result1);
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            var strArray = new[] { "Maya", "Something", "And One More", "PET" };
            Print(strArray); Console.WriteLine();

            var res2 = strArray.OrderByDescending(x => x.Length).First();
            Console.WriteLine(res2);

            var res3 = strArray.Max(x => x.Length);
            Console.WriteLine(res3);

            var res4 = strArray.Aggregate("", (x, y) => x.Length > y.Length ? x : y);
            Console.WriteLine(res4);

            var res5 =
                from x in strArray
                where GetLongestString(x)
                select x;
            // Print(res5);
            Console.WriteLine(res5.Last());
        }
        /*2.	Implement a set of extension methods for IEnumerable<T> that implement the following group functions:
         * sum, product, min, max, average.*/
        static void Main()
        {
            List<int> listInt = new List<int> { 1, 2, 3, 4, 5 };
            double[] testDouble = new[] { 4.5, 6.0, 5.7, 34.7 }; //sum = 50.9

            Console.WriteLine("---list <int>---");
            Console.WriteLine("Sum: {0}", listInt.Sum());
            Console.WriteLine("Average: {0}", listInt.Average());
            Console.WriteLine("Product: {0}", listInt.Product());
            Console.WriteLine("Minimum: {0}", listInt.Min());
            Console.WriteLine("Minimum: {0}", listInt.Max());

            Console.WriteLine("---double---");
            Console.WriteLine("Sum: {0}", testDouble.Sum());
            Console.WriteLine("Average: {0}", testDouble.Average());
            Console.WriteLine("Product: {0}", testDouble.Product());
            Console.WriteLine("Minimum: {0}", testDouble.Min());
            Console.WriteLine("Minimum: {0}", testDouble.Max());

            List<int> testEmpty = new List<int>();
            Console.WriteLine(testEmpty.Sum()); //return error when enumaration is empty, does not work about array(return 0)
        }
Beispiel #24
0
        static void Main()
        {
            var items = new[]
            {
                1.2,
                2.3,
                3.4
            };

            Console.Write("Elements: ");
            foreach (var item in items)
            {
                Console.Write("{0} ", item);
            }
            Console.WriteLine();

            Console.WriteLine("Sum: " + items.Sum());
            Console.WriteLine("Product: " + items.Product());
            Console.WriteLine("Min: " + items.Min());
            Console.WriteLine("Max: " + items.Max());
            Console.WriteLine("Average: " + items.Average());
        }
        public override string WriteTable(out int itemCount)
        {
            itemCount = -1;

            var iPId = _rules.Fields.GetHeaderIndex(FieldName.InventoryProductId);
            var iQuan = _rules.Fields.GetHeaderIndex(FieldName.InventoryQuantity);
            var indexes = new[] { iPId, iQuan };
            if (indexes.Min<int>() < 0)
                return string.Format("(bad header: {0})", Header.Aggregate((w, j) => string.Format("{0},{1}", w, j)));
            var maxIndex = indexes.Max<int>();

            _progress.StartTask("Parsing data", "items", null, Rows.Count);
            var data = new List<InventoryRecord>();
            try
            {
                data.AddRange(from cols in Rows
                                                where cols.Count() > maxIndex
                                                select new InventoryRecord(cols[iPId], cols[iQuan]));
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            _progress.EndTask(-1, "completed");
            if (data.Count < 1)
                return "no data";

            itemCount = data.Count;
            _progress.UpdateTable(itemCount, -1, "Writing table");
            var status = TableAccess.Instance.WriteTable(_rules.Alias, CartExtractor.InventoryFilename, data);
            _progress.UpdateTable(itemCount, -1, status);

            //Now the real work begins --convert new inventory data to DynamicUpdate Exclusions
            ProcessInventory(data);

            return status;
        }
        public void ProcessBar(Bar bar)
        {
            try
            {
                if (!IsItOkToHandleBar(bar))
                {
                    return;
                }

                if (bar.BeginTime >= CurrentValidityDateTime && !AreAllLegsCompleted)
                {
                    LoggingUtility.WriteTraceFormat(this, "Processing bar: {0}", bar);
                }

                BasicSaveBar(bar);

                CurrentBarRef = bar;

                SetCurrentDayOpeningPrice(bar);

                SetCurrentLastPrice(bar);

                if (bar.Size == CurrentExecutionTimePeriodInSeconds)
                {
                    int[] periods = new[]
                    {
                        SlowMaPeriod,
                        FastMaPeriod,
                        StochasticsDPeriod,
                        StochasticsKPeriod,
                        StochasticsSmoothPeriod
                    };

                    int maxPeriod = periods.Max();

                    if (CurrentExecutionBarSeries.Count <= maxPeriod)
                    {
                        return;
                    }

                    // Ensure that intraday indicators are evaluated
                    GetIsStochInBullishMode(bar);
                    GetIsStochInBearishMode(bar);
                    GetIsEmaInBearishMode(bar);
                    GetIsEmaInBullishMode(bar);
                    GetIsEmaAlmostInBearishMode(bar);
                    GetIsEmaAlmostInBullishMode(bar);

                    GetIsStochInObMode(bar);
                    GetIsStochInOsMode(bar);

                    AttempOrder();
                }

            }
            catch (Exception ex)
            {
                LoggingUtility.WriteError(this, ex, "Error in ProcessBar");
            }
            finally
            {
                CurrentBarRef = null;
            }
        }
        public string try_find_log_syntax(string[] lines) {
            if ( lines.Length < 5)
                return UNKNOWN_SYNTAX;

            string syntax = "";
            // see if we have $(file) first
            int pos1 = lines[0].IndexOf("\\"), pos2 = lines[0].IndexOf("\\");
            if ( pos1 < 20 && pos2 < 20)
                syntax += "$file ";

            List<int> times = new List<int>(), dates = new List<int>(), levels = new List<int>();
            foreach ( string line in lines) {
                times.Add( time_or_date_pos(line, ':'));
                
                int by_minus = time_or_date_pos(line, '-');
                int by_div = time_or_date_pos(line, '/');
                dates.Add(by_minus > 0 ? by_minus : by_div);

                int info = line.IndexOf(" INFO ");
                int err = line.IndexOf(" ERROR ");
                int fatal = line.IndexOf(" FATAL ");
                int dbg = line.IndexOf(" DEBUG ");
                int warn = line.IndexOf(" WARN ");
                if ( info > 0) levels.Add(info);
                else if ( err > 0) levels.Add(err);
                else if ( fatal > 0) levels.Add(fatal);
                else if ( dbg > 0) levels.Add(dbg);
                else if ( warn > 0) levels.Add(warn);
            }

            int[] all = new[] { times.Count, dates.Count, levels.Count };
            int min = all.Min(), max = all.Max();
            if (max - min > 1)
                // one of the times/dates/levels did not work                
                return UNKNOWN_SYNTAX;

            // at this point, we might have one line that was not fully parsed (thus, not all : time/date/level are parsed -> thus, we should ignore it)
            if (max - min == 1) {
                if ( times.Count == max)
                    times.RemoveAt(min);
                if ( dates.Count == max)
                    dates.RemoveAt(min);
                if ( levels.Count == max)
                    levels.RemoveAt(min);
            }

            bool ok = is_consistently_sorted(times,dates) != 0 && is_consistently_sorted(times,levels) != 0 && is_consistently_sorted(dates,levels) != 0;
            if ( !ok)
                // full line is a message
                return UNKNOWN_SYNTAX;

            List< Tuple<string,List<int>> > sorted = new List<Tuple<string,List<int>>>();
            // ... better to take the second line, since the first line might not be complete
            string first_line = lines.Length > 1 ? lines[1] : lines[0];
            List<int> end_indexes = new List<int>();
            if (is_consistently_present(times)) {
                int len = end_of_time_index(first_line, times[0]) - times[0];
                end_indexes.Add(times[0] + len);
                sorted.Add(new Tuple<string, List<int>>("$time[" + times[0] + "," + len + "]", times));
            }
            if (is_consistently_present(dates)) {
                int len = end_of_date_index(first_line, dates[0]) - dates[0];
                end_indexes.Add(dates[0] + len);
                sorted.Add(new Tuple<string, List<int>>("$date[" + dates[0] + "," + len + "]", dates));
            }
            if (is_consistently_present(levels)) {
                int len = 5;
                end_indexes.Add(levels[0] + 1 + len);
                sorted.Add(new Tuple<string, List<int>>("$level[" + (levels[0] + 1) + "," + len + "]", levels));
            }
            sorted.Sort( (x,y) => is_consistently_sorted(x.Item2,y.Item2) );

            foreach ( Tuple<string,List<int>> sli in sorted) 
                syntax += sli.Item1 + " ";

            end_indexes.Sort();
            if (end_indexes.Count > 0) {
                int start_msg = end_indexes.Last() + 1;
                // account for logs that have a starting line at beginning of msg
                if (first_line[start_msg] == '-')
                    ++start_msg;
                while (start_msg < first_line.Length && Char.IsWhiteSpace(first_line[start_msg]))
                    ++start_msg;
                syntax += "$msg[" + start_msg + "]";
            } else
                syntax += UNKNOWN_SYNTAX;
            return syntax;
        }
Beispiel #28
0
        /// <summary>
        /// 引数に関するヘルプを表示します。
        /// </summary>
        public static void ShowHelp()
        {
            var args = new []
            {
                new {Command = "--", Text = "これ以降のオプションをすべてファイルパスとして認識します."},
                new {Command = "    --code-pointing", Text = "コードポインティングを有効化します."},
                new {Command = "    --color", Text = "カラー表示を有効化します."},
                new {Command = "    --disable-code-pointing", Text = "コードポインティングを無効化します."},
                new {Command = "    --disable-color", Text = "カラー表示を無効化します."},
                new {Command = "-e, --suppress-error", Text = "エラー表示を抑制します."},
                new {Command = "-i, --suppress-info", Text = "情報表示を抑制します."},
                new {Command = "    --nonstop", Text = "エラー時が発生しても処理を中断しません."},
                new {Command = "-R, --recursive", Text = "子ディレクトリも再帰的に探索します."},
                new {Command = "-s, --silent", Text = "コンパイル出力以外の表示を抑制します."},
                new {Command = "-w, --suppress-warning", Text = "警告表示を抑制します."},

                new {Command = "-h, --help", Text = "このヘルプを表示します."},
            };

            Console.WriteLine("Options:");
            var commandLength = Math.Min(25, args.Max(a => a.Command.Length));
            var format = string.Format("  {{0,{0}}} {{1}}", -commandLength);

            foreach (var arg in args)
                Console.WriteLine(format, arg.Command, arg.Text);
        }
Beispiel #29
0
        private static double SmiteChampDamage()
        {
            if (smite.Slot == Player.GetSpellSlot("s5_summonersmiteduel"))
            {
                var damage = new[] { 54 + 6 * Player.Level };
                return Player.Spellbook.CanUseSpell(smite.Slot) == SpellState.Ready ? damage.Max() : 0;
            }

            if (smite.Slot == Player.GetSpellSlot("s5_summonersmiteplayerganker"))
            {
                var damage = new[] { 20 + 8 * Player.Level };
                return Player.Spellbook.CanUseSpell(smite.Slot) == SpellState.Ready ? damage.Max() : 0;
            }

            return 0;
        }
        public override void OnBar(Bar bar)
        {
            if (!bar.IsWithinRegularTradingHours(Instrument.Type))
            {
                return;
            }
            else
            {
                DataManager.Add(Instrument, bar);
            }

            try
            {
                CurrentBarRef = bar;

                if (bar.Size == PeriodConstants.PERIOD_DAILY)
                {
                    if (CurrentDailyBarSeries.Count <= AtrPeriod)
                    {
                        return;
                    }
                }

                if (bar.Size == CurrentExecutionTimePeriodInSeconds)
                {
                    int[] periods = new[]
                    {
                        SlowMaPeriod,
                        FastMaPeriod,
                        StochasticsDPeriod,
                        StochasticsKPeriod,
                        StochasticsSmoothPeriod
                    };

                    int maxPeriod = periods.Max();

                    if (CurrentExecutionBarSeries.Count <= maxPeriod)
                    {
                        return;
                    }
                }

                // If everything is filled - then exit:
                if (IsStrategyOrderFilled)
                    return;

                CurrentClosePrice = bar.Close;

                if (bar.Size == PeriodConstants.PERIOD_DAILY)
                {
                    CurrentAtrPrice = DailyAtrIndicator.Last;
                    if (CurrentClosePrice > 0 && IsBarCloseEnoughForLogging(bar))
                    {
                        LoggingUtility.WriteInfoFormat(this,
                            "Setting ATR to {0:c} which is {1:p} of the last close price {2:c}",
                            CurrentAtrPrice,
                            CurrentAtrPrice / CurrentClosePrice,
                            CurrentClosePrice);
                    }
                }

                if (bar.Size == PeriodConstants.PERIOD_DAILY)
                {
                    // We do not need to worry about any other type of bar
                    return;
                }

                if (bar.Size == CurrentExecutionTimePeriodInSeconds)
                {
                    // Ensure that intraday indicators are evaluated
                    GetIsStochInBullishMode(bar);
                    GetIsStochInBearishMode(bar);
                    GetIsEmaInBearishMode(bar);
                    GetIsEmaInBullishMode(bar);
                }

                if (CurrentAtrPrice <= 0)
                {
                    // need the ATR to process further
                    return;
                }

                if (CurrentAskPrice <= 0)
                {
                    // need the Ask to process further
                    return;
                }

                if (CurrentBidPrice <= 0)
                {
                    // need the Bid to process further
                    return;
                }

                if (GetCurrentDateTime() < CurrentValidityDateTime)
                {
                    return;
                }

                // 1. If the order is not triggered yet - then check when is the right time to trigger the order
                if (null == CurrentOrder)
                {
                    if (GetHasOrderBeenTriggered())
                    {
                        QueueOrder();
                    }
                }
                else
                {
                    if (IsStrategyOrderInFailedState)
                    {
                        throw new InvalidOperationException("Order is in an invalid state");
                    }
                    else
                    {
                        // 4. Partially filled? then queue up the remaining order
                        // We need to retry by adjusting the prices
                        if (GetHasOrderBeenReTriggered())
                        {
                            QueueOrder();
                        }
                    }
                }
            }
            finally
            {
                CurrentBarRef = null;
            }
        }