public override IEnumerable<string> WriteToFile(string outputFile, List<FeatureItemGroup> features, List<string> samples, string removeNamePrefix)
    {
      var result = base.WriteToFile(outputFile, features, samples, removeNamePrefix).ToList();

      var ntaFile = Path.ChangeExtension(outputFile, ".NTA.count");
      var isomiRFile = Path.ChangeExtension(outputFile, ".isomiR.count");
      var isomiRntaFile = Path.ChangeExtension(outputFile, ".isomiR_NTA.count");
      using (StreamWriter swNTA = new StreamWriter(ntaFile))
      using (StreamWriter swIso = new StreamWriter(isomiRFile))
      using (StreamWriter swIsoNTA = new StreamWriter(isomiRntaFile))
      {
        swNTA.WriteLine("Feature\tLocation\tSequence\t{0}", samples.Merge("\t"));
        swIso.WriteLine("Feature\tLocation\tSequence\t{0}", samples.Merge("\t"));
        swIsoNTA.WriteLine("Feature\tLocation\tSequence\t{0}", samples.Merge("\t"));

        foreach (var feature in features)
        {
          OutputCount(swNTA, feature, samples, MirnaConsts.NO_OFFSET, true, "", removeNamePrefix);

          OutputCount(swIso, feature, samples, 0, false, "_+_0", removeNamePrefix);
          OutputCount(swIso, feature, samples, 1, false, "_+_1", removeNamePrefix);
          OutputCount(swIso, feature, samples, 2, false, "_+_2", removeNamePrefix);

          OutputCount(swIsoNTA, feature, samples, 0, true, "_+_0", removeNamePrefix);
          OutputCount(swIsoNTA, feature, samples, 1, true, "_+_1", removeNamePrefix);
          OutputCount(swIsoNTA, feature, samples, 2, true, "_+_2", removeNamePrefix);
        }
      }

      result.Add(ntaFile);
      result.Add(isomiRFile);
      result.Add(isomiRntaFile);

      return result;
    }
        private IIdentifiedResultTextFormat GetMultipleFileFormat(IIdentifiedSpectrumWriter writer)
        {
            var result = DoGetMultipleFileFormat();

            result.ProteinFormat = format.ProteinFormat.GetLineFormat(proteinColumns.Merge("\t"));
            result.PeptideFormat = format.PeptideFormat.GetLineFormat(peptideColumns.Where(m => !string.IsNullOrWhiteSpace(m)).Merge("\t"));
            result.ScanWriter    = writer;
            return(result);
        }
Example #3
0
        public static RectangleUnion Unionize(IEnumerable <RectangleF> input)
        {
            IEnumerable <Shape> shapes = new List <Shape>();

            shapes = input.Select(r => new Shape(r));
            shapes = shapes.Merge((a, b) => Shape.TryMerge(a, b));
            shapes = shapes.Merge((a, b) => Shape.TryMerge(a, b));//Shouldn't have to do this twice
            return(new RectangleUnion(shapes.ToList()));
        }
Example #4
0
        public void TestRateStatList()
        {
            testInput    = DingliRecordExample;
            rateStatList = CsvContext.ReadString <LogRecord>(testInput, fileDescription_namesUs).ToList().MergeStat();
            Assert.AreEqual(rateStatList.Count, 28);
            Assert.AreEqual(rateStatList[0].DlThroughput, 18759024);
            Assert.AreEqual(rateStatList[25].DlThroughput, 68256);
            Assert.AreEqual(rateStatList[27].DlThroughput, 113760);
            Assert.AreEqual(rateStatList[2].DlMcs, 17);
            Assert.AreEqual(rateStatList[4].UlMcs, 0);
            Assert.AreEqual(rateStatList[6].Earfcn, 100);
            Assert.AreEqual(rateStatList[8].Pci, -1);
            Assert.AreEqual(rateStatList[10].PdschRbRate, 16160);
            Assert.AreEqual(rateStatList[14].PdschTbCode0, 14257);
            Assert.AreEqual(rateStatList[14].PdschTbCode1, 504);
            Assert.AreEqual(rateStatList[16].PhyThroughputCode0, 114056);
            Assert.AreEqual(rateStatList[16].PhyThroughputCode1, 4032);
            Assert.AreEqual(rateStatList[16].DlMcs, 20);
            Assert.AreEqual(rateStatList[16].PdschRbRate, 16160);
            Assert.AreEqual(rateStatList[16].DlThroughput, 68256);
            Assert.AreEqual(rateStatList[16].PhyRatePerRb, 7.057921, 1E-6);
            Assert.AreEqual(rateStatList[16].DlFrequencyEfficiency, 0.070579, 1E-6);
            Assert.AreEqual(rateStatList[16].DlRbsPerSlot, 8.08);
            Assert.AreEqual(rateStatList[16].Time.ToString("HH:mm:ss.fff"), "15:54:49.296");

            rateStatList[16].DividedBy <BasicRateStat>(10);
            Assert.AreEqual(rateStatList[16].PhyThroughputCode0, 11405);
            Assert.AreEqual(rateStatList[16].DlMcs, 2);
            Assert.AreEqual(rateStatList[16].PdschRbRate, 1616);
            Assert.AreEqual(rateStatList[16].DlThroughput, 6825);
            Assert.AreEqual(rateStatList[16].PhyRatePerRb, 7.057550, 1E-6);
            Assert.AreEqual(rateStatList[16].DlFrequencyEfficiency, 0.070575, 1E-6);
            Assert.AreEqual(rateStatList[16].DlRbsPerSlot, 0.808);
            Assert.AreEqual(rateStatList[16].Time.ToString("HH:mm:ss.fff"), "15:54:49.296");

            LogsOperations.RateEvaluationInterval = 1;
            List <BasicRateStat> basicList = rateStatList.Merge();

            Assert.AreEqual(basicList.Count, 2);
            Assert.AreEqual(basicList[0].DlFrequencyEfficiency, 5, 1E-6);
            Assert.AreEqual(basicList[0].DlThroughput, 17512972);

            LogsOperations.RateEvaluationInterval = 0.5;
            basicList = rateStatList.Merge();
            Assert.AreEqual(basicList.Count, 4);
            Assert.AreEqual(basicList[0].DlFrequencyEfficiency, 5, 1E-6);
            Assert.AreEqual(basicList[0].DlThroughput, 18759024);
            Assert.AreEqual(basicList[1].DlFrequencyEfficiency, 5, 1E-6);
            Assert.AreEqual(basicList[1].DlThroughput, 16088914);
            Assert.AreEqual(basicList[2].DlFrequencyEfficiency, 0.070579, 1E-6);
            Assert.AreEqual(basicList[2].DlThroughput, 58017);
            Assert.AreEqual(basicList[3].DlFrequencyEfficiency, 0.155195, 1E-6);
            Assert.AreEqual(basicList[3].DlThroughput, 74756);
        }
Example #5
0
        public static List <Param> GetReqJsonParameters(ListOrdered Components, IRedisClient Redis, IDatabase ObjectsDB)
        {
            List <Param> parameters = new List <Param>();

            foreach (ApiResources resource in Components)
            {
                if (resource is EbSqlReader || resource is EbSqlWriter || resource is EbSqlFunc)
                {
                    EbDataSourceMain dataSource = GetEbObject <EbDataSourceMain>(resource.Reference, Redis, ObjectsDB);

                    if (dataSource.InputParams == null || dataSource.InputParams.Count <= 0)
                    {
                        parameters.Merge(dataSource.GetParams(Redis as RedisClient));
                    }
                    else
                    {
                        parameters.Merge(dataSource.InputParams);
                    }
                }
                else if (resource is EbEmailNode)
                {
                    EbEmailTemplate emailTemplate = GetEbObject <EbEmailTemplate>(resource.Reference, Redis, ObjectsDB);

                    parameters = parameters.Merge(GetEmailParams(emailTemplate, Redis, ObjectsDB));
                }
                else if (resource is EbConnectApi)
                {
                    EbApi ob = GetEbObject <EbApi>(resource.Reference, Redis, ObjectsDB);

                    parameters = parameters.Merge(GetReqJsonParameters(ob.Resources, Redis, ObjectsDB));
                }
                else if (resource is EbThirdPartyApi thirdParty)
                {
                    if (thirdParty.Parameters != null && thirdParty.Parameters.Count > 0)
                    {
                        foreach (var param in thirdParty.Parameters)
                        {
                            parameters.Add(new Param
                            {
                                Name  = param.Name,
                                Type  = param.Type.ToString(),
                                Value = param.Value
                            });
                        }
                    }
                }
            }

            return(parameters);
        }
Example #6
0
        public static IEnumerable <Range> Merge(this IEnumerable <Range> ranges)
        {
            IEnumerable <Range> enu = new List <Range>();

            foreach (Range r in ranges)
            {
                IEnumerable <Range> next = ranges
                                           .Except(new Range[] { r })  // exclude current
                                           .Select(x => x?.Combine(r)) // combine
                                           .Where(x => x != null);     // exclude non-overlapping
                if (!next.Any())                                       // range is unique
                {
                    enu = enu.Concat(new Range[] { r });
                }
                else
                {
                    enu = enu.Concat(next);
                }
            }
            enu = enu.Distinct();
            if (enu.Except(ranges).Any()) // was it cut down at all?
            {
                return(enu.Merge());
            }
            return(enu);
        }
Example #7
0
        public virtual void WriteData2(Material _material)
        {
            MaterialPropertyBlock properties = new MaterialPropertyBlock();

            properties.SetInt("_GradientCountPoints", sfPoints.Count);

            List <float> gradientPoints          = new List <float>();
            List <float> gradientPointsPositions = new List <float>();
            List <float> gradientTypePoints      = new List <float>();

            if (sfPoints.Count > 0)
            {
                int curPos = 0;

                foreach (T point in sfPoints)
                {
                    gradientPoints = gradientPoints.Merge(point.ToData());

                    gradientPointsPositions.Add(curPos);
                    curPos += point.GetSize();

                    gradientTypePoints.Add((float)point.GetTypeGradient());
                }
            }

            properties.SetFloatArray("_GradientPoints", gradientPoints.ToArray());
            properties.SetFloatArray("_GradientPointsPositions", gradientPointsPositions.ToArray());
            properties.SetFloatArray("_GradientTypePoints", gradientTypePoints.ToArray());

            //_material.re
            //_material.SetP
            //_material.SetFloatArray( "_GradientTypePoints", gradientTypePoints.ToArray() );
        }
Example #8
0
        public void Validate_Merge_With_Conditions()
        {
            var e1 = new XElement("style");

            e1.Add(new XAttribute("element", "button"));
            e1.Add(new XElement("conditions", new XElement("pseudo-class", "hovered")));
            e1.Add(new XElement("property", "value-1"));

            var e2 = new XElement("style");

            e2.Add(new XAttribute("element", "button"));
            e2.Add(new XElement("conditions", new XElement("pseudo-class", "hovered")));
            e2.Add(new XElement("property", "value-2"));

            var s1 = new StyleWriterExtensions.Selector(e1);
            var s2 = new StyleWriterExtensions.Selector(e2);

            s1.Equals(s2).Should().BeTrue();

            var list = new List <XElement> {
                e1, e2
            };
            var result = list.Merge().ToList();

            result.Count.Should().Be(1);
            result.Elements("property").Count().Should().Be(2);
        }
Example #9
0
        public void TestRateStatMerge_DiscontinuousTime()
        {
            List <RateStat> stats = new List <RateStat> {
                new RateStat {
                    Time = new DateTime(2013, 1, 1, 10, 10, 24, 233),
                    Rsrp = -101
                },
                new RateStat {
                    Time = new DateTime(2013, 1, 1, 10, 10, 26, 333),
                    Rsrp = -102
                },
                new RateStat {
                    Time = new DateTime(2013, 1, 1, 10, 10, 27, 188),
                    Rsrp = -102
                },
                new RateStat {
                    Time = new DateTime(2013, 1, 1, 10, 10, 28, 278),
                    Rsrp = -101
                }
            };
            List <BasicRateStat> basicStats = stats.Merge();

            Assert.AreEqual(basicStats.Count, 3);
            Assert.AreEqual(basicStats[0].Rsrp, -101);
            Assert.AreEqual(basicStats[1].Rsrp, -102);
            Assert.AreEqual(basicStats[2].Rsrp, -101);
        }
Example #10
0
        public static Dictionary <string, ObjectMember> GetObjectMembers(this Type type)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var fields     = new List <ObjectMember>();
            var properties = new List <ObjectMember>();
            var flags      = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            foreach (var field in type.GetFields(flags).Where(x => !(x.IsSpecialName || x.Name.Contains("<"))))
            {
                var member = (ObjectMember)field;
                member.ToGetValue = o => field.GetValue(o);
                member.ToSetValue = (o, v) => field.SetValue(o, v);
                fields.Add(member);
            }

            foreach (var property in type.GetProperties(flags))
            {
                var member = (ObjectMember)property;
                member.ToGetValue = o => property.GetValue(o);
                member.ToSetValue = (o, v) => property.SetValue(o, v);
                properties.Add(member);
            }

            return(fields.Merge(properties).ToDictionary(x => x.MemberName, x => x));
        }
Example #11
0
            private async Task InternalRoll(int num, bool ordered)
            {
                if (num < 1 || num > 30)
                {
                    await ReplyErrorLocalized("dice_invalid_number", 1, 30).ConfigureAwait(false);

                    return;
                }

                var rng = new NadekoRandom();

                var dice   = new List <Image <Rgba32> >(num);
                var values = new List <int>(num);

                for (var i = 0; i < num; i++)
                {
                    var randomNumber = rng.Next(1, 7);
                    var toInsert     = dice.Count;
                    if (ordered)
                    {
                        if (randomNumber == 6 || dice.Count == 0)
                        {
                            toInsert = 0;
                        }
                        else if (randomNumber != 1)
                        {
                            for (var j = 0; j < dice.Count; j++)
                            {
                                if (values[j] < randomNumber)
                                {
                                    toInsert = j;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        toInsert = dice.Count;
                    }
                    dice.Insert(toInsert, GetDice(randomNumber));
                    values.Insert(toInsert, randomNumber);
                }

                using (var bitmap = dice.Merge())
                    using (var ms = bitmap.ToStream())
                    {
                        foreach (var d in dice)
                        {
                            d.Dispose();
                        }

                        await Context.Channel.SendFileAsync(ms, "dice.png",
                                                            Context.User.Mention + " " +
                                                            GetText("dice_rolled_num", Format.Bold(values.Count.ToString())) +
                                                            " " + GetText("total_average",
                                                                          Format.Bold(values.Sum().ToString()),
                                                                          Format.Bold((values.Sum() / (1.0f * values.Count)).ToString("N2")))).ConfigureAwait(false);
                    }
            }
Example #12
0
        public IObservable <FileSystemEventArgs> Watch(string vfsPath)
        {
            var actualPath = GetActualPath(vfsPath);

            var watcher = new FileSystemWatcher
            {
                Path   = actualPath,
                Filter = "*.*",
                EnableRaisingEvents   = true,
                IncludeSubdirectories = true
            };

            FileSystemEventArgs Selector(EventPattern <FileSystemEventArgs> pattern)
            {
                var e = pattern.EventArgs;

                return(e);
            }

            var observables = new List <IObservable <FileSystemEventArgs> >
            {
                Observable.FromEventPattern <FileSystemEventArgs>(watcher, "Changed").Select(Selector),
                Observable.FromEventPattern <FileSystemEventArgs>(watcher, "Created").Select(Selector),
                Observable.FromEventPattern <FileSystemEventArgs>(watcher, "Deleted").Select(Selector),
                Observable.FromEventPattern <FileSystemEventArgs>(watcher, "Renamed").Select(Selector)
            };

            return(observables.Merge());
        }
Example #13
0
        public void MergeTest()
        {
            Quote NewQuote(decimal i)
            {
                return(new Quote {
                    Price = i, Volume = 1, Broker = Broker.Bitflyer, Side = QuoteSide.Ask
                });
            }

            var quotes = new List <Quote>
            {
                NewQuote(1),
                NewQuote(2),
                NewQuote(11),
                NewQuote(512),
                NewQuote(514),
                NewQuote(510)
            };

            var step = 5;
            var r    = quotes.Merge(step).OrderBy(q => q.Price).ToList();

            Assert.AreEqual(5, r[0].Price);
            Assert.AreEqual(2, r[0].Volume);
            Assert.AreEqual(15, r[1].Price);
            Assert.AreEqual(1, r[1].Volume);
            Assert.AreEqual(510, r[2].Price);
            Assert.AreEqual(1, r[2].Volume);
            Assert.AreEqual(515, r[3].Price);
            Assert.AreEqual(2, r[3].Volume);
        }
Example #14
0
 /// <summary>
 /// Merges the elements in items into this List
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="list"></param>
 /// <param name="items"></param>
 internal static void Merge <T>(this List <T> list, T[] items)
 {
     foreach (T item in items)
     {
         list.Merge(item);
     }
 }
Example #15
0
 public static void Merge <T>(this List <T> items, IEnumerable <T> toMerge)
 {
     foreach (var item in toMerge)
     {
         items.Merge(item);
     }
 }
Example #16
0
            public async Task Draw(int num = 1)
            {
                var cards       = AllDecks.GetOrAdd(Context.Guild, (s) => new Cards());
                var images      = new List <Image>();
                var cardObjects = new List <Cards.Card>();

                if (num > 5)
                {
                    num = 5;
                }
                for (var i = 0; i < num; i++)
                {
                    if (cards.CardPool.Count == 0 && i != 0)
                    {
                        try { await Context.Channel.SendErrorAsync("No more cards in a deck.").ConfigureAwait(false); } catch { }
                        break;
                    }
                    var currentCard = cards.DrawACard();
                    cardObjects.Add(currentCard);
                    using (var stream = File.OpenRead(Path.Combine(cardsPath, currentCard.ToString().ToLowerInvariant() + ".jpg").Replace(' ', '_')))
                        images.Add(new Image(stream));
                }
                MemoryStream bitmapStream = new MemoryStream();

                images.Merge().SaveAsPng(bitmapStream);
                bitmapStream.Position = 0;
                var toSend = $"{Context.User.Mention}";

                if (cardObjects.Count == 5)
                {
                    toSend += $" drew `{Cards.GetHandValue(cardObjects)}`";
                }

                await Context.Channel.SendFileAsync(bitmapStream, images.Count + " cards.jpg", toSend).ConfigureAwait(false);
            }
Example #17
0
        /// <summary>
        /// Change the fields after merging with the merging window
        /// </summary>
        /// <param name="originalScriptMappings"></param>
        /// <param name="rootPath"></param>
        /// <param name="scenePath"></param>
        /// <param name="linesToChange"></param>
        /// <param name="mergedScriptMappings"></param>
        private void MergingWizardCompleted(List <ScriptMapping> originalScriptMappings, string rootPath,
                                            string scenePath,
                                            string[] linesToChange,
                                            List <ScriptMapping> mergedScriptMappings = null)
        {
            if (mergedScriptMappings != null)
            {
                originalScriptMappings = originalScriptMappings.Merge(mergedScriptMappings);
            }

            ThreadUtility.RunTask(() =>
            {
                fieldMappingController.MigrateFields(scenePath, ref linesToChange, ref originalScriptMappings,
                                                     ProjectPathUtility.getProjectPathFromFile(scenePath), rootPath);

                string newScenePath = rootPath + scenePath.GetRelativeAssetPath();

                if (!Administration.Instance.OverWriteMode)
                {
                    newScenePath = ProjectPathUtility.AddTimestamp(newScenePath);
                }

                mappingView.SaveScriptMappings(rootPath, originalScriptMappings);
                SaveSceneFile(newScenePath, linesToChange);
            });
        }
Example #18
0
        public void ListExtensionsMergeTest()
        {
            // arrange
            var firstList          = new List <string>();
            var secondList         = new List <string>();
            var expectedResultList = new List <string>();

            for (var i = 0; i < 100; i++)
            {
                var firstListItem  = Guid.NewGuid().ToString("N");
                var secondListItem = Guid.NewGuid().ToString("N");
                firstList.Add(firstListItem);
                secondList.Add(secondListItem);
                expectedResultList.Add(firstListItem);
                expectedResultList.Add(secondListItem);
            }
            var listsToMerge = new List <IEnumerable <string> >
            {
                firstList,
                secondList
            };
            // act
            var resultList = listsToMerge.Merge();

            // assert
            Assert.AreEqual(expectedResultList.Count, resultList.Count, "Expected amount of elements in result list is not present.");
            foreach (var item in expectedResultList)
            {
                Assert.IsTrue(resultList.Contains(item), "Expected element of result is not present there.");
            }
        }
        public void GotoDefinition(ILuaIntellisenseDocument document)
        {
            if (!CanGoto(document))
            {
                return;
            }

            Func <Expression, List <LuatValue.IReference> > func =
                expression =>
            {
                var definitions = new List <LuatValue.IReference>();
                foreach (LuatValue value in expression.ResolvedValues.Values)
                {
                    var variable = value as LuatVariable;
                    if (variable != null)
                    {
                        definitions.Merge(variable.Assignments.ToArray());
                    }
                }

                return(definitions);
            };

            GotoDefinitions("Goto definition", document, func);
        }
        /// <summary>
        /// Take two groups of sarif logs, and compute a sarif log containing the complete set of results,
        /// with status (compared to baseline) and various baseline-related fields persisted (e.x. work item links,
        /// ID, etc.
        /// </summary>
        /// <param name="previousLogs">Array of sarif logs representing the baseline run</param>
        /// <param name="currentLogs">Array of sarif logs representing the current run</param>
        /// <returns>A SARIF log with the merged set of results.</returns>
        public IEnumerable <SarifLog> Match(IEnumerable <SarifLog> previousLogs, IEnumerable <SarifLog> currentLogs)
        {
            Dictionary <string, List <Run> > runsByToolPrevious = GetRunsByTool(previousLogs);
            Dictionary <string, List <Run> > runsByToolCurrent  = GetRunsByTool(currentLogs);

            List <string> tools = runsByToolPrevious.Keys.Union(runsByToolCurrent.Keys).ToList();

            List <SarifLog> resultToolLogs = new List <SarifLog>();

            foreach (var key in tools)
            {
                IEnumerable <Run> baselineRuns = new Run[0];
                if (runsByToolPrevious.ContainsKey(key))
                {
                    baselineRuns = runsByToolPrevious[key];
                }
                IEnumerable <Run> currentRuns = new Run[0];

                if (runsByToolCurrent.ContainsKey(key))
                {
                    currentRuns = runsByToolCurrent[key];
                }

                resultToolLogs.Add(BaselineSarifLogs(baselineRuns, currentRuns));
            }

            return(new List <SarifLog> {
                resultToolLogs.Merge()
            });
        }
Example #21
0
    public void MergeSpike()
    {
        // the current list
        var currentList = new List <Employee>();

        currentList.Add(new Employee {
            Id = 154, Name = "George", Salary = 10000
        });
        currentList.Add(new Employee {
            Id = 233, Name = "Alice", Salary = 10000
        });
        // new list
        var newList = new List <Employee>();

        newList.Add(new Employee {
            Id = 154, Name = "George", Salary = 25000
        });
        newList.Add(new Employee {
            Id = 234, Name = "Bob", Salary = 30000
        });
        currentList.Merge(newList, (o, n) =>
        {
            if (o.Id != n.Id)
            {
                throw new ArgumentOutOfRangeException("Attempt to merge on mismatched IDs");
            }
            o.Name   = n.Name;
            o.Salary = n.Salary;
        });
        Assert.That(currentList.Count(), Is.EqualTo(2));
        Assert.That(currentList.First(c => c.Id == 154).Salary, Is.EqualTo(25000));
        Assert.That(currentList.Any(c => c.Id == 233), Is.False);
        Assert.That(currentList.First(c => c.Id == 234).Salary, Is.EqualTo(30000));
    }
Example #22
0
        /// <summary>
        /// take candle history for period
        /// взять историю свечек за период
        /// </summary>
        public List <Candle> GetCandleDataToSecurity(Security security, TimeFrameBuilder timeFrameBuilder,
                                                     DateTime startTime, DateTime endTime, DateTime actualTime)
        {
            int curStartTime = (int)(startTime - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;

            List <Candle> candles = new List <Candle>();

            while (true)
            {
                List <Candle> newCandles = _clientRest.GetCandles(security.Name, timeFrameBuilder.TimeFrameTimeSpan, curStartTime);

                if (newCandles == null ||
                    newCandles.Count == 0)
                {
                    break;
                }

                Candle lastCandle = newCandles[newCandles.Count - 1];

                candles.Merge(newCandles);

                if (newCandles.Count == 1)
                {
                    break;
                }

                curStartTime = (int)(lastCandle.TimeStart - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds;
            }

            return(candles);
        }
        public void MergePatterns(int testIndex, string input, string output, string outputExplanation, IntervalMergeBehavior behavior)
        {
            List <IInterval <int> > inputIntervals = GetIntervals(input).ToList();
            var slices = inputIntervals.Merge(behavior).OfType <Slice <int> >().ToArray();

            CompareInputAndOutput(inputIntervals, output, outputExplanation, slices);
        }
Example #24
0
        /// <summary>
        /// Generate a mapping of all scriptMappings in a project.
        /// Which means it creates a mapping between versions.
        /// </summary>
        /// <param name="oldIDs"></param>
        /// <param name="newIDs"></param>
        /// <returns></returns>
        public void MapAllClasses(List <ClassModel> oldIDs, List <ClassModel> newIDs,
                                  Action <List <ScriptMapping> > onComplete)
        {
            if (oldIDs == null || newIDs == null)
            {
                Debug.LogError("Old or new IDS are null. Cannot map without the old and new IDs");
            }

            // List<ScriptMapping> unmergedScriptMappings = MapAllClasses(oldIDs, newIDs);
            List <ScriptMapping> unmergedScriptMappings = MapAllClassesRecursiveParent(oldIDs, newIDs);


            List <ScriptMapping> unmappedScriptMapping = unmergedScriptMappings
                                                         .Where(script => script.HasBeenMapped == ScriptMapping.MappedState.NotMapped).ToList();

            if (unmappedScriptMapping.Count == 0)
            {
                onComplete(unmappedScriptMapping);
                return;
            }

            ThreadUtility.RunMainTask(() =>
            {
                MergeWizard mergeWizard = MergeWizard.CreateWizard(unmappedScriptMapping);
                mergeWizard.onComplete  = (mergedScriptMapping) =>
                {
                    List <ScriptMapping> completed = unmappedScriptMapping.Merge(mergedScriptMapping);
                    onComplete(completed);
                };
            });
        }
Example #25
0
        public void ExtensionsMethodForMergeTwoListWithLimitedThatGreaterThanLengthTest()
        {
            var left = new List <int> {
                0, 1, 2, 3, 4, 5
            };
            var right = new List <int> {
                6, 7, 8, 9
            };
            var target = left.Merge(right, 20).ToList();

            left.Count.ShouldBe(6);
            right.Count.ShouldBe(4);
            target.Count.ShouldBe(10);

            target[0].ShouldBe(0);
            target[1].ShouldBe(1);
            target[2].ShouldBe(2);
            target[3].ShouldBe(3);
            target[4].ShouldBe(4);
            target[5].ShouldBe(5);
            target[6].ShouldBe(6);
            target[7].ShouldBe(7);
            target[8].ShouldBe(8);
            target[9].ShouldBe(9);
        }
Example #26
0
            public async Task Draw(IUserMessage msg, int num = 1)
            {
                var channel = (ITextChannel)msg.Channel;
                var cards = AllDecks.GetOrAdd(channel.Guild, (s) => new Cards());
                var images = new List<Image>();
                var cardObjects = new List<Cards.Card>();
                if (num > 5) num = 5;
                for (var i = 0; i < num; i++)
                {
                    if (cards.CardPool.Count == 0 && i != 0)
                    {
                        try { await channel.SendMessageAsync("No more cards in a deck.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
                        break;
                    }
                    var currentCard = cards.DrawACard();
                    cardObjects.Add(currentCard);
                    using (var stream = File.OpenRead(Path.Combine(cardsPath, currentCard.ToString().ToLowerInvariant()+ ".jpg").Replace(' ','_')))
                        images.Add(new Image(stream));
                }
                MemoryStream bitmapStream = new MemoryStream();
                images.Merge().SaveAsPng(bitmapStream);
                bitmapStream.Position = 0;
                //todo CARD NAMES?
                var toSend = $"{msg.Author.Mention}";
                if (cardObjects.Count == 5)
                    toSend += $" drew `{Cards.GetHandValue(cardObjects)}`";

                await channel.SendFileAsync(bitmapStream, images.Count + " cards.jpg", toSend).ConfigureAwait(false);
            }
Example #27
0
        public void Query()
        {
            int?shopId = null;

            if (this.Shop != Globals.All)
            {
                shopId = Shop;
            }
            var query = this.LiquidateService.QueryShopLiquidate(shopId, LiquidateStates.Processing);

            // fill condition
            List = query.ToList(this, x => new ListLiquidate(x));
            var shopIds = List.Select(x => x.InnerObject.ShopId).ToArray();
            var shops   = ShopService.Query(new ShopRequest()
            {
                State = ShopStates.Normal
            }).ToList();

            Shop.Bind(shops.Select(x => new IdNamePair {
                Key = x.ShopId, Name = string.Format("{0} - {1}", x.Name, x.DisplayName)
            }).ToArray(), true);
            List.Merge(shops, (x, y) => x.InnerObject.ShopId == y.ShopId,
                       (x, y) =>
                       x.ShopName = (y.FirstOrDefault() == null ? "" : (y.FirstOrDefault().DisplayName)));
        }
        private static void OutputFile(List <string> samples, List <string> genes, Dictionary <string, Dictionary <string, TrackingItem> > map, Dictionary <string, SignificantItem> geneNameMap, Func <TrackingItem, string> fieldCount, string filename)
        {
            using (StreamWriter sw = new StreamWriter(filename))
            {
                sw.WriteLine("GeneId\tGene\tLocus\t" + samples.Merge("\t"));
                foreach (var gene in genes)
                {
                    var item = geneNameMap[gene];

                    sw.Write("{0}\t{1}\t{2}", item.Gene, item.GeneName, item.GeneLocation);
                    var genemap = map[gene];
                    foreach (var sample in samples)
                    {
                        if (genemap.ContainsKey(sample))
                        {
                            sw.Write("\t" + fieldCount(genemap[sample]));
                        }
                        else
                        {
                            sw.Write("\t");
                        }
                    }
                    sw.WriteLine();
                }
            }
        }
        public void AdditionOfManyLists()
        {
            List listA = new();

            listA.Add(1);
            listA.Add(2);
            listA.Add(3);
            List listB = new();

            listB.Add(4);
            listB.Add(5);
            listB.Add(6);

            List resultA = List.Merge(listA, listB, listA);
            List resultB = List.Merge(listA, listB, listA, listB, listA);

            for (int counter = 0; counter < listA.Count; counter++)
            {
                Assert.IsTrue(resultA[counter] == counter + 1);
            }

            for (int counter = 0; counter < listB.Count; counter++)
            {
                Assert.IsTrue(resultB [counter] == counter + 1);
            }
        }
Example #30
0
            public async Task Roll(IUserMessage umsg, int num)
            {
                var channel = (ITextChannel)umsg.Channel;

                if (channel == null)
                {
                    return;
                }

                var ordered = true;

                if (num < 1 || num > 30)
                {
                    await channel.SendMessageAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false);

                    return;
                }

                var rng = new NadekoRandom();

                var dice   = new List <Image>(num);
                var values = new List <int>(num);

                for (var i = 0; i < num; i++)
                {
                    var randomNumber = rng.Next(1, 7);
                    var toInsert     = dice.Count;
                    if (ordered)
                    {
                        if (randomNumber == 6 || dice.Count == 0)
                        {
                            toInsert = 0;
                        }
                        else if (randomNumber != 1)
                        {
                            for (var j = 0; j < dice.Count; j++)
                            {
                                if (values[j] < randomNumber)
                                {
                                    toInsert = j;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        toInsert = dice.Count;
                    }
                    dice.Insert(toInsert, GetDice(randomNumber));
                    values.Insert(toInsert, randomNumber);
                }

                var bitmap = dice.Merge();
                var ms     = new MemoryStream();

                bitmap.SaveAsPng(ms);
                ms.Position = 0;
                await channel.SendFileAsync(ms, "dice.png", $"{umsg.Author.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false);
            }
Example #31
0
        public IPlan GetPlan(IEngineConfiguration config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            ActionGraph                     graph          = new ActionGraph(config);
            IEnumerable <IAction>           actionsInOrder = graph.GetActionsInDependencyOrder();
            IObservable <IElement>          root           = System.Linq.Enumerable.Empty <IElement>().AsObservable();
            IList <IEnumerable <IElement> > finals         = new List <IEnumerable <IElement> >();

            foreach (IAction action in actionsInOrder)
            {
                if (graph.GetPrevActionsCount(action) > 0)
                {
                    var outputs = graph.GetPrevActions(action).Select(x => x.Output.AsEnumerable());
                    action.SetInput(outputs.Merge().AsObservable());
                }
                else
                {
                    action.SetInput(root);
                }
                if (graph.GetNextActionsCount(action) == 0)
                {
                    finals.Add(action.Output.AsEnumerable());
                }
            }

            return(new EnumerablePlan(finals.Merge()));
        }
Example #32
0
        public void AdditionOfManyLists()
        {
            List listA = new();

            listA.Add(1);
            listA.Add(2);
            listA.Add(3);
            List listB = new();

            listB.Add(4);
            listB.Add(5);
            listB.Add(6);

            int[] expectedA = { 1, 2, 3, 4, 5, 6, 1, 2, 3 };
            List  resultA   = List.Merge(listA, listB, listA);

            for (int counter = 0; counter < resultA.Count; counter++)
            {
                Assert.IsTrue(resultA[counter] == expectedA[counter]);
            }

            int[] expectedB = { 1, 2, 3, 4, 5, 6, 4, 5, 6, 1, 2, 3, 4, 5, 6 };
            List  resultB   = List.Merge(listA, listB, listB, listA, listB);

            for (int counter = 0; counter < resultB.Count; counter++)
            {
                Assert.IsTrue(resultB[counter] == expectedB[counter]);
            }
        }
Example #33
0
        public override Func<CommandEventArgs, Task> DoFunc() {
            Random r = new Random();
            return async e => {
                if (e.Args[0] == "") {
                    int num1 = r.Next(0, 10);
                    int num2 = r.Next(0, 10);

                    Image[] images;

                    if (num1 == 0 && num2 == 0 && r.Next(0, 2) == 1) {
                        images = new Image[3] { GetDice(1), GetDice(0), GetDice(0) };
                    } else {
                        images = new Image[2] { GetDice(num1), GetDice(num2) };
                    }

                    Bitmap bitmap = images.Merge();
                    await e.Channel.SendFile("dice.png", bitmap.ToStream(ImageFormat.Png));
                    return;
                } else {
                    try {
                        int num = int.Parse(e.Args[0]);
                        if (num < 1) num = 1;
                        if (num > 30) {
                            await e.Send("You can roll up to 30 dies at a time.");
                            num = 30;
                        }
                        List<Image> dices = new List<Image>(num);
                        List<int> values = new List<int>(num);
                        for (int i = 0; i < num; i++) {
                            int randomNumber = r.Next(1, 7);
                            int toInsert = dices.Count;
                            if (randomNumber == 6 || dices.Count == 0)
                                toInsert = 0;
                            else if (randomNumber != 1)
                                for (int j = 0; j < dices.Count; j++) {
                                    if (values[j] < randomNumber) {
                                        toInsert = j;
                                        break;
                                    }
                                }
                            dices.Insert(toInsert, GetDice(randomNumber));
                            values.Insert(toInsert, randomNumber);
                        }

                        Bitmap bitmap = dices.Merge();
                        await e.Send(values.Count + " Dies rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**");
                        await e.Channel.SendFile("dices.png", bitmap.ToStream(ImageFormat.Png));
                    } catch  {
                        await e.Send("Please enter a number of dices to roll.");
                        return;
                    }
                }
            };
        }
Example #34
0
        public void Add(string message, List<KeyValuePair<string, string>> options)
        {
            defaults.Add(new KeyValuePair<string, string>("apikey", this.ProwlConfig.ApiKey));

            List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();

            data.AddRange(options);
            data = data.Merge(defaults);
            data.Add(new KeyValuePair<string, string>("event", message));

            this._api("add", data);
        }
Example #35
0
        public static IList<Cms_Category> GetCategory(IList<Cms_Category> list)
        {
            IList<Cms_Category> result = new List<Cms_Category>();
            var a = from p in list where string.IsNullOrEmpty(p.Pguid) select p;

            IList<Cms_Category> rootlist = a.ToList<Cms_Category>();
            foreach (var item in rootlist)
            {
                result.Add(item);
                result = result.Merge(GetRecursionCateory(item.Fguid, list));
            }
            result.OrderBy(d => d.Categoryid);
            return result;
        }
Example #36
0
        public static IList<Base_Module> GetModule(IList<Base_Module> list)
        {
            IList<Base_Module> result = new List<Base_Module>();
            var a = from p in list where string.IsNullOrEmpty(p.Pguid) select p;

            IList<Base_Module> rootlist = a.ToList<Base_Module>();
            foreach (var item in rootlist)
            {
                result.Add(item);
                result = result.Merge(GetRecursionModule(item.Fguid, list));
            }
            result.OrderBy(d => d.Moduleno);
            return result;
        }
    public virtual IEnumerable<string> WriteToFile(string outputFile, List<FeatureItemGroup> features, List<string> samples, string removeNamePrefix)
    {
      using (StreamWriter sw = new StreamWriter(outputFile))
      {
        //sw.NewLine = Environment.NewLine;
        sw.WriteLine("Feature\tLocation\tSequence\t{0}", samples.Merge("\t"));
        foreach (var feature in features)
        {
          OutputCount(sw, feature, samples, MirnaConsts.NO_OFFSET, false, "", removeNamePrefix);
        }
      }

      string readFile = WriteReadCountTable(outputFile, features, samples);

      return new[] { outputFile, readFile };
    }
    private string GetKeywordSql()
    {
      if (Keywords.Length == 0)
      {
        return string.Empty;
      }

      var sqls = new List<string>();

      sqls.Add(GetSql("gse.title", this.Keywords));
      sqls.Add(GetSql("gse.summary", this.Keywords));
      sqls.Add(GetSql("gse.type", this.Keywords));
      sqls.Add(GetSql("gse.overall_design", this.Keywords));

      return sqls.Merge(" or ");
    }
Example #39
0
        public override Func<CommandEventArgs, Task> DoFunc() => async (e) =>
          {
              if (cards == null)
              {
                  await e.Send("Shuffling cards...");
                  cards = new Cards();
              }

              try
              {
                  int num = 1;
                  var isParsed = int.TryParse(e.GetArg("count"), out num);
                  if (!isParsed || num < 2)
                  {
                      var c = cards.DrawACard();
                      await e.Channel.SendFile(c.Name +".jpg",(Properties.Resources.ResourceManager.GetObject(c.Name) as Image).ToStream());
                      return;
                  }
                  if (num > 5)
                      num = 5;

                  List<Image> images = new List<Image>();
                  List<Cards.Card> cardObjects = new List<Cards.Card>();
                  for (int i = 0; i < num; i++)
                  {
                      if (cards.CardPool.Count == 0 && i != 0)
                      {
                          await e.Send("No more cards in a deck.");
                          break;
                      }
                      var currentCard = cards.DrawACard();
                      cardObjects.Add(currentCard);
                      images.Add(Properties.Resources.ResourceManager.GetObject(currentCard.Name) as Image);
                  }
                  Bitmap bitmap = images.Merge();
                  await e.Channel.SendFile(images.Count + " cards.jpg", bitmap.ToStream());
                  if (cardObjects.Count == 5)
                  {
                      await e.Send(Cards.GetHandValue(cardObjects));
                  }
              }
              catch (Exception ex)
              {
                  Console.WriteLine("Error drawing (a) card(s) " + ex.ToString());
              }
          };
Example #40
0
        private static IList<Cms_Category> GetRecursionCateory(string fguid, IList<Cms_Category> list)
        {
            IList<Cms_Category> result = new List<Cms_Category>();
            var a = from p in list where p.Pguid == fguid select p;
            IList<Cms_Category> sublist = a.ToList<Cms_Category>();

            char nbsp = (char)0xA0;
            foreach (var item in sublist)
            {
                int nodenolen = item.Categoryid.Length;
                string text = "∟" + item.Title.Trim();
                int len = nodenolen + text.Length;
                item.Title = text.PadLeft(len, nbsp);
                result.Add(item);
                result = result.Merge(GetRecursionCateory(item.Fguid, list));
            }
            return result;
        }
Example #41
0
        private static IList<Base_Module> GetRecursionModule(string fguid, IList<Base_Module> list)
        {
            IList<Base_Module> result = new List<Base_Module>();
            var a = from p in list where p.Pguid == fguid select p;
            IList<Base_Module> sublist = a.ToList<Base_Module>();

            char nbsp = (char)0xA0;
            foreach (var item in sublist)
            {
                int nodenolen = item.Moduleno.Length;
                string text = "∟" + item.Title.Trim();
                int len = nodenolen * 2 + text.Length-5;
                item.Title = text.PadLeft(len, nbsp);
                result.Add(item);
                result = result.Merge(GetRecursionModule(item.Fguid, list));
            }
            return result;
        }
Example #42
0
        private Func<CommandEventArgs, Task> DrawCardFunc() => async (e) =>
        {
            var cards = AllDecks.GetOrAdd(e.Server, (s) => new Cards());

            try
            {
                var num = 1;
                var isParsed = int.TryParse(e.GetArg("count"), out num);
                if (!isParsed || num < 2)
                {
                    var c = cards.DrawACard();
                    await e.Channel.SendFile(c.Name + ".jpg", (Properties.Resources.ResourceManager.GetObject(c.Name) as Image).ToStream()).ConfigureAwait(false);
                    return;
                }
                if (num > 5)
                    num = 5;

                var images = new List<Image>();
                var cardObjects = new List<Cards.Card>();
                for (var i = 0; i < num; i++)
                {
                    if (cards.CardPool.Count == 0 && i != 0)
                    {
                        await e.Channel.SendMessage("No more cards in a deck.").ConfigureAwait(false);
                        break;
                    }
                    var currentCard = cards.DrawACard();
                    cardObjects.Add(currentCard);
                    images.Add(Properties.Resources.ResourceManager.GetObject(currentCard.Name) as Image);
                }
                var bitmap = images.Merge();
                await e.Channel.SendFile(images.Count + " cards.jpg", bitmap.ToStream()).ConfigureAwait(false);
                if (cardObjects.Count == 5)
                {
                    await e.Channel.SendMessage($"{e.User.Mention} `{Cards.GetHandValue(cardObjects)}`").ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error drawing (a) card(s) " + ex.ToString());
            }
        };
Example #43
0
        public void TestMerge()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            var selRes = ed.Select("Выбери полилинии для объединения");
            if (selRes.Count==0) return;

            using (var t = db.TransactionManager.StartTransaction())
            {
                var pls = new List<Polyline>();
                foreach (var item in selRes)
                {
                    if (!item.IsValidEx()) continue;
                    var pl = item.GetObject(OpenMode.ForRead) as Polyline;
                    if (pl != null)
                    {
                        pls.Add(pl);
                    }
                }

                try
                {
                    var plMerged = pls.Merge();

                    var cs = db.CurrentSpaceId.GetObject(OpenMode.ForWrite) as BlockTableRecord;
                    cs.AppendEntity(plMerged);
                    t.AddNewlyCreatedDBObject(plMerged, true);
                    plMerged.ColorIndex = 5;
                }
                catch(System.Exception ex)
                {
                    Application.ShowAlertDialog(ex.ToString());
                }

                t.Commit();
            }
        }
    private static void WriteToFile(string fileName, List<RockhopperTranscriptResult> data, List<string> genes, Func<RockhopperTranscript, bool> significantFilter)
    {
      using (var sw = new StreamWriter(fileName))
      {
        sw.Write("Gene,Product");
        foreach (var d in data)
        {
          sw.Write(",{0}_RPKM_{1},{0}_RPKM_{2},{0}_log2({1}/{2}),{0}_qValue", d.ComparisonName, d.Group1, d.Group2);
        }
        sw.WriteLine(",Significant");

        foreach (var gene in genes)
        {
          sw.Write(gene);

          var synonym = gene.StringBefore(",");
          List<string> significant = new List<string>();
          foreach (var d in data)
          {
            if (d.UnpredictedMap.ContainsKey(synonym))
            {
              var entry = d.UnpredictedMap[synonym];
              sw.Write(",{0},{1},{2:0.00},{3}", entry.RPKM1, entry.RPKM2, entry.FoldChange, entry.Qvalue);
              if (significantFilter(entry))
              {
                significant.Add(d.ComparisonName);
              }
            }
            else
            {
              sw.Write(",0,0,0,1");
            }
          }

          sw.WriteLine(",{0}", significant.Merge(";"));
        }
      }
    }
Example #45
0
        /// <summary>
        /// Presents the parameter info prompt to the user
        /// </summary>
        /// <param name="syntaxEditor"></param>
        /// <returns></returns>
        private bool ShowIntelliPromptParameterInfoImmediate(ActiproSoftware.SyntaxEditor.SyntaxEditor syntaxEditor)
        {
            // Initialize the parameter info
            syntaxEditor.IntelliPrompt.ParameterInfo.Hide();
            syntaxEditor.IntelliPrompt.ParameterInfo.Info.Clear();
            syntaxEditor.IntelliPrompt.ParameterInfo.SelectedIndex = 0;

            // Get the compilation unit
            var cu = syntaxEditor.Document.SemanticParseData as CompilationUnit;
            if (cu == null)
                return false;

            // Move back to the last open bracket
            int caret = syntaxEditor.Caret.Offset;
            TextStream stream = syntaxEditor.Document.GetTextStream(caret);
            stream.GoToPreviousTokenWithID(LuatTokenId.OpenParenthesis);

            // Find the argument list the caret is within
            var arguments = cu.FindNodeRecursive<ArgumentList>(stream.Offset);
            ArgumentList next = arguments;
            while (null != next && false == arguments.InsideBrackets(caret))
            {
                arguments = next;
                next = next.FindAncestor<ArgumentList>();
            }

            if (arguments == null)
                return false;

            var call = arguments.ParentNode as FunctionCall;
            if (call == null)
                throw new Exception("ArgumentList does not have FunctionCall as parent");

            // Configure the parameter info
            var textRange = new TextRange(arguments.ListTextRange.StartOffset, arguments.ListTextRange.EndOffset + 1);

            IntelliPromptParameterInfo pi = syntaxEditor.IntelliPrompt.ParameterInfo;
            pi.ValidTextRange = textRange;
            pi.CloseDelimiterCharacter = ')';
            pi.UpdateParameterIndex();
            pi.HideOnParentFormDeactivate = true;

            var functions = new List<LuatValue>();
            foreach (var value in call.ResolvedFunctions)
            {
                if (false == value.Type is LuatTypeFunction)
                    continue;

                functions.Merge(value);

                pi.Info.Add(GetQuickInfoForFunctionCall(value, pi.ParameterIndex));
            }

            // Store the function types in the context
            pi.Context = functions.ToArray();

            // Show the parameter info
            pi.Show(caret);

            return false;
        }
Example #46
0
        public void TagListMerging()
        {
            IList<Tag> tl = new List<Tag>();
            tl.Add(new Tag("http://nu.nl", Tag.FHIRTAGNS, "v1"));
            tl.Add(new Tag("http://dan.nl", Tag.FHIRTAGNS, "v2"));

            IList<Tag> tl2 = new List<Tag>();
            tl2.Add(new Tag("http://nu.nl", Tag.FHIRTAGNS, "v3"));
            tl2.Add(new Tag("http://nooit.nl", Tag.FHIRTAGNS, "v4"));

            var result = tl.Merge(tl2);

            Assert.AreEqual(3, result.Count());
            Assert.AreEqual(1, result.FilterFhirTags().FindByTerm("http://nu.nl").Count());
            Assert.AreEqual("v3", result.FindByTerm("http://nu.nl", Tag.FHIRTAGNS).First().Label);
            Assert.AreEqual(1, result.FilterFhirTags().FindByTerm("http://nooit.nl").Count());
        }
Example #47
0
        private Func<CommandEventArgs, Task> RollFunc(bool ordered = true)
        {
            var r = new Random();
            return async e =>
            {
                var arg = e.Args[0]?.Trim();
                if (string.IsNullOrWhiteSpace(arg))
                {
                    var gen = r.Next(0, 101);

                    var num1 = gen / 10;
                    var num2 = gen % 10;

                    var imageStream = new Image[2] { GetDice(num1), GetDice(num2) }.Merge().ToStream(ImageFormat.Png);

                    await e.Channel.SendFile("dice.png", imageStream).ConfigureAwait(false);
                    return;
                }
                Match m;
                if ((m = dndRegex.Match(arg)).Length != 0)
                {
                    int n1;
                    int n2;
                    if (int.TryParse(m.Groups["n1"].ToString(), out n1) &&
                        int.TryParse(m.Groups["n2"].ToString(), out n2) &&
                        n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0)
                    {
                        var arr = new int[n1];
                        for (int i = 0; i < n1; i++)
                        {
                            arr[i] = r.Next(1, n2 + 1);
                        }
                        var elemCnt = 0;
                        await e.Channel.SendMessage($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false);
                    }
                    return;
                }
                try
                {
                    var num = int.Parse(e.Args[0]);
                    if (num < 1) num = 1;
                    if (num > 30)
                    {
                        await e.Channel.SendMessage("You can roll up to 30 dice at a time.").ConfigureAwait(false);
                        num = 30;
                    }
                    var dices = new List<Image>(num);
                    var values = new List<int>(num);
                    for (var i = 0; i < num; i++)
                    {
                        var randomNumber = r.Next(1, 7);
                        var toInsert = dices.Count;
                        if (ordered)
                        {
                            if (randomNumber == 6 || dices.Count == 0)
                                toInsert = 0;
                            else if (randomNumber != 1)
                                for (var j = 0; j < dices.Count; j++)
                                {
                                    if (values[j] < randomNumber)
                                    {
                                        toInsert = j;
                                        break;
                                    }
                                }
                        }
                        else {
                            toInsert = dices.Count;
                        }
                        dices.Insert(toInsert, GetDice(randomNumber));
                        values.Insert(toInsert, randomNumber);
                    }

                    var bitmap = dices.Merge();
                    await e.Channel.SendMessage(values.Count + " Dice rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**").ConfigureAwait(false);
                    await e.Channel.SendFile("dice.png", bitmap.ToStream(ImageFormat.Png)).ConfigureAwait(false);
                }
                catch
                {
                    await e.Channel.SendMessage("Please enter a number of dice to roll.").ConfigureAwait(false);
                }
            };
        }
Example #48
0
        /// <summary>
        /// Populates the warnings for each compilation unit registered with the database
        /// </summary>
        private void DoProcessWarnings()
        {
            lock (this)
            {
                // Remove warnings that are created from this function
                foreach (LuatScript script in m_scripts)
                {
                    if (script.CU == null)
                        continue;

                    script.CU.ClearWarnings(WarningType.UnresolvedVariable);
                    script.CU.ClearWarnings(WarningType.MixedType);
                    script.CU.ClearWarnings(WarningType.UnknownType);

                    foreach (Expression expression in script.UnresolvedExpressions)
                    {
                        var variable = expression as VariableExpression;
                        if (variable != null)
                        {
                            expression.AddWarning(script, WarningType.UnresolvedVariable, "Unknown variable '" + variable.Name.Text + "'");
                            continue;
                        }

                        var index = expression as IndexExpression;
                        if ((index != null) && (index.RHS != null))
                        {
                            index.RHS.AddWarning(script, WarningType.UnresolvedVariable, "Unknown index '" + index.RHS.DisplayText + "'");
                            continue;
                        }
                    }
                }

                foreach (LuatVariable variable in m_unresolvedVariableTypes)
                {
                    var types = new List<LuatType>();
                    foreach (LuatValue assignment in variable.ValueAssignments)
                    {
                        types.Merge(null != assignment ? assignment.Type : LuatTypeUnknown.Instance);
                    }

                    int typeCount = types.Count;
                    if (typeCount > 1)
                    {
                        var sb = new StringBuilder();
                        sb.Append("Assignment of different types ");
                        sb.Append("( ");
                        sb.Append(types.ToArray().ToCommaSeperatedList(type => type.ToString()));
                        sb.Append(" )");

                        foreach (LuatValue.IReference assignment in variable.Assignments)
                        {
                            string warning = string.Format(sb.ToString());
                            assignment.AddWarning(WarningType.MixedType, warning);
                        }
                    }

                    //                 foreach ( LuatValue.IReference reference in variable.References )
                    //                 {
                    //                     reference.AddWarning( WarningType.UnknownType, "Unknown type '" + reference.DisplayText + "'" );
                    //                 }
                }
            }
        }
Example #49
0
        public void GotoReference(ILuaIntellisenseDocument document)
        {
            if (!CanGoto(document))
                return;

            Func<Expression, List<LuatValue.IReference>> func =
                expression =>
                {
                    var definitions = new List<LuatValue.IReference>();
                    foreach (LuatValue value in expression.ResolvedValues.Values)
                    {
                        definitions.Merge(value.References.ToArray());
                    }

                    return definitions;
                };

            GotoDefinitions("Goto reference", document, func);
        }
    protected static string WriteReadCountTable(string outputFile, List<FeatureItemGroup> features, List<string> samples)
    {
      var readFile = Path.ChangeExtension(outputFile, ".read.count");
      using (var sw = new StreamWriter(readFile))
      {
        var reads = (from feature in features
                     from a in feature.GetAlignedLocations()
                     select a.Parent).Distinct().ToGroupDictionary(l => l.Sequence);

        var sequences = (from read in reads
                         orderby read.Value.Sum(l => l.QueryCount) descending
                         select read.Key).ToArray();

        sw.WriteLine("Sequence\t" + samples.Merge("\t"));
        foreach (var seq in sequences)
        {
          sw.Write(seq);
          var dic = reads[seq];
          foreach (var sample in samples)
          {
            var sampleSam = dic.FirstOrDefault(l => l.Sample.Equals(sample));
            if (sampleSam == null)
            {
              sw.Write("\t");
            }
            else
            {
              sw.Write("\t" + sampleSam.QueryCount.ToString());
            }
          }
          sw.WriteLine();
        }
      }

      return readFile;
    }
Example #51
0
        /// <summary>
        /// GetElementByTagName
        /// </summary>
        /// <param name="SourceHtml">Html代码</param>
        /// <param name="TagName">标签名称</param>
        /// <returns>返回标签的OuterHtml</returns>
        public static List<string> GetElementByTagName(this string SourceHtml, string TagName)
        {
            string pattern = string.Format(@"<{0}[^>]*>(?<key>[\w\W]*(((?'Open'<{0}[^>]*>)[\w\W]*)+((?'-Open'</{0}>)[\w\W]*)+)*(?(Open)(?!)))</{0}>", TagName);
            List<string> result = new List<string>();
            List<string> first_result = GetMatch(SourceHtml, pattern);
            foreach (string sub in first_result)
            {
                if (sub.CountString(string.Format("</{0}>", TagName)) > 0)
                {
                    result.Merge(GetElementByTagName(sub, TagName));
                }
            }
            result = result.Merge(first_result);

            return result;
        }
Example #52
0
    public override IEnumerable<string> Process()
    {
      var result = new List<string>();

      Dictionary<string, BarInfo> barMap;

      barMap = new Dictionary<string, BarInfo>();
      foreach (var tumor in _options.TumorTypes)
      {
        var curMap = TCGAUtils.GetBarcodeFileMap(_options.TCGADirectory,
          _options.GetTechnology(), tumor, _options.Platforms, _options.GetTCGASampleCodes().ToArray());

        foreach (var v in curMap)
        {
          barMap[GetSampleKey(tumor, v.Key)] = v.Value;
        }
      }

      var headers = new List<string>();
      var clindata = new Dictionary<string, IAnnotation>();
      foreach (var tumor in _options.TumorTypes)
      {
        ReadClinData(clindata, tumor, headers);
      }
      Console.WriteLine("{0} patient clinical information readed", clindata.Count);

      List<string> noclinical = new List<string>();
      var keyvalues = barMap.ToList();
      foreach (var bm in keyvalues)
      {
        if (!clindata.ContainsKey(GetSampleKey(GetTumorType(bm.Key), bm.Value.Paticipant)))
        {
          noclinical.Add(bm.Key);

          Console.Error.WriteLine(string.Format("Cannot find clinical data for patient {0}", bm.Value.Paticipant));
          if (_options.WithClinicalInformationOnly)
          {
            barMap.Remove(bm.Key);
          }
        }
      }

      Progress.SetMessage("Reading data ...");
      Func<double, double> getValue;
      var valueMap = GetData(barMap, out getValue);

      var genes = GetCommonGenes(valueMap);
      var samples = valueMap.Keys.OrderBy(m => m).ToList();

      Progress.SetMessage("Saving data ...");

      result.Add(_options.OutputFile);
      result.Add(_options.DesignFile);
      if (_options.TumorTypes.Count > 1)
      {
        using (var sw = new StreamWriter(_options.OutputFile))
        {
          sw.WriteLine("Gene\t{0}", samples.Merge("\t"));
          foreach (var gene in genes)
          {
            sw.Write(gene);
            foreach (var sample in samples)
            {
              sw.Write("\t{0}", getValue(valueMap[sample][gene]));
            }
            sw.WriteLine();
          }
        }

        using (var sw = new StreamWriter(_options.DesignFile))
        {
          sw.Write("Sample\tBarcode\tPatient\tTumorType\tPlatform\tSampleType\tSampleTypeDescription");
          if (headers.Count > 0)
          {
            sw.WriteLine("\t{0}", headers.Merge("\t"));
          }
          else
          {
            sw.WriteLine();
          }

          foreach (var entry in barMap)
          {
            var tumor = GetTumorType(entry.Key);
            var type = TCGASampleCode.Find(entry.Value.Sample);
            sw.Write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", entry.Key, entry.Value.BarCode, entry.Value.Paticipant, tumor, entry.Value.Platform, type.ShortLetterCode,
              type.Definition);
            var key = GetSampleKey(tumor, entry.Value.Paticipant);
            var vdata = clindata.ContainsKey(key) ? clindata[key] : new Annotation();
            foreach (var header in headers)
            {
              if (vdata.Annotations.ContainsKey(header))
              {
                sw.Write("\t{0}", vdata.Annotations[header]);
              }
              else
              {
                sw.Write("\t");
              }
            }
            sw.WriteLine();
          }
        }
      }
      else
      {
        using (var sw = new StreamWriter(_options.OutputFile))
        {
          sw.WriteLine("Gene\t{0}", (from s in samples select s.StringAfter("_")).Merge("\t"));
          foreach (var gene in genes)
          {
            sw.Write(gene);
            foreach (var sample in samples)
            {
              sw.Write("\t{0}", getValue(valueMap[sample][gene]));
            }
            sw.WriteLine();
          }
        }

        using (var sw = new StreamWriter(_options.DesignFile))
        {
          sw.Write("Sample\tBarcode\tPatient\tTumorType\tPlatform\tSampleType\tSampleTypeDescription");
          if (headers.Count > 0)
          {
            sw.WriteLine("\t{0}", headers.Merge("\t"));
          }
          else
          {
            sw.WriteLine();
          }

          foreach (var entry in barMap)
          {
            var tumor = _options.TumorTypes.First();
            var type = TCGASampleCode.Find(entry.Value.Sample);
            sw.Write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", entry.Key.StringAfter("_"), entry.Value.BarCode, entry.Value.Paticipant, tumor, entry.Value.Platform, type.ShortLetterCode,
              type.Definition);
            var key = GetSampleKey(tumor, entry.Value.Paticipant);
            var vdata = clindata.ContainsKey(key) ? clindata[key] : new Annotation();
            foreach (var header in headers)
            {
              if (vdata.Annotations.ContainsKey(header))
              {
                sw.Write("\t{0}", vdata.Annotations[header]);
              }
              else
              {
                sw.Write("\t");
              }
            }
            sw.WriteLine();
          }
        }

        var clinicalOptions = new TCGAClinicalInformationBuilderOptions()
        {
          ClinicalFile = TCGAUtils.GetClinicPatientFile(_options.TCGADirectory, _options.TumorTypes.First()),
          DataFile = _options.OutputFile,
          ThrowException = false,
        };
        result.AddRange(new TCGAClinicalInformationBuilder(clinicalOptions) { Progress = this.Progress }.Process());
      }
      Progress.End();

      if (noclinical.Count == 0)
      {
        return result.ToArray();
      }
      else
      {
        return new[] { string.Format("There are {0} samples without patient information:\n  {1}\n\nResult have been saved to:\n  {2}", noclinical.Count, noclinical.Merge("\n  "), result.Merge("\n  ")) };
      }
    }
Example #53
0
        public void GotoDefinition(ILuaIntellisenseDocument document)
        {
            if (!CanGoto(document))
                return;

            Func<Expression, List<LuatValue.IReference>> func =
                expression =>
                {
                    var definitions = new List<LuatValue.IReference>();
                    foreach (LuatValue value in expression.ResolvedValues.Values)
                    {
                        var variable = value as LuatVariable;
                        if (variable != null)
                            definitions.Merge(variable.Assignments.ToArray());
                    }

                    return definitions;
                };

            GotoDefinitions("Goto definition", document, func);
        }
Example #54
0
        private IObservable<EventPattern<FileSystemEventArgs>> GenerateWatchers()
        {
            var observables = new List<IObservable<EventPattern<FileSystemEventArgs>>>();
            foreach (Directory directory in _configuration.Watch)
            {
                if (!System.IO.Directory.Exists(directory.Path)) continue;
                var watcher = new FileSystemWatcher(directory.Path)
                {
                    IncludeSubdirectories = directory.IncludeSubDirs,
                    EnableRaisingEvents = false
                };
                _watchers.Add(watcher);
                foreach (var listenerType in directory.GetListenerTypes())
                {
                    IObservable<EventPattern<FileSystemEventArgs>> observable;
                    switch (listenerType)
                    {
                        case ListenerType.Created:
                            observable =
                                Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
                                    ev => watcher.Created += ev, ev => watcher.Created -= ev);
                            observables.Add(observable);
                            break;
                        case ListenerType.Changed:
                            observable = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
                                ev => watcher.Changed += ev, ev => watcher.Changed -= ev);
                            observables.Add(observable);
                            break;
                        case ListenerType.Deleted:
                            observable = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
                                ev => watcher.Deleted += ev, ev => watcher.Deleted -= ev);
                            observables.Add(observable);
                            break;
                        case ListenerType.Renamed:
                            var renamedObservable = Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>(
                                ev => watcher.Renamed += ev, ev => watcher.Renamed -= ev);
                            observables.Add(
                                renamedObservable.Select(
                                    evpat => new EventPattern<FileSystemEventArgs>(evpat.Sender, evpat.EventArgs)));
                            break;
                    }
                }
            }

            var mergedObservables = observables.Merge();
            return mergedObservables;
        }
Example #55
0
    public override IEnumerable<string> Process()
    {
      var files = GetFiles(_options.InputDir);

      Func<string, string> nameFunc;
      if (string.IsNullOrEmpty(_options.NamePattern))
      {
        nameFunc = Path.GetFileNameWithoutExtension;
      }
      else
      {
        nameFunc = n =>
        {
          var match = Regex.Match(n, _options.NamePattern);
          if (match.Success)
          {
            var values = new List<string>();
            for (int i = 1; i < match.Groups.Count; i++)
            {
              values.Add(match.Groups[i].Value);
            }
            return values.Merge("");
          }
          else
          {
            return n;
          }
        };
      };

      var map = files.GroupBy(m =>
      {
        if (_options.Recursion && _options.UseDirName)
        {
          return nameFunc(Path.GetFileName(Path.GetDirectoryName(m)));
        }
        else
        {
          return nameFunc(Path.GetFileName(m));
        }
      }).ToDictionary(n => n.Key);


      var names = (from k in map.Keys
                   orderby k
                   select k).ToList();

      if (_options.AutoFill)
      {
        var nameMap = names.ToDictionary(l => l, l => l);
        Regex number = new Regex(@"(.+?)(\d+)$");

        var numbers = (from n in names
                       let m = number.Match(n)
                       where m.Success
                       select new { OldName = n, Prefix = m.Groups[1].Value, Value = m.Groups[2].Value }).ToList();

        var numberMax = numbers.Max(l => l.Value.Length);
        foreach (var num in numbers)
        {
          if (num.Value.Length != numberMax)
          {
            nameMap[num.OldName] = num.Prefix + new string('0', numberMax - num.Value.Length) + num.Value;
          }
        }

        map = map.ToDictionary(l => nameMap[l.Key], l => l.Value);
        names = (from k in map.Keys
                 orderby k
                 select k).ToList();
      }

      if (File.Exists(_options.MapFile))
      {
        Progress.SetMessage("Reading name map from {0} ...", _options.MapFile);
        var namemap = new MapDataReader(0, 1).ReadFromFile(_options.MapFile);
        map = map.ToDictionary(l => namemap.Data[l.Key].Value, l => l.Value);
        names = (from k in map.Keys
                 orderby k
                 select k).ToList();
      }

      var result = new List<string> { "files => {" };
      foreach (var name in names)
      {
        result.Add(string.Format("  \"{0}\" => [{1}],", name, (from l in map[name] select '"' + Path.GetFullPath(l) + '"').Merge(", ")));
      }
      result.Add("},");

      if (string.IsNullOrEmpty(_options.GroupPattern))
        return result;

      var groupmap = names.GroupBy(n =>
      {
        var match = Regex.Match(n, _options.GroupPattern);
        if (!match.Success)
        {
          throw new Exception(string.Format("Cannot find pattern {0} in file {1}", _options.NamePattern, n));
        }


        var values = new List<string>();
        for (var i = 1; i < match.Groups.Count; i++)
        {
          values.Add(match.Groups[i].Value);
        }
        return values.Merge("");

      });

      var gnames = (from k in groupmap
                    orderby k.Key
                    select k).ToList();

      result.Add("groups => {");
      foreach (var name in gnames)
      {
        result.Add(string.Format("  \"{0}\" => [{1}],", name.Key, (from l in name
                                                                   orderby l
                                                                   select '"' + l + '"').Merge(", ")));
      }
      result.Add("},");

      return result;
    }
Example #56
0
 private IObservable<Unit> CancelInternal() {
     var list = new List<IObservable<GameLockChanged>>();
     foreach (var l in _list) {
         l.Value.Cancel();
         _lockChanged.OnNext(new GameLockChanged(l.Key, true, false));
         list.Add(GenerateObservable(l.Key));
     }
     return list.Any() ? list.Merge().Select(x => Unit.Value) : Observable.Return(Unit.Value);
 }
Example #57
0
        public async Task Hearthstone(IUserMessage umsg, [Remainder] string name = null)
        {
            var channel = (ITextChannel)umsg.Channel;
            var arg = name;
            if (string.IsNullOrWhiteSpace(arg))
            {
                await channel.SendMessageAsync("💢 `Please enter a card name to search for.`").ConfigureAwait(false);
                return;
            }

            if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey))
            {
                await channel.SendMessageAsync("💢 `Bot owner didn't specify MashapeApiKey. You can't use this functionality.`").ConfigureAwait(false);
                return;
            }

            await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false);
            string response = "";
            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Clear();
                http.DefaultRequestHeaders.Add("X-Mashape-Key", NadekoBot.Credentials.MashapeKey);
                response = await http.GetStringAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}")
                                        .ConfigureAwait(false);
                try
                {
                    var items = JArray.Parse(response).Shuffle().ToList();
                    var images = new List<Image>();
                    if (items == null)
                        throw new KeyNotFoundException("Cannot find a card by that name");
                    foreach (var item in items.Where(item => item.HasValues && item["img"] != null).Take(4))
                    {
                        using (var sr = await http.GetStreamAsync(item["img"].ToString()))
                        {
                            var imgStream = new MemoryStream();
                            await sr.CopyToAsync(imgStream);
                            imgStream.Position = 0;
                            images.Add(new Image(imgStream));
                        }
                    }
                    string msg = null;
                    if (items.Count > 4)
                    {
                        msg = "⚠ Found over 4 images. Showing random 4.";
                    }
                    var ms = new MemoryStream();
                    images.Merge().SaveAsPng(ms);
                    ms.Position = 0;
                    await channel.SendFileAsync(ms, arg + ".png", msg).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    await channel.SendMessageAsync($"💢 Error {ex.Message}").ConfigureAwait(false);
                }
            }
        }
Example #58
0
        private static bool CanRenameVariable(ILuaIntellisenseDocument document, out VariableExpression expression, out List<LuatValue.IReference> definitions)
        {
            expression = null;
            definitions = null;

            if (!CanGoto(document))
                return false;

            if (document.SyntaxEditorControl == null)
                return false;

            var se = (ActiproSoftware.SyntaxEditor.SyntaxEditor)document.SyntaxEditorControl;
            if ((se.SelectedView == null) || (se.SelectedView.Selection == null))
                return false;

            expression = GetExpressionAt(se.Document, se.SelectedView.Selection.StartOffset) as VariableExpression;
            if (expression == null)
                return false;

            definitions = new List<LuatValue.IReference>();
            foreach (LuatValue value in expression.ResolvedValues.Values)
            {
                var variable = value.As<LuatVariable>();
                if (variable != null)
                    definitions.Merge(variable.References.ToArray());
            }

            return definitions.Count > 0;
        }
    public override IEnumerable<string> WriteToFile(string outputFile, List<FeatureItemGroup> features, List<string> samples, string removeNamePrefix)
    {
      var header = "Feature\tLocation\tSequence\t" + samples.Merge("\t");

      var dicList = new List<Dictionary<string, double>>();
      var ntaList = new List<string[]>();
      var isomiRList = new List<string[]>();
      var ntaIsomiRList = new List<string[]>();
      foreach (var featureGroup in features)
      {
        var dic = new Dictionary<string, double>();
        var ntas = new HashSet<string>();
        var isomiRs = new HashSet<string>();
        var ntaIsomiRs = new HashSet<string>();
        foreach (var feature in featureGroup)
        {
          foreach (var featureLoc in feature.Locations)
          {
            foreach (var samLoc in featureLoc.SamLocations)
            {
              var ntaKey = GetNTAKey(samLoc.SamLocation.Parent.ClippedNTA);
              var isomiRkey = GetIsomiRKey(samLoc.Offset);
              var ntaIsomiRKey = GetNTAIsomiRKey(samLoc.SamLocation.Parent.ClippedNTA, samLoc.Offset);

              ntas.Add(ntaKey);
              isomiRs.Add(isomiRkey);
              ntaIsomiRs.Add(ntaIsomiRKey);

              var samCount = samLoc.SamLocation.Parent.GetEstimatedCount();

              string sampleKey = samLoc.SamLocation.Parent.Sample;
              AddCount(dic, sampleKey, samCount);

              var sampleNTAKey = GetSampleKey(samLoc.SamLocation.Parent.Sample, ntaKey);
              AddCount(dic, sampleNTAKey, samCount);

              string sampleIsomiRKey = GetSampleKey(samLoc.SamLocation.Parent.Sample, isomiRkey);
              AddCount(dic, sampleIsomiRKey, samCount);

              var sampleNTAIsomiRKey = GetSampleKey(samLoc.SamLocation.Parent.Sample, ntaIsomiRKey);
              AddCount(dic, sampleNTAIsomiRKey, samCount);
            }
          }
        }

        dicList.Add(dic);
        ntaList.Add(ntas.OrderBy(m => m).ToArray());
        isomiRList.Add(isomiRs.OrderBy(m => m).ToArray());
        ntaIsomiRList.Add(ntaIsomiRs.OrderBy(m => m).ToArray());
      }

      var ntaFile = Path.ChangeExtension(outputFile, ".NTA.count");
      var isomiRFile = Path.ChangeExtension(outputFile, ".isomiR.count");
      var ntaIsomiRFile = Path.ChangeExtension(outputFile, ".isomiR_NTA.count");
      using (var sw = new StreamWriter(outputFile))
      using (var swNTA = new StreamWriter(ntaFile))
      using (var swIsomiR = new StreamWriter(isomiRFile))
      using (var swNTAIsomiR = new StreamWriter(ntaIsomiRFile))
      {
        sw.WriteLine(header);
        swNTA.WriteLine(header);
        swIsomiR.WriteLine(header);
        swNTAIsomiR.WriteLine(header);

        for (int i = 0; i < features.Count; i++)
        {
          var feature = features[i];
          var dic = dicList[i];
          var ntas = ntaList[i];
          var isomiRs = isomiRList[i];
          var ntaIsomiRs = ntaIsomiRList[i];

          var featureName = (from f in feature select f.Name.StringAfter(removeNamePrefix)).Merge(";");
          var featureSequences = (from l in feature select l.Sequence).ToArray();
          var sequence = featureSequences.Distinct().Count() == 1 ? featureSequences.First() : featureSequences.Merge(";");
          var featureLocations = feature.DisplayLocations;

          WriteCounts(samples, sw, dic, new[] { string.Empty }, featureName, sequence, featureLocations);
          WriteCounts(samples, swNTA, dic, ntas, featureName, sequence, featureLocations);
          WriteCounts(samples, swIsomiR, dic, isomiRs, featureName, sequence, featureLocations);
          WriteCounts(samples, swNTAIsomiR, dic, ntaIsomiRs, featureName, sequence, featureLocations);
        }
      }

      string readFile = WriteReadCountTable(outputFile, features, samples);

      return new[] { outputFile, ntaFile, isomiRFile, ntaIsomiRFile, readFile };
    }
Example #60
0
        // Returns a list of all direct and indirect assignments of this variable
        protected IReference[] GetAssignmentsRecursive(ref HashSet<LuatValue> visited)
        {
            visited.Add(this);

            var assignments = new List<IReference>();
            assignments.AddRange(Assignments);

            foreach (IReference reference in Assignments)
            {
                var variable = reference.Value as LuatVariable;
                if (variable != null && visited.Contains(variable))
                    continue;

                if (variable != null)
                    assignments.Merge(variable.GetAssignmentsRecursive(ref visited));
            }

            return assignments.ToArray();
        }