Пример #1
0
        public void DescribeCandidateProcesses(IList<IProcessInfo> candidates, ConsoleLog console)
        {
            var byArchitecture = candidates.ToLookup(c => c.Architecture);
            var self = ProcessArchitecture.FromCurrentProcess();

            if(self is ProcessArchitecture.x86)
            {
                if(!x86Thunk.Bootstrap.WasUsed)
                {
                    // Native x86. Write out everything.
                    WriteProcessList(candidates, console);
                }
                else
                {
                    // Write out only matching processes.
                    WriteProcessList(byArchitecture[self].ToList(), console);
                }
            }
            else
            {
                WriteProcessList(byArchitecture[self].ToList(), console);
                if(byArchitecture[new ProcessArchitecture.x86()].Any())
                {
                    // Go to 32-bit and render the rest of the process information.
                    Bootstrap.RecurseInto32BitProcess();
                }
            }
        }
Пример #2
0
        private IList <Player> GetPlayers(IList <SimplifiedPlayer> members)
        {
            var wr            = new Wrapper(ApiKey);
            var membersLookup = members?.ToLookup(k => k.tag, v => v);
            var players       = wr.GetPlayer(membersLookup?.Select(t => t.Key).ToArray());

            return(players);
        }
Пример #3
0
		public IEnumerable<IssueMatch> Match (IList<ActionSummary> summaries, IList<CodeAction> realActions)
		{
			var summaryLookup = summaries.ToLookup (summary => summary.Region);
			foreach (var action in realActions) {
				if (summaryLookup.Contains (action.DocumentRegion)) {
					yield return new IssueMatch {
						Action = action,
						Summary = summaryLookup[action.DocumentRegion].First ()
					};
				}
			}
		}
Пример #4
0
        public void GuardarRedes(IList<Resultado> lista, string archivo, IList<FichaIndicadores> fichas)
        {
            var map = fichas.ToDictionary(x => x.Nombre);
            var grupos = lista.ToLookup(x => x.Tipo_item);

            using (var pck = new ExcelPackage(new FileInfo(archivo))) {
                try {
                    foreach (var grupo in grupos) {
                        if (!map.ContainsKey(grupo.Key))
                            continue;
                        Ficha = map[grupo.Key];
                        CrearHoja(grupo.ToList(), Ficha.Nombre, pck);
                    }
                    pck.Save();
                } catch (Exception ex) {
                    AppNotifier.Print("Error " + ex.Message, ex);
                }
            }
        }
Пример #5
0
        private IList <DataRowDetails> SumMs1Transitions(IList <DataRowDetails> dataRows)
        {
            var dataRowsByReplicateIndexAndTransitionGroup =
                dataRows.ToLookup(row =>
                                  new Tuple <int, IdentityPath>(row.ReplicateIndex,
                                                                row.IdentityPath.GetPathTo((int)SrmDocument.Level.TransitionGroups)));
            var newDataRows = new List <DataRowDetails>();

            foreach (var grouping in dataRowsByReplicateIndexAndTransitionGroup)
            {
                DataRowDetails ms1DataRow      = null;
                var            transitionGroup = (TransitionGroupDocNode)SrmDocument.FindNode(grouping.Key.Item2);
                foreach (var dataRow in grouping)
                {
                    var transition = (TransitionDocNode)transitionGroup.FindNode(dataRow.IdentityPath.Child);
                    if (transition.IsMs1)
                    {
                        if (ms1DataRow == null)
                        {
                            ms1DataRow = new DataRowDetails()
                            {
                                IdentityPath   = grouping.Key.Item2,
                                BioReplicate   = dataRow.BioReplicate,
                                Control        = dataRow.Control,
                                ReplicateIndex = dataRow.ReplicateIndex
                            };
                        }
                        ms1DataRow.Intensity   += dataRow.Intensity;
                        ms1DataRow.Denominator += dataRow.Denominator;
                    }
                    else
                    {
                        newDataRows.Add(dataRow);
                    }
                }
                if (ms1DataRow != null)
                {
                    newDataRows.Add(ms1DataRow);
                }
            }
            return(newDataRows);
        }
Пример #6
0
        protected IEnumerable <UM_Resource> FullHierarchyTraversal(IList <UM_Resource> resources, IList <UM_Resource> allResources)
        {
            var resourcesDict = allResources.ToDictionary(n => n.ID);
            var resourcesLp   = allResources.ToLookup(n => n.ParentID.GetValueOrDefault());

            foreach (var item in resources)
            {
                yield return(item);

                foreach (var parent in GetAllParents(item, resourcesDict))
                {
                    yield return(parent);
                }

                foreach (var child in GetAllChildren(item, resourcesLp))
                {
                    yield return(child);
                }
            }
        }
Пример #7
0
        public void UpdateLabels(ISession session)
        {
            String tagsNames;
            NameValueCollection labelsByProperty = this.MyFetcher.GetLabels();
            IList <LabelEntity> databaseLabels   = session.CreateCriteria <LabelEntity>()
                                                   .Add(Restrictions.Eq("MailAccountEntity", this.Entity))
                                                   .Add(Restrictions.Eq("Active", true))
                                                   .List <LabelEntity>();

            this.RegisterLabel(labelsByProperty["INBOX"], session, databaseLabels, "Inbox");
            this.RegisterLabel(labelsByProperty["All"], session, databaseLabels, "All");
            this.RegisterLabel(labelsByProperty["Trash"], session, databaseLabels, "Trash");
            this.RegisterLabel(labelsByProperty["Junk"], session, databaseLabels, "Junk");
            this.RegisterLabel(labelsByProperty["Important"], session, databaseLabels, "Important");
            this.RegisterLabel(labelsByProperty["Sent"], session, databaseLabels, "Sent");
            this.RegisterLabel(labelsByProperty["Flagged"], session, databaseLabels, "Flagged");
            this.RegisterLabel(labelsByProperty["Drafts"], session, databaseLabels, "Drafts");

            tagsNames = labelsByProperty["Tags"];
            if (tagsNames != null)
            {
                IList <String> labelsName = tagsNames.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                labelsName = labelsName.Where(x => !x.Contains("[Gmail]/")).ToList(); //filtrar otros labels de Gmail

                foreach (String existingLabel in labelsName)
                {
                    this.RegisterLabel(existingLabel, session, databaseLabels);
                }

                //eliminar labels que no esten en Gmail
                var namesLookUp   = labelsName.ToLookup(x => x);
                var removedLabels = databaseLabels.Where(x => x.SystemName == null && !namesLookUp.Contains(x.Name));
                foreach (LabelEntity removedLabel in removedLabels)
                {
                    Label label = new Label(removedLabel);
                    label.Delete(session);
                }
            }
            this.SetFetcherLabels(session);
        }
Пример #8
0
        public IList<Result> Judge(IList<IPlayer> playerList)
        {
            if (playerList == null) {
                throw new ArgumentNullException("player is missing");
            }

            if (playerList.Count < 1) {
                throw new ArgumentException("MajorityDecision need one person or more.");
            }

            var handLookup = playerList.ToLookup(player => player.ChoosedHand);
            if (handLookup.Count == 1) {
                return playerList.Map(player => new Result(player, ResultType.Draw));
            }
            var maxCount = handLookup.Max(hand => handLookup[hand.Key].Count());
            if (handLookup.Count(group => group.Count() == maxCount) > 1) {
                return playerList.Map(player => new Result(player, ResultType.Draw));
            }
            var winHand = handLookup.First(group => group.Count() == maxCount).Key;
            return playerList.Map(player => new Result(player, player.ChoosedHand.Equals(winHand) ? ResultType.Win : ResultType.Lose));
        }
        private IList <ItemKey> DetermineKeysNotFound()
        {
            IList <ItemKey> keysFound = KeysFound;

            if (keysFound.IsNullOrEmpty())
            {
                return(KeysRequested);
            }

            if (keysFound.Count == KeysRequested.Count)
            {
                return(null);
            }

            ILookup <string, ItemKey> foundKeysLookupTable = keysFound.ToLookup(key => key.ID);

            return((
                       from key in KeysRequested
                       where !(foundKeysLookupTable.Contains(key.ID))
                       select key
                       ).ToArray());
        }
Пример #10
0
        public void ApplyPendingDownloadIncrements(IList <LucenePackage> increments, ISession <LucenePackage> session)
        {
            if (increments.Count == 0)
            {
                return;
            }

            var byId = increments.ToLookup(p => p.Id);

            foreach (var grouping in byId)
            {
                var packageId = grouping.Key;
                var packages  = from p in session.Query() where p.Id == packageId select p;
                var byVersion = grouping.ToLookup(p => p.Version);

                foreach (var lucenePackage in packages)
                {
                    lucenePackage.DownloadCount        += grouping.Count();
                    lucenePackage.VersionDownloadCount += byVersion[lucenePackage.Version].Count();
                }
            }
        }
Пример #11
0
        /// <summary>
        ///     create a hashtable of start->list of tuples that start there
        ///     put all tuples in a queue of tupleSets
        ///     set the longestTupleSet to the first tuple
        ///     while the queue is not empty
        ///     take tupleSet from the queue
        ///     if any tuples start where the tupleSet ends
        ///     foreach tuple that starts where the tupleSet ends
        ///     enqueue new tupleSet of tupleSet + tuple
        ///     continue
        /// 
        ///     if tupleSet is longer than longestTupleSet
        ///     replace longestTupleSet with tupleSet
        /// 
        ///     return longestTupleSet
        /// </summary>
        /// <param name = "input"></param>
        /// <returns></returns>
        public static IList<Pair<int, int>> FindLongestNonOverlappingRangeSet(IList<Pair<int, int>> input)
        {
            var rangeStarts = input.ToLookup(x => x.First, x => x);
            var adjacentTuples = new Queue<List<Pair<int, int>>>(
                input.Select(x => new List<Pair<int, int>>
                    {
                        x
                    }));

            var longest = new List<Pair<int, int>>
                {
                    input[0]
                };
            int longestLength = input[0].Second - input[0].First;

            while (adjacentTuples.Count > 0)
            {
                var tupleSet = adjacentTuples.Dequeue();
                var last = tupleSet.Last();
                int end = last.First + last.Second;
                var sameStart = rangeStarts[end];
                if (sameStart.Any())
                {
                    foreach (var nextTuple in sameStart)
                    {
                        adjacentTuples.Enqueue(tupleSet.Concat(new[] { nextTuple }).ToList());
                    }
                    continue;
                }
                int length = end - tupleSet.First().First;
                if (length > longestLength)
                {
                    longestLength = length;
                    longest = tupleSet;
                }
            }

            return longest;
        }
Пример #12
0
        public static void SimpleLookup()
        {
            IList <string> list = GetStringList();

            //Sets KeyValue pair based on the string length.
            ILookup <int, string> lookup = list.ToLookup(i => i.Length);

            Console.WriteLine();
            Console.WriteLine("String length=7");

            //Iterates only string length having 7.
            foreach (string temp in lookup[7])
            {
                Console.WriteLine(temp);
            }
            Console.WriteLine("String length=9");

            //Iterates only string length having 9.
            foreach (string temp in lookup[9])
            {
                Console.WriteLine(temp);
            }
        }
Пример #13
0
    public static IEnumerable <TreeNode <T, TKey> > ToTree <T, TKey>(
        this IList <T> collection,
        Func <T, TKey> itemIdSelector,
        Func <T, TKey> parentIdSelector)
    {
        var rootNodes      = new List <TreeNode <T, TKey> >();
        var collectionHash = collection.ToLookup(parentIdSelector);
        //find root nodes
        var parentIds = collection.Select(parentIdSelector);
        var itemIds   = collection.Select(itemIdSelector);
        var rootIds   = parentIds.Except(itemIds);

        foreach (var rootId in rootIds)
        {
            rootNodes.AddRange(
                GetTreeNodes(
                    itemIdSelector,
                    collectionHash,
                    rootId)
                );
        }
        return(rootNodes);
    }
        public void AddSecurityList(ISession session, IList <Entities.Security> securityList)
        {
            IList <Entities.Security> securityListFromDb = securityRepository.GetSecurityListByRequestDate(session, DateTime.Today);

            IDictionary <string, Entities.Security> securityFromDbDictionary      = securityListFromDb.ToDictionary(s => s.Symbol?.ToUpperInvariant());
            ILookup <string, Entities.Security>     securityFromRequestDictionary = securityList.ToLookup(s => s.Symbol?.ToUpperInvariant());

            IList <string> securityFromRequestKeys = securityFromRequestDictionary.Select(x => x.Key).ToList();
            IList <string> newSymbolList           = securityFromRequestKeys.Except(securityFromDbDictionary.Keys).ToList();

            using (var ssession = dbSessionFactory.OpenStatelessSession())
                using (var transaction = ssession.BeginTransaction())
                {
                    foreach (string symbol in newSymbolList)
                    {
                        Entities.Security security = securityFromRequestDictionary[symbol].FirstOrDefault();

                        securityRepository.Insert(ssession, security);
                    }

                    transaction.Commit();
                }
        }
Пример #15
0
        public void ApplyPendingDownloadIncrements(IList<LucenePackage> increments, ISession<LucenePackage> session)
        {
            if (increments.Count == 0) return;

            var byId = increments.ToLookup(p => p.Id);

            foreach (var grouping in byId)
            {
                var packageId = grouping.Key;
                var packages = from p in session.Query() where p.Id == packageId select p;
                var byVersion = grouping.ToLookup(p => p.Version);

                foreach (var lucenePackage in packages)
                {
                    lucenePackage.DownloadCount += grouping.Count();
                    lucenePackage.VersionDownloadCount += byVersion[lucenePackage.Version].Count();
                }
            }
        }
Пример #16
0
 public static ILookup <TKey, TValue> ToLookup <TKey, TValue>(
     this IList <KeyValuePair <TKey, TValue> > source)
 {
     return(source.ToLookup(x => x.Key, x => x.Value));
 }
 public static IList<AlbumTarget> FromListAndTargets(IList<Track> iTracks, IList<Artist> Artists, string AlbumName, string itGenre = null, int? tYear = null)
 {
     var res = iTracks.ToLookup(t => t.RawAlbum).ToLookup(a => new AlbumTarget(Artists ?? a.Key.RawArtists, AlbumName ?? a.Key.Name, itGenre, tYear));
     return res.Apply(g => g.Key.OrderedTrack = g.Select((gg) => new OriginedGroupedTrack(gg.Key, gg.ToList(), g.Key)).ToList()).Select(g => g.Key).ToList();
 }
Пример #18
0
        public void Save(Stream hpiStream, Stream hpbStream, IList <IArchiveFileInfo> files)
        {
            var sjis = Encoding.GetEncoding("SJIS");
            var hash = new SimpleHash(0x25);

            using var hpiBw = new BinaryWriterX(hpiStream);

            // Calculate offsets
            var fileOffset   = 0;
            var hashOffset   = HeaderSize;
            var entryOffset  = hashOffset + HashSlotCount_ * HashEntrySize;
            var stringOffset = entryOffset + files.Count * FileEntrySize;

            // Group files
            var fileLookup = files.ToLookup(x => hash.ComputeValue(x.FilePath.ToRelative().FullName, sjis) % HashSlotCount_);

            // Write files and strings
            hpiStream.Position = stringOffset;
            hpbStream.Position = fileOffset;
            foreach (var file in files.Cast <HpiHpbArchiveFileInfo>().OrderBy(x => x.FilePath, new SlashFirstStringComparer()))
            {
                fileOffset = (int)hpbStream.Position;
                var nameOffset = (int)hpiStream.Position;

                var writtenSize = file.SaveFileData(hpbStream);
                hpiBw.WriteString(file.FilePath.ToRelative().FullName, sjis, false);

                file.Entry.offset       = fileOffset;
                file.Entry.stringOffset = nameOffset - stringOffset;
                file.Entry.compSize     = (int)writtenSize;
                file.Entry.decompSize   = file.UsesCompression ? (int)file.FileSize : 0;
            }

            // Write entries
            var hashes = new List <HpiHashEntry>();

            hpiStream.Position = entryOffset;
            for (uint i = 0, offset = 0; i < HashSlotCount_; i++)
            {
                var hashEntry = new HpiHashEntry
                {
                    entryOffset = (short)offset,
                    entryCount  = (short)fileLookup[i].Count()
                };
                hashes.Add(hashEntry);
                offset += (uint)hashEntry.entryCount;

                foreach (var file in fileLookup[i].Cast <HpiHpbArchiveFileInfo>())
                {
                    hpiBw.WriteType(file.Entry);
                }
            }

            // Write hash entries
            hpiStream.Position = hashOffset;
            hpiBw.WriteMultiple(hashes);

            // Write header
            hpiStream.Position = 0;
            hpiBw.WriteType(new HpiHeader
            {
                hashCount  = (short)hashes.Count,
                entryCount = files.Count
            });
        }
Пример #19
0
        public void PostMoveAnalytics()
        {
            var playersByLocation = players.ToLookup(x => x.GetPosition());

            foreach (var meetingPlayers in playersByLocation.Where(x => playersByLocation.Any(y => y.Key == x.Key + 1)))
            {
                foreach (var meetingPlayer in meetingPlayers)
                {
                    if (meetingPlayer.GetDirection() < 0)
                    {
                        continue;
                    }
                    foreach (var player in playersByLocation
                             .Where(y => y.Key == meetingPlayers.Key + 1)
                             .SelectMany(x => x)
                             .Where(x => x.GetDirection() < 0))
                    {
                        stats.AddPlayerMeet(PlayerMeet.Create(
                                                meetingPlayers.Key,
                                                meetingPlayer,
                                                meetingPlayers.Key + 1,
                                                player));
                    }
                }
            }
            foreach (var meetingPlayers in playersByLocation.Where(x => playersByLocation.Any(y => y.Key == x.Key - 1)))
            {
                foreach (var meetingPlayer in meetingPlayers)
                {
                    if (meetingPlayer.GetDirection() > 0)
                    {
                        continue;
                    }
                    foreach (var player in playersByLocation
                             .Where(y => y.Key == meetingPlayers.Key - 1)
                             .SelectMany(x => x)
                             .Where(x => x.GetDirection() > 0))
                    {
                        stats.AddPlayerMeet(PlayerMeet.Create(
                                                meetingPlayers.Key,
                                                meetingPlayer,
                                                meetingPlayers.Key - 1,
                                                player));
                    }
                }
            }
            foreach (var passingPlayers in playersByLocation.Where(x => playersByLocation.Any(y => y.Key == x.Key - 1)))
            {
                foreach (var meetingPlayer in passingPlayers)
                {
                    if (meetingPlayer.GetDirection() < 0)
                    {
                        continue;
                    }
                    foreach (var player in playersByLocation
                             .Where(y => y.Key == passingPlayers.Key - 1)
                             .SelectMany(x => x)
                             .Where(x => x.GetDirection() < 0))
                    {
                        stats.AddPlayerPass(PlayerPass.Create(
                                                passingPlayers.Key,
                                                meetingPlayer,
                                                passingPlayers.Key - 1,
                                                player));
                    }
                }
            }
            foreach (var passingPlayers in playersByLocation.Where(x => playersByLocation.Any(y => y.Key == x.Key + 1)))
            {
                foreach (var meetingPlayer in passingPlayers)
                {
                    if (meetingPlayer.GetDirection() > 0)
                    {
                        continue;
                    }
                    foreach (var player in playersByLocation
                             .Where(y => y.Key == passingPlayers.Key + 1)
                             .SelectMany(x => x)
                             .Where(x => x.GetDirection() > 0))
                    {
                        stats.AddPlayerPass(PlayerPass.Create(
                                                passingPlayers.Key,
                                                meetingPlayer,
                                                passingPlayers.Key + 1,
                                                player));
                    }
                }
            }
            foreach (var passingPlayers in playersByLocation.Where(x => x.Count() > 1))
            {
                foreach (var meetingPlayer in passingPlayers)
                {
                    foreach (var player in playersByLocation
                             .SelectMany(x => x))
                    {
                        stats.AddPlayerPass(PlayerPass.Create(
                                                passingPlayers.Key,
                                                meetingPlayer,
                                                passingPlayers.Key + 1,
                                                player));
                    }
                }
            }
            foreach (var playersNotOnBoard in playersByLocation.Where(x => !IsOnBoard(x.Key)))
            {
                foreach (var player in playersNotOnBoard)
                {
                    players.Remove(player);
                }
            }
        }
Пример #20
0
 public ILookup <string, string> AsILookup()
 {
     return(errorList.ToLookup(_ => _.Key, _ => _.Value));
 }
Пример #21
0
        public IEnumerable <string> Invoke(IList <string> input)
        {
            // I've kept this method simple but I also chose include sanity checks and a minor edge case so that you know what I've considered.

            // Sanity check input. Would normally do this kind of thing with Code Contracts.
            // Could have combined all 3 checks to yield break rather than raising an exception.
            // I do like the explicit nature of raising exceptions though and in prod code would define a more useful exception type.
            if (input == null || input.Any() == false)
            {
                throw new Exception("You must pass a non-empty, non-null parameter to the Parse method.");
            }

            if (input.Count < 3)
            {
                yield break;
            }

            // Store the input in a lookup with word length as the key. Lookup is more performant than some other solutions such as doing a Where on the input.
            var lookup = input.ToLookup(x => x.Length);

            // Using a hashset for constant time lookup when doing .Contains() (O(1)).
            // Could have used a list but since we've got a base count of items > 5, HashSet is probably more performant.
            var possibleWords = new HashSet <string>(lookup[6]);

            // This is the expanded non-linq version. I've included two Linq versions below for comparison.
            // I'd use the Linq version in production code but it's sometimes nice to see it written long(er) form in a test too.
            // I could have also looped over the 6 char words instead of all of them and output based on whether any combination makes the current word.
            foreach (var word in input)
            {
                // Copy word variable so we don't access foreach variable in closure.
                var safeWord = word;

                // Get all the right hand segments that would create a combined word + part length equal to 6.
                var possParts = lookup[6 - word.Length].ToList();

                // This one is a bit of an edge case but I thought I'd include it since I'd written the test for it already.
                // We want to make sure that a segment isn't appended to itself to form a combination that's also a valid word
                // whilst at the same time, making sure that if a segment apears twice, and its combination is a valid word, it passes.
                var indexOfCurrentWord = possParts.FindIndex(x => x == safeWord);

                if (indexOfCurrentWord >= 0)
                {
                    possParts.RemoveAt(indexOfCurrentWord);
                }


                foreach (var part in possParts)
                {
                    var comb = word + part;

                    if (possibleWords.Contains(comb))
                    {
                        yield return(comb);
                    }
                }
            }

            /*
             * LINQ variations of the foreach above:
             * 1) return from word in input let possParts = lookup[6 - word.Length] from part in possParts select word + part into comb where possibleWords.Contains(comb) select comb;
             *
             * 2) return input
             *            .SelectMany(w => lookup[6 - w.Length], (w, y) => new { Value = w + y })
             *            .Where(x => possibleWords.Contains(x.Value))
             *            .Select(x => x.Value);
             */
        }
Пример #22
0
 private void RebuildIndexes()
 {
     _indexes = _lookups.ToDictionary(
         lookup => lookup.ToString(), lookup => _items.ToLookup(lookup.Compile()));
 }
Пример #23
0
        public static Tree <T> ToTree <T>(this IList <T> items, Func <T, T, bool> parentSelector)
        {
            var lookup = items.ToLookup(item => items.FirstOrDefault(parent => parentSelector(parent, item)), child => child);

            return(Tree <T> .FromLookup(lookup));
        }
Пример #24
0
        private async Task UploadLocalChanges()
        {
            this.OnSyncProgress(new SyncProgressEventArgs("Get local changes..."));

            IList <DirtyEntity> allDirtyItems = await siaqodbMobile.LoadAllAsync <DirtyEntity>();

            ILookup <string, DirtyEntity> lookup = allDirtyItems.ToLookup(a => a.EntityType);

            this.OnSyncProgress(new SyncProgressEventArgs("Prepare uploads..."));

            foreach (var item in lookup)
            {
                IEnumerable <DirtyEntity> entities = lookup[item.Key];
                Dictionary <int, Tuple <object, DirtyEntity> > inserts = new Dictionary <int, Tuple <object, DirtyEntity> >();
                Dictionary <int, Tuple <object, DirtyEntity> > updates = new Dictionary <int, Tuple <object, DirtyEntity> >();
                Dictionary <int, Tuple <object, DirtyEntity> > deletes = new Dictionary <int, Tuple <object, DirtyEntity> >();
                Type type = ReflectionHelper.GetTypeByDiscoveringName(entities.First <DirtyEntity>().EntityType);
                if (!this.SyncedTypes.ContainsKey(type))
                {
                    continue;
                }
                string tableName = this.SyncedTypes[type];
                foreach (DirtyEntity en in entities)
                {
                    if (en.DirtyOp == DirtyOperation.Deleted)
                    {
                        if (inserts.ContainsKey(en.EntityOID))
                        {
                            siaqodbMobile.DeleteBase(inserts[en.EntityOID].Item1);
                            siaqodbMobile.DeleteBase(en);
                            inserts.Remove(en.EntityOID);
                            continue;
                        }
                        else if (updates.ContainsKey(en.EntityOID))
                        {
                            siaqodbMobile.DeleteBase(updates[en.EntityOID].Item1);
                            updates.Remove(en.EntityOID);
                        }
                    }
                    else
                    {
                        if (deletes.ContainsKey(en.EntityOID) || inserts.ContainsKey(en.EntityOID) || updates.ContainsKey(en.EntityOID))
                        {
                            siaqodbMobile.DeleteBase(en);
                            continue;
                        }
                    }


                    object entityFromDB = _bs._lobjby(siaqodbMobile, type, en.EntityOID);
                    if (en.DirtyOp == DirtyOperation.Inserted)
                    {
                        inserts.Add(en.EntityOID, new Tuple <object, DirtyEntity>(entityFromDB, en));
                    }
                    else if (en.DirtyOp == DirtyOperation.Updated)
                    {
                        updates.Add(en.EntityOID, new Tuple <object, DirtyEntity>(entityFromDB, en));
                    }
                    else if (en.DirtyOp == DirtyOperation.Deleted)
                    {
                        deletes.Add(en.EntityOID, new Tuple <object, DirtyEntity>(entityFromDB, en));
                    }
                }


                this.OnSyncProgress(new SyncProgressEventArgs("Start upload changes..."));
                IMobileServiceTable table = MobileService.GetTable(tableName);
                table.SystemProperties |= MobileServiceSystemProperties.All;

                this.OnSyncProgress(new SyncProgressEventArgs("Start upload inserts..."));
                await UploadInserts(table, inserts);

                this.OnSyncProgress(new SyncProgressEventArgs("Inserts uploads finished..."));

                this.OnSyncProgress(new SyncProgressEventArgs("Start upload updates..."));
                await UploadUpdates(table, updates);

                this.OnSyncProgress(new SyncProgressEventArgs("Updates uploads finished..."));

                this.OnSyncProgress(new SyncProgressEventArgs("Start upload deletes..."));
                await UploadDeletes(table, deletes);

                this.OnSyncProgress(new SyncProgressEventArgs("Deletes uploads finished..."));


                siaqodbMobile.Flush();
            }
            siaqodbMobile.DropType <DirtyEntity>();
            this.OnSyncProgress(new SyncProgressEventArgs("Uploads finsihed..."));
        }
Пример #25
0
        private void WriteComments(IList <POComment> comments)
        {
            IOrderedEnumerable <IGrouping <POCommentKind, POComment> > commentLookup = comments.ToLookup(c => c.Kind).OrderBy(c => c.Key);

            foreach (IGrouping <POCommentKind, POComment> commentGroup in commentLookup)
            {
                foreach (POComment comment in commentGroup)
                {
                    char commentKindToken;
                    switch (comment.Kind)
                    {
                    case POCommentKind.Translator: commentKindToken = ' '; break;

                    case POCommentKind.Extracted: commentKindToken = '.'; break;

                    case POCommentKind.Reference: commentKindToken = ':'; break;

                    case POCommentKind.Flags: commentKindToken = ','; break;

                    case POCommentKind.PreviousValue: commentKindToken = '|'; break;

                    default: throw new InvalidOperationException();
                    }

                    _writer.WriteLine($"#{commentKindToken} {comment}");
                }
            }
        }
Пример #26
0
        public void Generate(string projectRoot, IList <ControllerDefinition> controllers)
        {
            var areaControllers = controllers.ToLookup(c => c.Area);

            // Processing controllers, generating partial and derived controller classes for R4Mvc
            var generatedControllers = new List <NamespaceDeclarationSyntax>();

            foreach (var namespaceGroup in controllers.Where(c => c.Namespace != null).GroupBy(c => c.Namespace).OrderBy(c => c.Key))
            {
                var namespaceNode = NamespaceDeclaration(ParseName(namespaceGroup.Key));
                foreach (var controller in namespaceGroup.OrderBy(c => c.Name))
                {
                    namespaceNode = namespaceNode.AddMembers(
                        _controllerGenerator.GeneratePartialController(controller),
                        _controllerGenerator.GenerateR4Controller(controller));

                    // If SplitIntoMultipleFiles is set, store the generated classes alongside the controller files.
                    if (_settings.SplitIntoMultipleFiles)
                    {
                        var controllerFile = NewCompilationUnit()
                                             .AddMembers(namespaceNode);
                        CompleteAndWriteFile(controllerFile, controller.GetFilePath().TrimEnd(".cs") + ".generated.cs");
                        namespaceNode = NamespaceDeclaration(ParseName(namespaceGroup.Key));
                    }
                }

                // If SplitIntoMultipleFiles is NOT set, bundle them all in R4Mvc
                if (!_settings.SplitIntoMultipleFiles)
                {
                    generatedControllers.Add(namespaceNode);
                }
            }

            // R4MVC namespace used for the areas and Dummy class
            var r4Namespace = NamespaceDeclaration(ParseName(_settings.R4MvcNamespace))
                              // add the dummy class using in the derived controller partial class
                              .WithDummyClass()
                              .AddMembers(CreateViewOnlyControllerClasses(controllers).ToArray <MemberDeclarationSyntax>())
                              .AddMembers(CreateAreaClasses(areaControllers).ToArray <MemberDeclarationSyntax>());

            // create static MVC class and add the area and controller fields
            var mvcStaticClass = ClassDeclaration(_settings.HelpersPrefix)
                                 .WithModifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword, SyntaxKind.PartialKeyword)
                                 .WithGeneratedNonUserCodeAttributes();

            foreach (var area in areaControllers.Where(a => !string.IsNullOrEmpty(a.Key)).OrderBy(a => a.Key))
            {
                mvcStaticClass = mvcStaticClass.WithStaticFieldBackedProperty(area.First().AreaKey, $"{_settings.R4MvcNamespace}.{area.Key}AreaClass", SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword);
            }
            foreach (var controller in areaControllers[string.Empty].OrderBy(c => c.Namespace == null).ThenBy(c => c.Name))
            {
                mvcStaticClass = mvcStaticClass.AddMembers(
                    SyntaxNodeHelpers.CreateFieldWithDefaultInitializer(
                        controller.Name,
                        controller.FullyQualifiedGeneratedName,
                        controller.FullyQualifiedR4ClassName ?? controller.FullyQualifiedGeneratedName,
                        SyntaxKind.PublicKeyword,
                        SyntaxKind.StaticKeyword,
                        SyntaxKind.ReadOnlyKeyword));
            }

            // Generate a list of all static files from the wwwroot path
            var staticFileNode = _staticFileGenerator.GenerateStaticFiles(projectRoot);

            var r4mvcNode = NewCompilationUnit()
                            .AddMembers(
                mvcStaticClass,
                r4Namespace,
                staticFileNode,
                ActionResultClass(),
                JsonResultClass(),
                ContentResultClass(),
                RedirectResultClass(),
                RedirectToActionResultClass(),
                RedirectToRouteResultClass())
                            .AddMembers(generatedControllers.ToArray <MemberDeclarationSyntax>());

            CompleteAndWriteFile(r4mvcNode, Path.Combine(projectRoot, R4MvcGeneratorService.R4MvcFileName));
        }
Пример #27
0
        public void ReplaceIndexersCalls(MethodDefinition method, IList<SliceParameters> slices)
        {
            var processor = method.Body.GetILProcessor();
            var instructions = processor.Body.Instructions;

            var slicesLookup = slices.ToLookup(x => x.Definition);

            for (int offset = 0; offset < instructions.Count; offset++)
            {
                var instruction = instructions[offset];
                if (!instruction.OpCode.IsCall())
                    continue;

                var methodReference = instruction.Operand as MethodReference;
                if (methodReference == null)
                    continue;

                if (methodReference.Name != "get_Item" && methodReference.Name != "set_Item")
                    continue;

                var objectToCall = instruction.TraceBack(methodReference, 0);
                var parameter = instruction.TraceBack(methodReference, -1);

                var slice = slicesLookup[objectToCall.Operand].FirstOrDefault();
                if (slice == null)
                    continue;

                var arraySliceType = ModuleDefinition.Import(typeof(ArraySlice<>)).MakeGenericInstanceType(slice.GenericArgument);

                var methodDefinition = methodReference.Resolve();

                // FIXME: We know we cannot process if anything happens between the push of the array slice and the final operation.
                if (methodDefinition.IsGetter)
                {
                    // Original GET:
                    // 1    ldarg.s segment              $ Push the object to call
                    // =    ldloc.1                      $ Push the parameter
                    // 2    callvirt instance !0 class ArraySegment.ArraySlice`1<float32>::get_Item(int32)
                    // =    stloc.s t                    $ Do whatever with the result of the GET call

                    // Target GET:
                    // 1    ldloc.s data                 $ Push the object to call
                    // =    ldloc.1                      $ Push the parameter
                    // 2    ldloc.s offset
                    // 2    add                          $ Add the parameter (i) and the offset.
                    // 2    ldelem.r4                    $ Use standard ldelem with type to get the value from the array.
                    // =    stloc.s t                    $ Do whatever with the result of the GET call

                    //HACK: We rewrite it to avoid killing the loop.
                    objectToCall.OpCode = OpCodes.Ldloc;
                    objectToCall.Operand = slice.ArrayVariable;

                    processor.Replace(instruction, Instruction.Create(OpCodes.Ldelem_Any, slice.GenericArgument));

                    processor.InsertAfter(parameter, new[] {
                                Instruction.Create( OpCodes.Ldloc, slice.OffsetVariable ),
                                Instruction.Create( OpCodes.Add )
                        });
                }
                else if (methodDefinition.IsSetter)
                {
                    // Original SET:
                    // 1		ldarg segment	    $ Push the object to call
                    // =		ldloc.0		        $ Push the parameter
                    // =		ldc.r4 2		    $ Push the value to set
                    // 2		callvirt instance void class ArraySegment.ArraySlice`1<float32>::set_Item(int32, !0)
                    // -        nop			        $ Check if it even exists after SimplifyMacros in the collection.

                    // Target SET
                    // 1		ldloc data		    $ Push the array
                    // =		ldloc.0		        $ Push the parameter
                    // 2		ldloc offset
                    // 2		add      		    $ Add the parameter (i) and the offset.
                    // =		ldc.r4 2		    $ Push the value to set. Use standard ldc with type and check if it  is optimized afterwards.
                    // 2		stelem   		    $ Use standard stelem with type and check if it is optimized afterwards.

                    //HACK: We rewrite it to avoid killing the loop.
                    objectToCall.OpCode = OpCodes.Ldloc;
                    objectToCall.Operand = slice.ArrayVariable;

                    processor.Replace(instruction, Instruction.Create(OpCodes.Stelem_Any, slice.GenericArgument));

                    processor.InsertAfter(parameter, new[] {
                                Instruction.Create( OpCodes.Ldloc, slice.OffsetVariable ),
                                Instruction.Create( OpCodes.Add )
                        });

                }
                else continue;
            }
        }
Пример #28
0
 private void ResetCaches()
 {
     m_lookup = m_data.ToLookup(c => c.BcvRef.BBCCCVVV);
     m_uniqueCharacterAndDeliveries = null;
     m_uniqueDeliveries             = null;
 }
Пример #29
0
        private void TestToLookup()
        {
            var studentsGrouped = _studentList.ToLookup(s => s.Age).ToList();

            PrintGrouping(studentsGrouped);
        }
Пример #30
0
        public ILookup <string, Author> GroupByCountry(IReadOnlyList <string> countries)
        {
            var res = _authors.ToLookup(a => a.Country);

            return(res);
        }
Пример #31
0
        public TraktSyncEpisodesResult SyncSeries()
        {
            _mediaPortalServices.GetLogger().Info("Trakt: start sync series");

            ValidateAuthorization();

            TraktSyncEpisodesResult  syncEpisodesResult     = new TraktSyncEpisodesResult();
            TraktEpisodes            traktEpisodes          = _traktCache.RefreshSeriesCache();
            IList <Episode>          traktUnWatchedEpisodes = traktEpisodes.UnWatched;
            IList <EpisodeWatched>   traktWatchedEpisodes   = traktEpisodes.Watched;
            IList <EpisodeCollected> traktCollectedEpisodes = traktEpisodes.Collected;

            Guid[] types =
            {
                MediaAspect.ASPECT_ID,            EpisodeAspect.ASPECT_ID, VideoAspect.ASPECT_ID, ImporterAspect.ASPECT_ID,
                ProviderResourceAspect.ASPECT_ID, ExternalIdentifierAspect.ASPECT_ID
            };
            var contentDirectory = _mediaPortalServices.GetServerConnectionManager().ContentDirectory;

            if (contentDirectory == null)
            {
                throw new MediaLibraryNotConnectedException("ML not connected");
            }

            Guid?           userProfile = null;
            IUserManagement userProfileDataManagement = _mediaPortalServices.GetUserManagement();

            if (userProfileDataManagement != null && userProfileDataManagement.IsValidUser)
            {
                userProfile = userProfileDataManagement.CurrentUser.ProfileId;
            }

            #region Get data from local database

            IList <MediaItem> localEpisodes = contentDirectory.SearchAsync(new MediaItemQuery(types, null, null), true, userProfile, false).Result;

            if (localEpisodes.Any())
            {
                syncEpisodesResult.CollectedInLibrary = localEpisodes.Count;
                _mediaPortalServices.GetLogger().Info("Trakt: found {0} total episodes in library", localEpisodes.Count);
            }

            List <MediaItem> localWatchedEpisodes = localEpisodes.Where(MediaItemAspectsUtl.IsWatched).ToList();

            if (localWatchedEpisodes.Any())
            {
                syncEpisodesResult.WatchedInLibrary = localWatchedEpisodes.Count;
                _mediaPortalServices.GetLogger().Info("Trakt: found {0} episodes watched in library", localWatchedEpisodes.Count);
            }

            #endregion

            #region Mark episodes as unwatched in local database

            _mediaPortalServices.GetLogger().Info("Trakt: start marking series episodes as unwatched in media library");
            if (traktUnWatchedEpisodes.Any())
            {
                // create a unique key to lookup and search for faster
                ILookup <string, MediaItem> localLookupEpisodes = localWatchedEpisodes.ToLookup(twe => CreateLookupKey(twe), twe => twe);

                foreach (var episode in traktUnWatchedEpisodes)
                {
                    string tvdbKey = CreateLookupKey(episode);

                    var watchedEpisode = localLookupEpisodes[tvdbKey].FirstOrDefault();
                    if (watchedEpisode != null)
                    {
                        _mediaPortalServices.GetLogger().Info(
                            "Marking episode as unwatched in library, episode is not watched on trakt. Title = '{0}', Year = '{1}', Season = '{2}', Episode = '{3}', Show TVDb ID = '{4}', Show IMDb ID = '{5}'",
                            episode.ShowTitle, episode.ShowYear.HasValue ? episode.ShowYear.ToString() : "<empty>", episode.Season,
                            episode.Number, episode.ShowTvdbId.HasValue ? episode.ShowTvdbId.ToString() : "<empty>",
                            episode.ShowImdbId ?? "<empty>");

                        if (_mediaPortalServices.MarkAsUnWatched(watchedEpisode).Result)
                        {
                            syncEpisodesResult.MarkedAsUnWatchedInLibrary++;
                        }

                        // update watched episodes
                        localWatchedEpisodes.Remove(watchedEpisode);
                    }
                }
            }

            #endregion

            #region Mark episodes as watched in local database

            _mediaPortalServices.GetLogger().Info("Trakt: start marking series episodes as watched in media library");
            if (traktWatchedEpisodes.Any())
            {
                // create a unique key to lookup and search for faster
                ILookup <string, EpisodeWatched> onlineEpisodes = traktWatchedEpisodes.ToLookup(twe => CreateLookupKey(twe), twe => twe);
                List <MediaItem> localUnWatchedEpisodes         = localEpisodes.Except(localWatchedEpisodes).ToList();
                foreach (var episode in localUnWatchedEpisodes)
                {
                    string tvdbKey = CreateLookupKey(episode);

                    var traktEpisode = onlineEpisodes[tvdbKey].FirstOrDefault();
                    if (traktEpisode != null)
                    {
                        _mediaPortalServices.GetLogger().Info(
                            "Marking episode as watched in library, episode is watched on trakt. Plays = '{0}', Title = '{1}', Year = '{2}', Season = '{3}', Episode = '{4}', Show TVDb ID = '{5}', Show IMDb ID = '{6}', Last Watched = '{7}'",
                            traktEpisode.Plays, traktEpisode.ShowTitle,
                            traktEpisode.ShowYear.HasValue ? traktEpisode.ShowYear.ToString() : "<empty>", traktEpisode.Season,
                            traktEpisode.Number, traktEpisode.ShowTvdbId.HasValue ? traktEpisode.ShowTvdbId.ToString() : "<empty>",
                            traktEpisode.ShowImdbId ?? "<empty>", traktEpisode.WatchedAt);

                        if (_mediaPortalServices.MarkAsWatched(episode).Result)
                        {
                            syncEpisodesResult.MarkedAsWatchedInLibrary++;
                        }
                    }
                }
            }

            #endregion

            #region Add episodes to watched history at trakt.tv

            ITraktSyncHistoryPost syncHistoryPost = GetWatchedShowsForSync(localWatchedEpisodes, traktWatchedEpisodes);
            if (syncHistoryPost.Shows != null && syncHistoryPost.Shows.Any())
            {
                _mediaPortalServices.GetLogger().Info("Trakt: trying to add {0} watched episodes to trakt watched history", syncHistoryPost.Shows.Count());
                ITraktSyncHistoryPostResponse response = _traktClient.AddWatchedHistoryItems(syncHistoryPost);
                syncEpisodesResult.AddedToTraktWatchedHistory = response.Added?.Episodes;
                _traktCache.ClearLastActivity(FileName.WatchedEpisodes.Value);

                if (response.Added?.Episodes != null)
                {
                    _mediaPortalServices.GetLogger().Info("Trakt: successfully added {0} watched episodes to trakt watched history", response.Added.Episodes.Value);
                }
            }

            #endregion

            #region Add episodes to collection at trakt.tv

            ITraktSyncCollectionPost syncCollectionPost = GetCollectedShowsForSync(localEpisodes, traktCollectedEpisodes);
            if (syncCollectionPost.Shows != null && syncCollectionPost.Shows.Any())
            {
                _mediaPortalServices.GetLogger().Info("Trakt: trying to add {0} collected episodes to trakt collection", syncCollectionPost.Shows.Count());
                ITraktSyncCollectionPostResponse response = _traktClient.AddCollectionItems(syncCollectionPost);
                syncEpisodesResult.AddedToTraktCollection = response.Added?.Episodes;
                _traktCache.ClearLastActivity(FileName.CollectedEpisodes.Value);

                if (response.Added?.Episodes != null)
                {
                    _mediaPortalServices.GetLogger().Info("Trakt: successfully added {0} collected episodes to trakt collection", response.Added.Episodes.Value);
                }
            }

            #endregion

            return(syncEpisodesResult);
        }
Пример #32
0
        public void ReplaceIndexersCalls(MethodDefinition method, IList <SliceParameters> slices)
        {
            var processor    = method.Body.GetILProcessor();
            var instructions = processor.Body.Instructions;

            var slicesLookup = slices.ToLookup(x => x.Definition);

            for (int offset = 0; offset < instructions.Count; offset++)
            {
                var instruction = instructions[offset];
                if (!instruction.OpCode.IsCall())
                {
                    continue;
                }

                var methodReference = instruction.Operand as MethodReference;
                if (methodReference == null)
                {
                    continue;
                }

                if (methodReference.Name != "get_Item" && methodReference.Name != "set_Item")
                {
                    continue;
                }

                var objectToCall = instruction.TraceBack(methodReference, 0);
                var parameter    = instruction.TraceBack(methodReference, -1);

                var slice = slicesLookup[objectToCall.Operand].FirstOrDefault();
                if (slice == null)
                {
                    continue;
                }

                var arraySliceType = ModuleDefinition.Import(typeof(ArraySlice <>)).MakeGenericInstanceType(slice.GenericArgument);

                var methodDefinition = methodReference.Resolve();

                // FIXME: We know we cannot process if anything happens between the push of the array slice and the final operation.
                if (methodDefinition.IsGetter)
                {
                    // Original GET:
                    // 1    ldarg.s segment              $ Push the object to call
                    // =    ldloc.1                      $ Push the parameter
                    // 2    callvirt instance !0 class ArraySegment.ArraySlice`1<float32>::get_Item(int32)
                    // =    stloc.s t                    $ Do whatever with the result of the GET call

                    // Target GET:
                    // 1    ldloc.s data                 $ Push the object to call
                    // =    ldloc.1                      $ Push the parameter
                    // 2    ldloc.s offset
                    // 2    add                          $ Add the parameter (i) and the offset.
                    // 2    ldelem.r4                    $ Use standard ldelem with type to get the value from the array.
                    // =    stloc.s t                    $ Do whatever with the result of the GET call

                    //HACK: We rewrite it to avoid killing the loop.
                    objectToCall.OpCode  = OpCodes.Ldloc;
                    objectToCall.Operand = slice.ArrayVariable;

                    processor.Replace(instruction, Instruction.Create(OpCodes.Ldelem_Any, slice.GenericArgument));

                    processor.InsertAfter(parameter, new[] {
                        Instruction.Create(OpCodes.Ldloc, slice.OffsetVariable),
                        Instruction.Create(OpCodes.Add)
                    });
                }
                else if (methodDefinition.IsSetter)
                {
                    // Original SET:
                    // 1		ldarg segment	    $ Push the object to call
                    // =		ldloc.0		        $ Push the parameter
                    // =		ldc.r4 2		    $ Push the value to set
                    // 2		callvirt instance void class ArraySegment.ArraySlice`1<float32>::set_Item(int32, !0)
                    // -        nop			        $ Check if it even exists after SimplifyMacros in the collection.

                    // Target SET
                    // 1		ldloc data		    $ Push the array
                    // =		ldloc.0		        $ Push the parameter
                    // 2		ldloc offset
                    // 2		add                 $ Add the parameter (i) and the offset.
                    // =		ldc.r4 2		    $ Push the value to set. Use standard ldc with type and check if it  is optimized afterwards.
                    // 2		stelem              $ Use standard stelem with type and check if it is optimized afterwards.

                    //HACK: We rewrite it to avoid killing the loop.
                    objectToCall.OpCode  = OpCodes.Ldloc;
                    objectToCall.Operand = slice.ArrayVariable;

                    processor.Replace(instruction, Instruction.Create(OpCodes.Stelem_Any, slice.GenericArgument));

                    processor.InsertAfter(parameter, new[] {
                        Instruction.Create(OpCodes.Ldloc, slice.OffsetVariable),
                        Instruction.Create(OpCodes.Add)
                    });
                }
                else
                {
                    continue;
                }
            }
        }
Пример #33
0
        public override void OnExtractionSuccess(string filePath, IList <Directory> directories, string relativePath, TextWriter log, long streamPosition)
        {
            base.OnExtractionSuccess(filePath, directories, relativePath, log, streamPosition);

            try
            {
                using (var writer = OpenWriter(filePath))
                {
                    try
                    {
                        // Write any errors
                        if (directories.Any(d => d.HasError))
                        {
                            foreach (var directory in directories)
                            {
                                if (!directory.HasError)
                                {
                                    continue;
                                }
                                foreach (var error in directory.Errors)
                                {
                                    writer.Write("[ERROR: {0}] {1}\n", directory.Name, error);
                                }
                            }
                            writer.Write('\n');
                        }

                        // Write tag values for each directory
                        foreach (var directory in directories)
                        {
                            var directoryName = directory.Name;
                            foreach (var tag in directory.Tags)
                            {
                                var tagName     = tag.Name;
                                var description = tag.Description;

                                if (directory is FileMetadataDirectory && tag.Type == FileMetadataDirectory.TagFileModifiedDate)
                                {
                                    description = "<omitted for regression testing as checkout dependent>";
                                }

                                writer.Write("[{0} - 0x{1:x4}] {2} = {3}\n",
                                             directoryName, tag.Type, tagName, description);
                            }

                            if (directory.TagCount != 0)
                            {
                                writer.Write('\n');
                            }

                            var xmpDirectory = directory as XmpDirectory;
                            if (xmpDirectory?.XmpMeta != null)
                            {
                                var wrote = false;
                                foreach (var prop in xmpDirectory.XmpMeta.Properties)
                                {
                                    var value = prop.Value;
                                    if (value?.Length > 512)
                                    {
                                        value = value.Substring(0, 512) + $" <truncated from {value.Length} characters>";
                                    }
                                    writer.WriteLine($"[XMPMeta - {prop.Namespace}] {prop.Path} = {value}");
                                    wrote = true;
                                }
                                if (wrote)
                                {
                                    writer.Write('\n');
                                }
                            }
                        }

                        // Write file structure
                        var tree = directories.ToLookup(d => d.Parent);

                        void WriteLevel(Directory parent, int level)
                        {
                            const int indent = 4;

                            foreach (var child in tree[parent])
                            {
                                writer.Write(new string(' ', level * indent));
                                writer.Write($"- {child.Name}\n");
                                WriteLevel(child, level + 1);
                            }
                        }

                        WriteLevel(null, 0);

                        writer.Write('\n');
                    }
                    finally
                    {
                        writer.Write("Generated using metadata-extractor\n");
                        writer.Write("https://drewnoakes.com/code/exif/\n");
                    }
                }
            }
            catch (Exception e)
            {
                log.Write("Exception after extraction: {0}\n", e.Message);
            }
        }
Пример #34
0
        public bool WordBreak2(string s, IList <string> wordDict)
        {
            /*
             * 将一长串字符,拆分成已知的多个单词,是否可行
             * 思路:
             *  1.依据已知的单词,将串从头开始拆分,拆分成:已知的串+待拆分的串;-->大问题可以拆分成同类的小问题,可以考虑使用递归
             *  2.不同的拆分方法,最后可能面临相同的待拆分串;                  -->面临重复的子问题
             *  3.可以考虑使用备忘录的方式,将待拆分串与拆分结果关联起来;      -->做合理的剪枝,让回溯也能接近动态规划的效率
             *
             * 时间复杂度:O(n*m)
             * 空间复杂度:O(n*m)
             *
             * 考察点:
             *  1.回溯法 + 备忘录
             */

            //单词分组
            if (!charDic.Any())
            {
                charDic = wordDict.ToLookup(i => i[0], j => j).ToDictionary(i => i.Key, j => j.ToList());
            }

            //备忘录读取
            if (memoDic.ContainsKey(s))
            {
                return(memoDic[s]);
            }

            //特殊情况处理
            if (string.IsNullOrWhiteSpace(s))
            {
                return(true);
            }

            //正常的业务比较
            var firstChar = s[0];
            var words     = charDic.ContainsKey(firstChar) ? charDic[firstChar] : new List <string>();

            foreach (var wordItem in words)
            {
                if (s.Length < wordItem.Length)
                {
                    continue;
                }
                if (s.Substring(0, wordItem.Length) != wordItem)
                {
                    continue;
                }

                var newStr = new string(s.Skip(wordItem.Length).Take(s.Length - wordItem.Length).ToArray());
                if (WordBreak(newStr, wordDict))
                {
                    memoDic[newStr] = true;
                    return(true);
                }
                else
                {
                    memoDic[newStr] = false;
                }
            }

            return(false);
        }