Пример #1
0
        public static void MaxEachGroup()
        {
            /*
             * For each building category,
             * select a tuple with (Category, MostExpensiveBuildings)
             * with MostExpensiveBuildings being the list of all buildings whose price is equal
             * to the maximum price for the category
             */

            IEnumerable <Building> buildings = DataSource.Buildings;

            IEnumerable <(string Category, IEnumerable <Building> MostExpensiveBuildings)> categories =
                from b in buildings
                group b by b.Category into g
                let maxPrice = g.Max(p => p.Price)
                               select(Category: g.Key, MostExpensiveBuildings: g.Where(p => p.Price == maxPrice));

            foreach (var c in categories)
            {
                Console.WriteLine($"Category: {c.Category}");
                foreach (var p in c.MostExpensiveBuildings)
                {
                    Console.WriteLine($"\t{p}");
                }
            }
        }
            static void Born(Pawn pawn, Pawn parent)
            {
                if (!betterPawnControl_Birth)
                {
                    return;
                }
                if (!(BpcAnimalLinks?.GetValue(null) is IList animalLinks))
                {
                    return;
                }

                var pawnLinks = (from object animalLink in animalLinks
                                 let animal = (Pawn)AccessTools.Field(BpcAnimalLinkType, "animal").GetValue(animalLink)
                                              let isObedient = pawn.training?.HasLearned(TrainableDefOf.Obedience)
                                                               where animal == parent
                                                               select Activator.CreateInstance(
                                     BpcAnimalLinkType,
                                     (int)AccessTools.Field(BpcAnimalLinkType, "zone").GetValue(animalLink),
                                     pawn,
                                     isObedient == true ? (Pawn)AccessTools.Field(BpcAnimalLinkType, "master").GetValue(animalLink) : null,
                                     (Area)AccessTools.Field(BpcAnimalLinkType, "area").GetValue(animalLink),
                                     pawn.playerSettings?.followDrafted ?? default,
                                     pawn.playerSettings?.followFieldwork ?? default,
                                     (int)AccessTools.Field(BpcAnimalLinkType, "mapId").GetValue(animalLink))).ToList();

                foreach (var pawnLink in pawnLinks)
                {
                    animalLinks.Add(pawnLink);
                }
            }
Пример #3
0
    private Task pathlist(string project, HttpContext context)
    {
        var apilist = getApiNames();
        var spaUser = context.Items["spaUser"] as SpaUser;
        // e.Enforce(sub, obj, act)
        var e          = ConfigHelper.createEnforcer();
        var folderList = Directory.GetDirectories(ConfigHelper.WebRootPath);
        var list       = (from d in folderList
                          let f = new DirectoryInfo(d)
                                  let indexHtml = Path.Combine(f.FullName, "index.html")
                                                  let auth = spaUser !.Supper || (apilist.Any(y => e.Auth(spaUser.LoginName, f.Name, y.url)))
                                                             let last = GetFirstBackup(f.Name)
                                                                        where File.Exists(indexHtml) && f.Name != "admin" && f.Name != "_backup_" && auth
                                                                        select new SpaModel
        {
            Title = f.Name,
            DateTime = f.LastWriteTime,
            Time = f.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
            Rollback = last.Item2.Item1,
            User = last.Item1.Item2
        }
                          )
                         .ToList();

        context.Response.ContentType = "application/json";
        return(context.Response.WriteAsync(JsonConvert.SerializeObject(list)));
    }
Пример #4
0
        public async Task Test_ParallelAndLet()
        {
            var sw = Stopwatch.StartNew();

            var result = await
                         from one in Get1().AsParallel()

                         let oneA = one

                                    from two in Get2().AsParallel()
                                    from freeStr in Get3Str().AsParallel()

                                    let free = int.Parse(freeStr)//Intermediate expr

                                               from oneB in Get1().AsParallel()
                                               from twoA in Get2().AsParallel()

                                               select one + oneA + two + int.Parse(freeStr) + free + oneB + twoA;


            sw.Stop();

            Assert.AreEqual(13, result);
            Assert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            Assert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }
Пример #5
0
        public virtual double GetGPA(char letterGrade, StudentType studentType)
        {
            let added = 0;

            if ((studentType == StudentType.Honors || studentType == StudentType.DualEnrolled) &&
                IsWeighted == true)
            {
                added = added + 1;
            }
            switch (letterGrade)
            {
            case 'A':
                return(4 + added);

            case 'B':
                return(3 + added);

            case 'C':
                return(2 + added);

            case 'D':
                return(1 + added);

            case 'F':
                return(0 + added);
            }
            return(0);
        }
Пример #6
0
        private InstanceProducer BuildInstanceProducerForMetadataList(Type enumerableOfProducersType)
        {
            Type metadataType = enumerableOfProducersType.GetGenericArguments()[0];
            Type serviceType  = metadataType.GetGenericArguments()[0];

            var collection = this.container.GetAllInstances(serviceType) as IContainerControlledCollection;

            if (collection is null)
            {
                // This exception might not be expressive enough. If GetAllInstances succeeds, but the
                // returned type is not an IContainerControlledCollection, it likely means the collection is
                // container uncontrolled.
                this.container.ThrowMissingInstanceProducerException(serviceType);
            }

            IContainerControlledCollection metadataCollection =
                ControlledCollectionHelper.CreateContainerControlledCollection(metadataType, this.container);

            metadataCollection.AppendAll(
                from producer in collection !.GetProducers()
                let metadata                     = CreateMetadata(metadataType, producer)
                                         let reg = Lifestyle.Singleton.CreateRegistration(metadataType, metadata, this.container)
                                                   select ContainerControlledItem.CreateFromRegistration(reg));

            return(new InstanceProducer(
                       serviceType: enumerableOfProducersType,
                       registration: metadataCollection.CreateRegistration(enumerableOfProducersType, this.container)));
        }
Пример #7
0
    // 호출: DotNet.exe 3 5
    static void Main(string[] args)
    {
        let first  = Convert.ToInt32(args[0]);
        let second = Convert.ToInt32(args[1]);

        console.log(Sum(first, second));
    }
Пример #8
0
 static void Main()
 {
     using (C? x = new C() + from y in new[] { 1 }
            join z in new[] { 1 } on y equals z
            let s = y + z
                    select s is int? "" : null) { }
 }
        private void RunListEnchantmentBindings()
        {
            var query = from binding in Storage.ListEnchantmentBindings.AsParallel()
                        let resolvedList = binding.EdidList.Resolve(LinkCache)
                                           from entry in resolvedList.Entries.EmptyIfNull()
                                           let resolvedEntry = entry.Data !.Reference.TryResolve <TItem>(LinkCache)
                                                               where resolvedEntry != null
                                                               where !GetEnchantment(resolvedEntry).IsNull
                                                               where !GetTemplate(resolvedEntry).IsNull
                                                               where !GetEnchantmentExclusionList().IsExcluded(resolvedEntry)
                                                               let template = GetTemplate(resolvedEntry).Resolve(LinkCache)
                                                                              where GetEnchantment(template).IsNull
                                                                              from replacer in binding.Replacers
                                                                              where GetEnchantment(resolvedEntry).FormKey == replacer.EdidBase.FormKey
                                                                              group(replacer.EdidNew, template, resolvedEntry, entry, resolvedList) by resolvedList;

            var results = query.ToList();

            foreach (var listGroup in results)
            {
                var lo = Patch.LeveledItems.GetOrAddAsOverride(listGroup.Key);
                foreach (var entry in listGroup)
                {
                    var newArmor = CreateItemFromTemplate(entry.template, entry.resolvedEntry !,
                                                          new FormLink <IObjectEffectGetter>(entry.EdidNew.FormKey));
                    lo.Entries !.Add(new LeveledItemEntry
                    {
                        Data = new LeveledItemEntryData
                        {
                            Reference = new FormLink <IItemGetter>(newArmor),
                            Count     = entry.entry.Data !.Count,
                            Level     = entry.entry.Data !.Level
                        }
                    });
Пример #10
0
 int getTypeDefTableRecOwner (int methodDefIndex, TypeDefTableRec [] typeDefTable)
 { 
      let typeDefTableRecOwnerIndex = 
          typeDefTable |> Seq.tryFindIndex (fun typeDefRec -> 
                             //don't look in the pseudo class row
                             //but start with the 3rd row (if there)
                             if typeDefRec._index > 1 && typeDefRec.MethodList > uint16 (methodDefIndex) then true
Пример #11
0
 static Operator()
 {
     instance = ~
                from ctor in typeof(r).TryGetDefaultPrivateConstructor()
                let v = (r)ctor.Invoke(array <object>())
                        select v;
 }
Пример #12
0
        public async Task Test_SequentialAndLet()
        {
            var sw = Stopwatch.StartNew();

            var result = await
                         from one in Get1().AsParallel()

                         let oneA = one

                                    from two in Get2().AsParallel()
                                    from freeStr in Get3Str().AsParallel()

                                    let free = int.Parse(freeStr)                       //Intermediate expr

                                               from eight in  Add5(free).AsSequential() //Here all the previous results can be used

                                               from oneB in Get1().AsParallel()
                                               from twoA in Get2().AsParallel()

                                               from six in Add5(oneB).AsSequential()//Here all the previous results can be used

                                               select one + oneA + two + int.Parse(freeStr) + free + eight + oneB + twoA + six;


            sw.Stop();

            Assert.AreEqual(27, result);
            Assert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs * 3);
            Assert.Less(sw.ElapsedMilliseconds, TimeSlotMs * 3 + LagMs);
        }
Пример #13
0
 static Keyword()
 {
     instance = ~
                from ctor in typeof(k).TryGetDefaultPrivateConstructor()
                let v = (k)ctor.Invoke(array <object>())
                        select v;
 }
Пример #14
0
        private static IEnumerable <ValidatorUsage> AnalyzeDirectives(IEnumerable <Directive> directives, Func <string, string[]> getValidatorArgs, string fieldName = null, int?fieldIndex = null)
        {
            var defaultFields = fieldName == null ? ImmutableArray <string> .Empty : ImmutableArray.Create(fieldName);
            var fieldPrefix   = fieldName == null ? "" : fieldName + ".";

            return(from xx in directives.Select((d, i) => (i, d))
                   let d = xx.d
                           let dindex = xx.i
                                        where d.Name.StartsWith("validate") && d.Name.Length > "validate".Length
                                        let validatorName = char.ToLower(d.Name["validate".Length]) + d.Name.Substring("validate".Length + 1)

                                                            let args = getValidatorArgs(validatorName) ??
                                                                       throw new ValidationErrorException(ValidationErrors.CreateField(
                                                                                                              (fieldIndex == null ? Array.Empty <string>() : new[] { "fields", fieldIndex.ToString() }).Concat(new [] { "directives", dindex.ToString(), "name" }).ToArray(),
                                                                                                              $"Validator {validatorName} could not be found"
                                                                                                              ))

                                                                       let forFields = d.Args["forFields"] == null || args.Contains("forFields") ?
                                                                                       defaultFields :
                                                                                       d.Args["forFields"].Values <string>().Select(a => fieldPrefix + a).ToImmutableArray()

                                                                                       let argValues = args.Select(a => (a, val: d.Args[a]))
                                                                                                       .Where(a => a.val != null)
                                                                                                       .ToDictionary(a => a.a, a => a.val)

                                                                                                       select new ValidatorUsage(validatorName, argValues, forFields, dindex, fieldIndex));
        }
Пример #15
0
        static IEnumerable <string> GetQueries(IEnumerable <string> tail,
                                               bool includeSubdirs)
        {
            var dirSearchOption = includeSubdirs
                                ? SearchOption.AllDirectories
                                : SearchOption.TopDirectoryOnly;

            return
                (from spec in tail
                 let tokens = SplitDirFileSpec(spec).Fold((dp, fs) =>
                                                          (
                                                              dirPath: dp ?? Environment.CurrentDirectory,
                                                              fileSpec: fs
                                                          ))
                              let dirPath = tokens.dirPath ?? Environment.CurrentDirectory
                                            from e in
                                            tokens.fileSpec.IndexOfAny(Wildchars) >= 0
                    ? from fi in new DirectoryInfo(dirPath).EnumerateFiles(tokens.fileSpec, dirSearchOption)
                                            select new { File = fi, Searched = true }
                    : Directory.Exists(spec)
                    ? from fi in new DirectoryInfo(spec).EnumerateFiles("*.linq", dirSearchOption)
                 select new { File = fi, Searched = true }
                    : new[] { new { File = new FileInfo(spec), Searched = false } }
                 where !e.Searched ||
                 (!e.File.Name.StartsWith(".", StringComparison.Ordinal) &&
                  0 == (e.File.Attributes & (FileAttributes.Hidden | FileAttributes.System)))
                 select e.File.FullName);
        }
Пример #16
0
        public async Task <ThreadLolCounts> DownloadThreadLolCounts(ChattyThread thread)
        {
            var query = _downloadService.NewQuery();

            foreach (var post in thread.Posts)
            {
                query.Add("ids[]", $"{post.Id}");
            }

            var json = await _downloadService.DownloadWithSharedLogin(
                "https://www.shacknews.com/api2/api-index.php?action2=get_all_tags_for_posts",
                verifyLoginStatus : false,
                postBody : query);

            var response = JsonSerializer.Deserialize <TagsForPosts>(json,
                                                                     new JsonSerializerOptions {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            return
                (new ThreadLolCounts
            {
                CountsByPostId = (
                    from tag in response.Data
                    group tag by int.Parse(tag.ThreadId) into post_group
                    let postLols = (
                        from x in post_group
                        select new LolModel {
                    Tag = GetTagName(x.Tag), Count = int.Parse(x.Total)
                }
                        ).ToList()
                                   select(PostId: post_group.Key, Tags: postLols)
                    ).ToDictionary(x => x.PostId, x => x.Tags)
            });
Пример #17
0
    // Command Line Argument
    public static void Main(string[] args)
    {
        let first  = int.Parse(args[0]);       // 1
        let second = Convert.ToInt32(args[1]); // 2

        System.console.log(first + second);    // 1 + 2 = 3
    }
Пример #18
0
        public async Task Day04_ParseFile(string filename, int expected)
        {
            var logEntries = new List <LogEntry>();

            await foreach (var line in filename.GetLinesAsync())
            {
                logEntries.Add(LogEntry.Parse(line));
            }

            var shifts = Shift.Parse(logEntries).ToList();

            var asleep = from s in shifts
                         group s by s.GuardId into gg
                         let guardId = gg.Key
                                       let totalMinutesAsleep = gg.Sum(s => s.TotalMinutesAsleep)
                                                                orderby totalMinutesAsleep descending
                                                                select(guardId, totalMinutesAsleep);

            var sleepiest = asleep.First();

            var query = from shift in shifts
                        where shift.GuardId == sleepiest.guardId
                        from minute in shift.AsleepMinutes
                        group minute by minute into gg
                        let minute                         = gg.Key
                                                 let count = gg.Count()
                                                             orderby count descending
                                                             select(minute, count);

            var(sleepiestMinute, sleepiestMinuteCount) = query.First();

            Assert.Equal(expected, sleepiest.guardId * sleepiestMinute);
        }
Пример #19
0
        protected static void WriteExitCodeList(IConsoleService console, string title, Func <ExitCode, bool> exitCodePredicate)
        {
            var exitCodes = (from field in typeof(ExitCode).GetFields(BindingFlags.Public | BindingFlags.Static)
                             let attr = field.GetCustomAttribute <ReturnableExitCodeAttribute>()
                                        where attr != null
                                        let code = (ExitCode)field.GetValue(null) !
                                                   where exitCodePredicate(code)
                                                   let decimalCode = ((int)code).ToString()
                                                                     let hexCode = "0x" + Convert.ToString((int)code, 16).PadLeft(8, '0')
                                                                                   select(decimalCode, hexCode, description: attr.Description)).ToArray();

            console.WriteLine();
            console.WriteLine($"{title}:");
            if (exitCodes.Length == 0)
            {
                console.WriteLine("   In this category no exit codes are returned.");
            }
            else
            {
                new TableControl(console)
                {
                    Margin            = new(3, 0, 0, 0),
                    ShowColumnHeaders = false,
                    Columns           =
                    {
                        new() { WidthMode = ColumnWidthMode.Auto },
                        new() { WidthMode = ColumnWidthMode.Auto },
                        new() { WidthMode = ColumnWidthMode.Star },
                    },
Пример #20
0
        public IReadOnlyDictionary <int, string?> GetManagedThreadNames()
        {
            var threadQuery =
                from clrObject in Heap.EnumerateObjects()
                let type = clrObject.Type
                           where type != null && !type.IsFree && type.Name == "System.Threading.Thread"
                           let managedThreadId = type.GetFieldByName("m_ManagedThreadId") !.Read <int>(clrObject, true)
                                                 let threadName = type.GetFieldByName("m_Name") !.ReadString(clrObject, false)
                                                                  select new { managedThreadId, threadName };

//            // <{0}>k__BackingField
//            var threadQuery = from address in heap.EnumerateObjectAddresses()
//                              let type = heap.GetObjectType(address)
//                              where type != null && !type.IsFree && type.Name == "System.Threading.Thread"
////                              let runtimeThread = type.GetFieldByName("_runtimeThread")
//                              //                                 .GetValue(address)
//                              let managedThreadId = type.GetFieldByName("_managedThreadId")
//                                 .GetValue(address)
//                              let threadName = type.GetFieldByName("m_Name")
//                                 .GetValue(address)
////                              let managedThreadId = type.GetFieldByName("<ManagedThreadId>k__BackingField")
////                                 .GetValue(address)
////                              let threadName = type.GetFieldByName("<Name>k__BackingField")
////                                 .GetValue(address)
//                              select new {managedThreadId, threadName};

            var result = new Dictionary <int, string?>();

            foreach (var threadInfo in threadQuery)
            {
                result[threadInfo.managedThreadId] = threadInfo.threadName;
            }

            return(result);
        }
Пример #21
0
        public static async Task <bool> CheckHasAnyLogAvailableAsync()
        {
            try
            {
                foreach (StorageFile LogFile in from StorageFile File in await ApplicationData.Current.TemporaryFolder.GetFilesAsync()
                         let Mat = Regex.Match(File.Name, @"(?<=\[)(.+)(?=\])")
                                   where Mat.Success && DateTime.TryParseExact(Mat.Value, "yyyy-MM-dd HH-mm-ss.fff", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateTime _)
                                   select File)
                {
                    BasicProperties Properties = await LogFile.GetBasicPropertiesAsync();

                    if (Properties.Size > 0)
                    {
                        return(true);
                    }
                }

                return(false);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"An error was threw in {nameof(CheckHasAnyLogAvailableAsync)}, message: {ex.Message}");
                return(false);
            }
        }
Пример #22
0
 static void Multi(string message, let count)
 {
     for (var i = 0; i < count; i++)
     {
         console.log("{0}", message);
     }
 }
        static ObsoleteConventionsTests()
        {
            // Ensure all assemblies are loaded
            var types = new[]
            {
                typeof(Container),                                     // SimpleInjector.dll
                typeof(SimpleInjectorAspNetCoreIntegrationExtensions), // SI.Integration.AspNetCore
                typeof(SimpleInjectorTagHelperActivator),              // SI.Integration.AspNetCore.Mvc
                typeof(SimpleInjectorViewComponentActivator),          // SI.Integration.AspNetCore.Mvc.Core
                typeof(SimpleInjectorWcfExtensions),                   // SI.Integration.Wcf
                typeof(SimpleInjectorHttpModule),                      // SI.Integration.Web
                typeof(SimpleInjectorMvcExtensions),                   // SI.Integration.Web.Mvc
                typeof(SimpleInjectorWebApiExtensions),                // SI.Integration.WebApi
                typeof(PackageExtensions)                              // SI.Packaging
            };

            var assemblies = (
                from assembly in AppDomain.CurrentDomain.GetAssemblies()
                let fileName = Path.GetFileName(assembly.Location)
                               where fileName.Contains("SimpleInjector")
                               where !fileName.Contains("Test")
                               select assembly)
                             .ToArray();

            var exportedSimpleInjectorTypes = (
                from assembly in assemblies
                from type in assembly.GetExportedTypes()
                orderby type.FullName
                select type)
                                              .ToArray();

            var obsoletedTypes =
                from type in exportedSimpleInjectorTypes
                where type.GetCustomAttributes <ObsoleteAttribute>().Any()
                let attribute = type.GetCustomAttributes <ObsoleteAttribute>().Single()
                                select Tuple.Create((MemberInfo)type, attribute);

            var members = (
                from type in exportedSimpleInjectorTypes
                from member in type.GetMembers(BindingFlags.DeclaredOnly
                                               | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static)
                where member.Module.Assembly == type.Assembly
                select member)
                          .Distinct();

            var obsoletedTypeMembers =
                from member in members
                where member.GetCustomAttributes <ObsoleteAttribute>().Any()
                let attribute = member.GetCustomAttributes <ObsoleteAttribute>().Single()
                                select Tuple.Create(member, attribute);

            ObsoletedTypesAndTypeMembers = (
                from member in obsoletedTypes.Concat(obsoletedTypeMembers)
                let assembly = member.Item1 is Type t ? t.Assembly : member.Item1.DeclaringType.Assembly
                               let fileName = Path.GetFileName(assembly.Location)
                                              orderby fileName != "SimpleInjector.dll", assembly.FullName
                select member)
                                           .ToList().AsReadOnly();
        }
Пример #24
0
 static let MyPower(let num, let cnt)
 {
     if (cnt == 0)
     {
         return(1);
     }
     return(num * MyPower(num, --cnt)); // 2 * (2 * (1))
 }
Пример #25
0
 HttpParameterIndex(IEnumerable <HttpParameterSpec> parameters)
 {
     this.Parameters = (from p in parameters
                        group p by p.EntityName into g
                        let key = g.Key
                                  let specs = g.Select(x => x)
                                              select(key, specs.ToReadOnlyList())).ToDictionary(x => x.key, x => x.Item2);
 }
Пример #26
0
 /// <summary>
 /// Get an enumerable of all variables which are read in the program with a count of how many times they are read
 /// </summary>
 /// <param name="cfg"></param>
 /// <returns></returns>
 [NotNull] public static IEnumerable <(VariableName, uint)> FindReadCounts([NotNull] this IControlFlowGraph cfg)
 {
     return(from v in cfg.Vertices
            from r in v.FindReadCounts()
            group r.Item2 by r.Item1 into counts
            let c = counts.Aggregate((a, b) => a + b)
                    select(counts.Key, c));
 }
Пример #27
0
 private static void SolvePart1()
 {
     var input = File.ReadAllText("Input.txt");
     var data  = input.Split('\n').ToList();
     var nodes = (from s in data.Where(s => s != "").Where(s => s[0] == '/')
                  select s.Split(" ").Where(p => p != "").ToArray()
                  into parts
                  let path = parts[0].Split('-')
                             let x = int.Parse(path[1][1..])
Пример #28
0
 private static IEnumerable <FieldDef> GetRemovableFields(MethodDef method, WeavingContext context)
 {
     return(from instruction in method.Body.Instructions
            let fieldReference = instruction.Operand as IField
                                 where fieldReference is not null && fieldReference.DeclaringType.SafeEquivalent(method.DeclaringType)
                                 let fieldDefinition = fieldReference.ResolveFieldDef()
                                                       where fieldDefinition.CustomAttributes.Any(a => a.AttributeType.SafeEquivalent(context.CompilerGeneratedAttributeType))
                                                       select fieldDefinition);
 }
Пример #29
0
        public static (Player, Player) Parse(string input)
        {
            var numberRegex = new Regex("[0-9]+");

            var playerList = (from lines in input.Split(Environment.NewLine + Environment.NewLine)
                              select lines.Split(Environment.NewLine)
                              into line
                              let id = long.Parse(numberRegex.Match(line[0]).Value)
                                       let card = line[1..].Select(long.Parse).ToList()
Пример #30
0
 private IEnumerable <OverriddenParameter> CreateOverriddenDecoratorContextParameters(
     InstanceProducer currentProducer)
 {
     return
         (from parameter in this.decoratorConstructor !.GetParameters()
          where parameter.ParameterType == typeof(DecoratorContext)
          let contextExpression = Expression.Constant(new DecoratorContext(this.Context !))
                                  select new OverriddenParameter(parameter, contextExpression, currentProducer));
 }