Ejemplo n.º 1
0
 public void StartDraining(Action onRequestsDrained)
 {
     if (_allPendingRequests.IsEmpty())
     {
         onRequestsDrained?.Invoke();
         return;
     }
     _draining          = true;
     _onRequestsDrained = onRequestsDrained;
 }
Ejemplo n.º 2
0
 void NotifyTermination(int id)
 {
     ids.TryRemove(id);
     if (ids.IsEmpty())
     {
         if (uiCanvas != null)
         {
             uiCanvas.Hide();
         }
         else
         {
             InvokeAndClearShownActionList();
         }
     }
 }
Ejemplo n.º 3
0
        public virtual void TestListDirectory()
        {
            FilePath dir = new FilePath("testListDirectory");

            Files.CreateDirectory(dir.ToPath());
            try
            {
                ICollection <string> entries = new HashSet <string>();
                entries.AddItem("entry1");
                entries.AddItem("entry2");
                entries.AddItem("entry3");
                foreach (string entry in entries)
                {
                    Files.CreateDirectory(new FilePath(dir, entry).ToPath());
                }
                IList <string> list = IOUtils.ListDirectory(dir, TestIOUtils.NoEntry3Filter.Instance
                                                            );
                foreach (string entry_1 in list)
                {
                    Assert.True(entries.Remove(entry_1));
                }
                Assert.True(entries.Contains("entry3"));
                list = IOUtils.ListDirectory(dir, null);
                foreach (string entry_2 in list)
                {
                    entries.Remove(entry_2);
                }
                Assert.True(entries.IsEmpty());
            }
            finally
            {
                FileUtils.DeleteDirectory(dir);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// The set is connected if the set of points are neighbor-connected, and isNeighborsConnected return true for each
        /// two neighbors in the set.Two points are connected if they are neighbors, or one point has
        /// a neighbor that is neighbor-connected with the other point.
        ///
        /// Another way to put this is, this function returns true if there is a set that connects point1
        /// to point2.
        /// </summary>
        /// <example>
        /// Checks whether the two points are connected by color.
        /// <code>
        /// IsConnected(grid, p1, p2, (p, q) => grid[p].Color == grid[q].Color)
        /// </code>
        /// </example>
        /// <typeparam name="TCell">The type of cell of the grid that this algorithm takes.</typeparam>
        /// <typeparam name="TPoint">The type of point of the grid that this algorithm takes.</typeparam>
        /// <param name="grid">The grid on which to do the check</param>
        /// <param name="point1">The first point to check.</param>
        /// <param name="point2">The second point to check.</param>
        /// <param name="getAllNeighbors">The function to use to get all neighbors of the grid.</param>
        /// <param name="isNeighborsConnected">The function to use to check whether two neighbors are connected.</param>
        /// <returns>Returns true if the two points are in a connected set.</returns>
        public static bool IsConnected <TPoint, TCell>(
            IGrid <TPoint, TCell> grid,
            TPoint point1,
            TPoint point2,
            Func <TPoint, IEnumerable <TPoint> > getAllNeighbors,
            Func <TPoint, TPoint, bool> isNeighborsConnected)
        {
            var openSet = new HashSet <TPoint>()
            {
                point1
            };
            var closedSet = new HashSet <TPoint>();

            while (!openSet.IsEmpty())
            {
                var current = openSet.First();

                if (current.Equals(point2))
                {
                    return(true);
                }

                openSet.Remove(current);
                closedSet.Add(current);

                var connectedNeighbors =
                    from neighbor in getAllNeighbors(current).In(grid)
                    where !closedSet.Contains(neighbor) && isNeighborsConnected(current, neighbor)
                    select neighbor;

                openSet.AddRange(connectedNeighbors);
            }

            return(false);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// TODO: @herman
        /// </summary>
        /// <typeparam name="TCell">The type of cell of the grid that this algorithm takes.</typeparam>
        /// <typeparam name="TPoint">The type of point of the grid that this algorithm takes.</typeparam>
        /// <param name="grid">The grid from which to get the connected set.</param>
        /// <param name="point">Point where the check start.</param>
        /// <param name="getConnectedPoints">This function is used to get the connected Points.</param>
        /// <returns>Returns a list of points connected to the given point.</returns>
        // TODO to Explicit shape
        public static HashSet <TPoint> GetConnectedSet <TCell, TPoint>(
            IGrid <TPoint, TCell> grid,
            TPoint point,
            Func <TPoint, IEnumerable <TPoint> > getConnectedPoints)
        {
            var openSet = new HashSet <TPoint>()
            {
                point
            };
            var closedSet = new HashSet <TPoint>();

            while (!openSet.IsEmpty())
            {
                var current = openSet.First();

                openSet.Remove(current);
                closedSet.Add(current);

                var connectedNeighbors =
                    from neighbor in getConnectedPoints(current).In(grid)
                    where !closedSet.Contains(neighbor)
                    select neighbor;

                openSet.AddRange(connectedNeighbors);
            }

            return(closedSet);
        }
Ejemplo n.º 6
0
        /**
         *      Returns a list of points connected to the given point.
         *
         *      @param isNeighborsConnected The function to use to check whether two neighbors are connected
         *
         *      @tparam TCell the type of cell of the grid that this algorithm takes.
         *      @tparam TPoint the type of point of the grid that this algorithm takes.
         */
        public static HashSet <TPoint> GetConnectedSet <TCell, TPoint>(
            IGrid <TCell, TPoint> grid,
            TPoint point,
            Func <TPoint, TPoint, bool> isNeighborsConnected)

            where TPoint : IGridPoint <TPoint>
        {
            var openSet = new HashSet <TPoint>(new PointComparer <TPoint>())
            {
                point
            };
            var closedSet = new HashSet <TPoint>(new PointComparer <TPoint>());

            while (!openSet.IsEmpty())
            {
                var current = openSet.First();

                openSet.Remove(current);
                closedSet.Add(current);

                var connectedNeighbors =
                    from neighbor in grid.GetNeighbors(current)
                    where !closedSet.Contains(neighbor) && isNeighborsConnected(current, neighbor)
                    select neighbor;

                openSet.AddRange(connectedNeighbors);
            }

            return(closedSet);
        }
Ejemplo n.º 7
0
        /**
         *      Returns true if the collection of points are connected. The set is connected if
         *      the set of points are neighbor-connected, and isNeighborsConnected return true for each
         *      two neighbors in the set. Two points are connected if they are neighbors, or one point has
         *      a neighbor that is neighbor-connected with the other point.
         *
         *      @param grid the grid on which to do the check
         *      @param points the set of points to check. It is assumed all points are in the grid.
         *      @param isNeighborsConnected the function to use to check whether two neighbors are connected
         *
         *      @tparam TCell the type of cell of the grid that this algorithm takes.
         *      @tparam TPoint the type of point of the grid that this algorithm takes.
         *
         *      Example:
         *              //checks whether the list of points are connected by color.
         *              IsConnected(grid, points, (p, q) => grid[p].Color == grid[q].Color)
         *
         */
        //TODO: what should be done about points not in the grid?
        public static bool IsConnected <TCell, TPoint>(
            IGrid <TCell, TPoint> grid,
            IEnumerable <TPoint> points,
            Func <TPoint, TPoint, bool> isNeighborsConnected)

            where TPoint : IGridPoint <TPoint>
        {
            //What if collection is empty?

            var openSet   = new HashSet <TPoint>(new PointComparer <TPoint>());
            var closedSet = new HashSet <TPoint>(new PointComparer <TPoint>());

            openSet.Add(points.First());

            while (!openSet.IsEmpty())
            {
                var current = openSet.First();

                openSet.Remove(current);
                closedSet.Add(current);

                //Adds all connected neighbors that
                //are in the grid and in the collection
                var connectedNeighbors = from neighbor in grid.GetNeighbors(current)
                                         where !closedSet.Contains(neighbor) &&
                                         isNeighborsConnected(current, neighbor) &&
                                         points.Contains(neighbor)
                                         select neighbor;

                openSet.AddRange(connectedNeighbors);
            }

            return(points.All(closedSet.Contains));
        }
Ejemplo n.º 8
0
        public static bool ContainsAll <T>(this IEnumerable <T> collection, params T[] args)
            where T : IComparable <T>
        {
            collection.ThrowIfNull("The passed collection cannot be null.");

            args.ThrowIfNull("The passed arguments cannot be null.");

            var collectionHashSet = new HashSet <T>(collection);
            var argsHashSet       = new HashSet <T>(args);

            if (collectionHashSet.Count() < argsHashSet.Count())
            {
                foreach (var item in argsHashSet)
                {
                    collectionHashSet.Remove(item);
                }

                return(collection.IsEmpty());
            }

            foreach (var item in collectionHashSet)
            {
                argsHashSet.Remove(item);
            }

            return(argsHashSet.IsEmpty());
        }
Ejemplo n.º 9
0
        /// <summary>Add multiple node labels to repository</summary>
        /// <param name="labels">new node labels added</param>
        /// <exception cref="System.IO.IOException"/>
        public virtual void AddToCluserNodeLabels(ICollection <string> labels)
        {
            if (!nodeLabelsEnabled)
            {
                Log.Error(NodeLabelsNotEnabledErr);
                throw new IOException(NodeLabelsNotEnabledErr);
            }
            if (null == labels || labels.IsEmpty())
            {
                return;
            }
            ICollection <string> newLabels = new HashSet <string>();

            labels = NormalizeLabels(labels);
            // do a check before actual adding them, will throw exception if any of them
            // doesn't meet label name requirement
            foreach (string label in labels)
            {
                CheckAndThrowLabelName(label);
            }
            foreach (string label_1 in labels)
            {
                // shouldn't overwrite it to avoid changing the Label.resource
                if (this.labelCollections[label_1] == null)
                {
                    this.labelCollections[label_1] = new NodeLabel(label_1);
                    newLabels.AddItem(label_1);
                }
            }
            if (null != dispatcher && !newLabels.IsEmpty())
            {
                dispatcher.GetEventHandler().Handle(new StoreNewClusterNodeLabels(newLabels));
            }
            Log.Info("Add labels: [" + StringUtils.Join(labels.GetEnumerator(), ",") + "]");
        }
Ejemplo n.º 10
0
			public virtual void Predict(ICollection<string> predictedRelationsRaw, ICollection<string> goldRelationsRaw)
			{
				ICollection<string> predictedRelations = new HashSet<string>(predictedRelationsRaw);
				predictedRelations.Remove(KBPRelationExtractorConstants.NoRelation);
				ICollection<string> goldRelations = new HashSet<string>(goldRelationsRaw);
				goldRelations.Remove(KBPRelationExtractorConstants.NoRelation);
				// Register the prediction
				foreach (string pred in predictedRelations)
				{
					if (goldRelations.Contains(pred))
					{
						correctCount.IncrementCount(pred);
					}
					predictedCount.IncrementCount(pred);
				}
				goldRelations.ForEach(null);
				HashSet<string> allRelations = new HashSet<string>();
				Sharpen.Collections.AddAll(allRelations, predictedRelations);
				Sharpen.Collections.AddAll(allRelations, goldRelations);
				allRelations.ForEach(null);
				// Register the confusion matrix
				if (predictedRelations.Count == 1 && goldRelations.Count == 1)
				{
					confusion.Add(predictedRelations.GetEnumerator().Current, goldRelations.GetEnumerator().Current);
				}
				if (predictedRelations.Count == 1 && goldRelations.IsEmpty())
				{
					confusion.Add(predictedRelations.GetEnumerator().Current, "NR");
				}
				if (predictedRelations.IsEmpty() && goldRelations.Count == 1)
				{
					confusion.Add("NR", goldRelations.GetEnumerator().Current);
				}
			}
Ejemplo n.º 11
0
        private void Save()
        {
            HashSet <GameObject> prefabs = new HashSet <GameObject>();

            foreach (var pair in mod)
            {
                pair.Key.textKey = pair.Value;
                EditorUtil.SetDirty(pair.Key);
                GameObject p = PrefabUtility.FindPrefabRoot(pair.Key.gameObject);
                if (p != null)
                {
                    prefabs.Add(p);
                }
            }
            mod.Clear();
            if (!prefabs.IsEmpty())
            {
                foreach (GameObject p in prefabs)
                {
                    PrefabUtility.ReplacePrefab(p, PrefabUtility.GetCorrespondingObjectFromSource(p), ReplacePrefabOptions.ConnectToPrefab);
                }
                AssetDatabase.SaveAssets();
                EditorSceneManager.SaveOpenScenes();
            }
        }
Ejemplo n.º 12
0
        public virtual void RemoveOrTrackCompletedContainersFromContext(IList <ContainerId
                                                                               > containerIds)
        {
            ICollection <ContainerId> removedContainers = new HashSet <ContainerId>();

            Sharpen.Collections.AddAll(pendingContainersToRemove, containerIds);
            IEnumerator <ContainerId> iter = pendingContainersToRemove.GetEnumerator();

            while (iter.HasNext())
            {
                ContainerId containerId = iter.Next();
                // remove the container only if the container is at DONE state
                Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Container.Container nmContainer
                    = context.GetContainers()[containerId];
                if (nmContainer == null)
                {
                    iter.Remove();
                }
                else
                {
                    if (nmContainer.GetContainerState().Equals(ContainerState.Done))
                    {
                        Sharpen.Collections.Remove(context.GetContainers(), containerId);
                        removedContainers.AddItem(containerId);
                        iter.Remove();
                    }
                }
            }
            if (!removedContainers.IsEmpty())
            {
                Log.Info("Removed completed containers from NM context: " + removedContainers);
            }
            pendingCompletedContainers.Clear();
        }
Ejemplo n.º 13
0
        public void IsEmpty_Returns_True_When_Generic_HashSet_Is_Not_Null_But_Empty()
        {
            HashSet <string> testValue = new HashSet <string>();
            bool             result    = testValue.IsEmpty();

            Assert.True(result);
        }
Ejemplo n.º 14
0
        public void TestSetBehavior()
        {
            ISet<InterchangeablePair<EventBean, EventBean>> eventPairs = new HashSet<InterchangeablePair<EventBean, EventBean>>();

            EventBean[] events = new EventBean[4];
            for (int i = 0; i < events.Length; i++)
            {
                events[i] = SupportEventBeanFactory.CreateObject(
                    supportEventTypeFactory, new SupportBean("E" + i, i));
            }

            eventPairs.Add(new InterchangeablePair<EventBean, EventBean>(events[0], events[1]));
            eventPairs.Add(new InterchangeablePair<EventBean, EventBean>(events[0], events[2]));
            eventPairs.Add(new InterchangeablePair<EventBean, EventBean>(events[1], events[2]));
            Assert.AreEqual(3, eventPairs.Count);

            eventPairs.Add(new InterchangeablePair<EventBean, EventBean>(events[0], events[1]));
            eventPairs.Add(new InterchangeablePair<EventBean, EventBean>(events[1], events[2]));
            eventPairs.Add(new InterchangeablePair<EventBean, EventBean>(events[2], events[0]));
            eventPairs.Add(new InterchangeablePair<EventBean, EventBean>(events[2], events[1]));
            eventPairs.Add(new InterchangeablePair<EventBean, EventBean>(events[1], events[0]));
            Assert.AreEqual(3, eventPairs.Count);

            Assert.IsTrue(eventPairs.Contains(new InterchangeablePair<EventBean, EventBean>(events[1], events[0])));
            Assert.IsFalse(eventPairs.Contains(new InterchangeablePair<EventBean, EventBean>(events[3], events[0])));
            Assert.IsTrue(eventPairs.Contains(new InterchangeablePair<EventBean, EventBean>(events[1], events[2])));
            Assert.IsTrue(eventPairs.Contains(new InterchangeablePair<EventBean, EventBean>(events[2], events[0])));

            eventPairs.Remove(new InterchangeablePair<EventBean, EventBean>(events[2], events[0]));
            Assert.IsFalse(eventPairs.Contains(new InterchangeablePair<EventBean, EventBean>(events[2], events[0])));
            eventPairs.Remove(new InterchangeablePair<EventBean, EventBean>(events[1], events[2]));
            eventPairs.Remove(new InterchangeablePair<EventBean, EventBean>(events[1], events[0]));

            Assert.IsTrue(eventPairs.IsEmpty());
        }
Ejemplo n.º 15
0
        private static bool ContainsAnyImplementation(string source, IEnumerable<char> characters)
        {
            Debug.Assert(source != null, "source != null");
            Debug.Assert(characters != null, "characters != null");

            var hs = new HashSet<char>(characters);
            return !hs.IsEmpty() && source.Any(hs.Contains);
        }
Ejemplo n.º 16
0
        public static bool IsEquivalentTo <T>(this IEnumerable <T> source, IEnumerable <T> other,
                                              IEqualityComparer <T> comparer = null)
        {
            var set = new HashSet <T>(source, comparer ?? EqualityComparer <T> .Default);

            set.SymmetricExceptWith(other);
            return(set.IsEmpty());
        }
Ejemplo n.º 17
0
 public void RemoveLevel(BindingLevel level)
 {
     _levels.Remove(level);
     if (_levels.IsEmpty())
     {
         Clear();
     }
 }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            HashSet <int> set = new HashSet <int>();

            set.AddRange(new[] { 2, 3, 4, 4 });
            Console.WriteLine(set.IsEmpty());
            Console.WriteLine(string.Join(" ", set));
        }
Ejemplo n.º 19
0
        public void IsEmpty_Returns_False_When_Generic_HashSet_Is_Not_Null_And_Not_Empty()
        {
            HashSet <string> testValue = new HashSet <string>();

            testValue.Add("test");
            bool result = testValue.IsEmpty();

            Assert.False(result);
        }
Ejemplo n.º 20
0
        /// <exception cref="System.IO.IOException"></exception>
        private ObjectDirectory.CachedPackList ScanCachedPacks(ObjectDirectory.CachedPackList
                                                               old)
        {
            FileSnapshot s = FileSnapshot.Save(cachedPacksFile);

            byte[] buf;
            try
            {
                buf = IOUtil.ReadFully(cachedPacksFile);
            }
            catch (FileNotFoundException)
            {
                buf = new byte[0];
            }
            if (old != null && old.snapshot.Equals(s) && Arrays.Equals(old.raw, buf))
            {
                old.snapshot.SetClean(s);
                return(old);
            }
            AList <LocalCachedPack> list = new AList <LocalCachedPack>(4);
            ICollection <ObjectId>  tips = new HashSet <ObjectId>();
            int ptr = 0;

            while (ptr < buf.Length)
            {
                if (buf[ptr] == '#' || buf[ptr] == '\n')
                {
                    ptr = RawParseUtils.NextLF(buf, ptr);
                    continue;
                }
                if (buf[ptr] == '+')
                {
                    tips.AddItem(ObjectId.FromString(buf, ptr + 2));
                    ptr = RawParseUtils.NextLF(buf, ptr + 2);
                    continue;
                }
                IList <string> names = new AList <string>(4);
                while (ptr < buf.Length && buf[ptr] == 'P')
                {
                    int end = RawParseUtils.NextLF(buf, ptr);
                    if (buf[end - 1] == '\n')
                    {
                        end--;
                    }
                    names.AddItem(RawParseUtils.Decode(buf, ptr + 2, end));
                    ptr = RawParseUtils.NextLF(buf, end);
                }
                if (!tips.IsEmpty() && !names.IsEmpty())
                {
                    list.AddItem(new LocalCachedPack(this, tips, names));
                    tips = new HashSet <ObjectId>();
                }
            }
            list.TrimToSize();
            return(new ObjectDirectory.CachedPackList(s, Sharpen.Collections.UnmodifiableList
                                                          (list), buf));
        }
 public void LazyInjectAll()
 {
     while (!_instancesToInject.IsEmpty())
     {
         var instance = _instancesToInject.First();
         _instancesToInject.Remove(instance);
         _container.Inject(instance);
     }
 }
Ejemplo n.º 22
0
        public virtual void TestDirectory()
        {
            fs.Mkdirs(Dir1);
            // test empty directory
            RemoteIterator <LocatedFileStatus> itor = fs.ListFiles(Dir1, true);

            NUnit.Framework.Assert.IsFalse(itor.HasNext());
            itor = fs.ListFiles(Dir1, false);
            NUnit.Framework.Assert.IsFalse(itor.HasNext());
            // testing directory with 1 file
            WriteFile(fs, File2, FileLen);
            itor = fs.ListFiles(Dir1, true);
            LocatedFileStatus stat = itor.Next();

            NUnit.Framework.Assert.IsFalse(itor.HasNext());
            Assert.True(stat.IsFile());
            Assert.Equal(FileLen, stat.GetLen());
            Assert.Equal(fs.MakeQualified(File2), stat.GetPath());
            Assert.Equal(1, stat.GetBlockLocations().Length);
            itor = fs.ListFiles(Dir1, false);
            stat = itor.Next();
            NUnit.Framework.Assert.IsFalse(itor.HasNext());
            Assert.True(stat.IsFile());
            Assert.Equal(FileLen, stat.GetLen());
            Assert.Equal(fs.MakeQualified(File2), stat.GetPath());
            Assert.Equal(1, stat.GetBlockLocations().Length);
            // test more complicated directory
            WriteFile(fs, File1, FileLen);
            WriteFile(fs, File3, FileLen);
            ICollection <Path> filesToFind = new HashSet <Path>();

            filesToFind.AddItem(fs.MakeQualified(File1));
            filesToFind.AddItem(fs.MakeQualified(File2));
            filesToFind.AddItem(fs.MakeQualified(File3));
            itor = fs.ListFiles(TestDir, true);
            stat = itor.Next();
            Assert.True(stat.IsFile());
            Assert.True("Path " + stat.GetPath() + " unexpected", filesToFind
                        .Remove(stat.GetPath()));
            stat = itor.Next();
            Assert.True(stat.IsFile());
            Assert.True("Path " + stat.GetPath() + " unexpected", filesToFind
                        .Remove(stat.GetPath()));
            stat = itor.Next();
            Assert.True(stat.IsFile());
            Assert.True("Path " + stat.GetPath() + " unexpected", filesToFind
                        .Remove(stat.GetPath()));
            NUnit.Framework.Assert.IsFalse(itor.HasNext());
            Assert.True(filesToFind.IsEmpty());
            itor = fs.ListFiles(TestDir, false);
            stat = itor.Next();
            Assert.True(stat.IsFile());
            Assert.Equal(fs.MakeQualified(File1), stat.GetPath());
            NUnit.Framework.Assert.IsFalse(itor.HasNext());
            fs.Delete(TestDir, true);
        }
Ejemplo n.º 23
0
        public override IEnumerable <FileGroup> ScanDirectories(CancellationToken token)
        {
            var existingGroups =
                new HashSet <string>(GetGroups().Where(@group => group != _files).Select(@group => group.Name));
            IEnumerable <DirectoryTreeFileGroup> fileGroups =
                _directoryInfo.EnumerateDirectories()
                .Where(info => info.Name != ".picasaoriginals")
                .Where(info => !existingGroups.Remove(info.Name))
                .Select(info => new DirectoryTreeFileGroup(info.Name, info));


            var groups = new List <FileGroup>();

            foreach (DirectoryTreeFileGroup fileGroup in fileGroups)
            {
                token.ThrowIfCancellationRequested();
                groups.Add(fileGroup);
            }
            AddGroups(groups);

            if (!existingGroups.IsEmpty())
            {
                RemoveGroups(existingGroups);
            }

            var existingFiles = new HashSet <string>(_files.GetFiles().Select(file => file.FileName));
            IEnumerable <PictureFile.PictureFile> pictureFiles =
                PictureFile.PictureFile.FileNamePatterns.SelectMany(pattern => _directoryInfo.EnumerateFiles(pattern))
                .Distinct(new CompareFileNames())
                .Where(info => !info.Name.StartsWith("._"))
                .Where(info => !existingFiles.Remove(info.FullName))
                .Select(info => new PictureFile.PictureFile(info));
            var files = new List <PictureFile.PictureFile>();

            foreach (PictureFile.PictureFile pictureFile in pictureFiles)
            {
                token.ThrowIfCancellationRequested();
                files.Add(pictureFile);
                if (files.Count > 999)
                {
                    _files.AddFiles(files);
                    files = new List <PictureFile.PictureFile>();
                }
            }
            if (!files.IsEmpty())
            {
                _files.AddFiles(files);
            }
            if (!existingFiles.IsEmpty())
            {
                _files.RemoveFiles(existingFiles);
            }

            return(GetGroups());
        }
        public async Task <IEnumerable <ApiResource> > FindApiResourcesByNameAsync(IEnumerable <string> apiResourceNames)
        {
            var names        = new HashSet <string>(apiResourceNames);
            var apiResources = new List <ApiResource>();

            if (!names.IsEmpty())
            {
                apiResources.AddRange(_resources.ApiResources.Where(r => names.Contains(r.Name, StringComparer.Ordinal)));
            }
            return(await Task.FromResult(apiResources));
        }
        public async Task <IEnumerable <IdentityResource> > FindIdentityResourcesByScopeNameAsync(
            IEnumerable <string> scopeNames)
        {
            var names     = new HashSet <string>(scopeNames);
            var resources = new List <IdentityResource>();

            if (!names.IsEmpty())
            {
                resources.AddRange(_resources.IdentityResources.Where(r => names.Contains(r.Name, StringComparer.Ordinal)));
            }
            return(await Task.FromResult(resources));
        }
Ejemplo n.º 26
0
        public virtual void TestNullKeys()
        {
            JobConf          conf   = new JobConf(typeof(TestMapRed));
            FileSystem       fs     = FileSystem.GetLocal(conf);
            HashSet <string> values = new HashSet <string>();
            string           m      = "AAAAAAAAAAAAAA";

            for (int i = 1; i < 11; ++i)
            {
                values.AddItem(m);
                m = m.Replace((char)('A' + i - 1), (char)('A' + i));
            }
            Path testdir = new Path(Runtime.GetProperty("test.build.data", "/tmp")).MakeQualified
                               (fs);

            fs.Delete(testdir, true);
            Path inFile = new Path(testdir, "nullin/blah");

            SequenceFile.Writer w = SequenceFile.CreateWriter(fs, conf, inFile, typeof(NullWritable
                                                                                       ), typeof(Text), SequenceFile.CompressionType.None);
            Text t = new Text();

            foreach (string s in values)
            {
                t.Set(s);
                w.Append(NullWritable.Get(), t);
            }
            w.Close();
            FileInputFormat.SetInputPaths(conf, inFile);
            FileOutputFormat.SetOutputPath(conf, new Path(testdir, "nullout"));
            conf.SetMapperClass(typeof(TestMapRed.NullMapper));
            conf.SetReducerClass(typeof(IdentityReducer));
            conf.SetOutputKeyClass(typeof(NullWritable));
            conf.SetOutputValueClass(typeof(Text));
            conf.SetInputFormat(typeof(SequenceFileInputFormat));
            conf.SetOutputFormat(typeof(SequenceFileOutputFormat));
            conf.SetNumReduceTasks(1);
            conf.Set(MRConfig.FrameworkName, MRConfig.LocalFrameworkName);
            JobClient.RunJob(conf);
            // Since null keys all equal, allow any ordering
            SequenceFile.Reader r = new SequenceFile.Reader(fs, new Path(testdir, "nullout/part-00000"
                                                                         ), conf);
            m = "AAAAAAAAAAAAAA";
            for (int i_1 = 1; r.Next(NullWritable.Get(), t); ++i_1)
            {
                NUnit.Framework.Assert.IsTrue("Unexpected value: " + t, values.Remove(t.ToString(
                                                                                          )));
                m = m.Replace((char)('A' + i_1 - 1), (char)('A' + i_1));
            }
            NUnit.Framework.Assert.IsTrue("Missing values: " + values.ToString(), values.IsEmpty
                                              ());
        }
Ejemplo n.º 27
0
        // what are the dependencies that the given deployment provides to other modules?
        public static EPDeploymentDependencyProvided GetDependenciesProvided(
            string selfDeploymentId,
            EPServicesPath paths,
            DeploymentLifecycleService deploymentLifecycleService)
        {
            DeploymentInternal selfDeployment = deploymentLifecycleService.GetDeploymentById(selfDeploymentId);

            if (selfDeployment == null)
            {
                return(null);
            }

            IList <EPDeploymentDependencyProvided.Item> dependencies = new List <EPDeploymentDependencyProvided.Item>(4);
            string moduleName = selfDeployment.ModuleProvider.ModuleName;

            HandleProvided(selfDeployment.PathNamedWindows, EPObjectType.NAMEDWINDOW, paths.NamedWindowPathRegistry, moduleName, dependencies, name => name);
            HandleProvided(selfDeployment.PathTables, EPObjectType.TABLE, paths.TablePathRegistry, moduleName, dependencies, name => name);
            HandleProvided(selfDeployment.PathVariables, EPObjectType.VARIABLE, paths.VariablePathRegistry, moduleName, dependencies, name => name);
            HandleProvided(selfDeployment.PathContexts, EPObjectType.CONTEXT, paths.ContextPathRegistry, moduleName, dependencies, name => name);
            HandleProvided(selfDeployment.PathEventTypes, EPObjectType.EVENTTYPE, paths.EventTypePathRegistry, moduleName, dependencies, name => name);
            HandleProvided(selfDeployment.PathExprDecls, EPObjectType.EXPRESSION, paths.ExprDeclaredPathRegistry, moduleName, dependencies, name => name);
            HandleProvided(selfDeployment.PathScripts, EPObjectType.SCRIPT, paths.ScriptPathRegistry, moduleName, dependencies, SCRIPT_OBJECTNAME);
            HandleProvided(
                selfDeployment.PathClassProvideds,
                EPObjectType.CLASSPROVIDED,
                paths.ClassProvidedPathRegistry,
                moduleName,
                dependencies,
                name => name);

            foreach (ModuleIndexMeta objectName in selfDeployment.PathIndexes)
            {
                EventTableIndexMetadata indexMetadata = GetIndexMetadata(objectName, moduleName, paths);
                if (indexMetadata == null)
                {
                    continue;
                }

                EventTableIndexMetadataEntry meta = indexMetadata.GetIndexEntryByName(objectName.IndexName);
                if (meta != null && meta.ReferringDeployments != null && meta.ReferringDeployments.Length > 0)
                {
                    ISet <string> referred = new HashSet <string>(Arrays.AsList(meta.ReferringDeployments));
                    referred.Remove(selfDeploymentId);
                    if (!referred.IsEmpty())
                    {
                        dependencies.Add(new EPDeploymentDependencyProvided.Item(EPObjectType.INDEX, INDEX_OBJECTNAME.Invoke(objectName), referred));
                    }
                }
            }

            return(new EPDeploymentDependencyProvided(dependencies));
        }
        private ICollection <string> RouteDataSources(ShardingRule shardingRule, TableRule tableRule, List <IRouteValue> databaseShardingValues)
        {
            if (databaseShardingValues.IsEmpty())
            {
                return(tableRule.GetActualDatasourceNames());
            }
            ICollection <string> result = new HashSet <string>(shardingRule.GetDatabaseShardingStrategy(tableRule).DoSharding(tableRule.GetActualDatasourceNames(), databaseShardingValues, this.Properties));

            ShardingAssert.If(result.IsEmpty(), "no database route info");
            ShardingAssert.Else(tableRule.GetActualDatasourceNames().All(o => result.Contains(o)), $"Some routed data sources do not belong to configured data sources. routed data sources: `{result}`, configured data sources: `{tableRule.GetActualDatasourceNames()}`");

            return(result);
        }
Ejemplo n.º 29
0
        void FinishLoadingTask(int loadingTaskId, IReadOnlyList <AssetBundleRecord> necessaryAssetBundleRecords)
        {
            foreach (AssetBundleRecord assetBundleRecord in necessaryAssetBundleRecords)
            {
                string assetBundleName = assetBundleRecord.AssetBundleName;

                HashSet <int> taskIds = loadingTaskIdSets.GetValue(assetBundleName);
                if (taskIds == null)
                {
                    errorReceiver.OnError(AssetBundleErrorCode.MissingTaskIdSetInTermination, $"cannot get task id set: {assetBundleName}");
                    return;
                }

                if (!taskIds.TryRemove(loadingTaskId))
                {
                    errorReceiver.OnError(AssetBundleErrorCode.FailureToRemoveTaskId, $"cannot remove task id: {assetBundleName}");
                    return;
                }

                if (taskIds.IsEmpty())
                {
                    if (!loadingTaskIdSets.TryRemove(assetBundleName))
                    {
                        errorReceiver.OnError(AssetBundleErrorCode.FailureToRemoveLoadingTaskIdSet, $"cannot remove loading task id set: {assetBundleName}");
                        return;
                    }
                    HashSetPool <int> .Pool.Put(ref taskIds);

                    AssetBundle unusingAssetBundle = loadedAssetBundles.GetValue(assetBundleName);
                    if (unusingAssetBundle == null)
                    {
                        errorReceiver.OnError(AssetBundleErrorCode.MissingLoadedAssetBundle, $"cannot get loaded asset bundle: {assetBundleName}");
                        return;
                    }

                    unusingAssetBundle.Unload(false);

                    if (!loadedAssetBundles.TryRemove(assetBundleName))
                    {
                        errorReceiver.OnError(AssetBundleErrorCode.FailureToRemoveLoadedAssetBundle, $"cannot remove loaded asset bundle: {assetBundleName}");
                        return;
                    }
                }
            }

            if (!loadingTasks.TryRemove(loadingTaskId))
            {
                errorReceiver.OnError(AssetBundleErrorCode.FailureToRemoveLoadingTask, "cannot remove loading task");
                return;
            }
        }
Ejemplo n.º 30
0
        public IActionResult EditDepartment(string id, HashSet <string> OwnerIds, HashSet <string> userGroupIds)
        {
            string successMsg = string.Empty;
            string errorMsg   = string.Empty;


            var dbDepartment = this.GetService <DepartmentService>().Get(id);

            if (dbDepartment == null)
            {
                errorMsg = id + "doesn't exist!";
                return(RedirectDepartment(successMsg, errorMsg));
            }

            if (!this.GetService <DepartmentService>().IsBoss(this.GetUserId(), dbDepartment.OwnerIds))
            {
                errorMsg = "You don't have right!";
                return(RedirectDepartment(successMsg, errorMsg));
            }

            if (OwnerIds.IsEmpty())
            {
                ViewData["Department"] = dbDepartment;
                ViewData["Owners"]     = this.GetService <UserService>().Get(o => o.UserType == UserType.Manager);
                ViewData["UserGroups"] = this.GetService <DepartmentService>().GetUserGroupsByOwnerId(this.GetUserId());
                return(View());
            }
            else
            {
                try
                {
                    dbDepartment.OwnerIds = OwnerIds;
                    var removeUserGroupIds = dbDepartment.UserGroups.Keys.Except(userGroupIds).ToList();

                    foreach (var item in removeUserGroupIds)
                    {
                        dbDepartment.UserGroups.Remove(item);
                    }

                    this.GetService <DepartmentService>().Update(dbDepartment);
                    successMsg = string.Format("Edit department({0}) successfully!", id);
                }
                catch (Exception ex)
                {
                    errorMsg = ex.Message;
                }

                return(RedirectDepartment(successMsg, errorMsg));
            }
        }
Ejemplo n.º 31
0
        public virtual ICollection <EventType> GetSupportedEvents()
        {
            ICollection <EventType> evts = new HashSet <EventType>();

            foreach (ILocationExtractionStrategy s in strategies)
            {
                ICollection <EventType> se = s.GetSupportedEvents();
                if (se != null)
                {
                    evts.AddAll(se);
                }
            }
            return(evts.IsEmpty() ? null : evts);
        }
        /// <summary>
        /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
        /// added later. 
        /// </summary>
        public new CSharpCompilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_RemoveSyntaxTrees, message: this.AssemblyName))
            {
                if (trees == null)
                {
                    throw new ArgumentNullException("trees");
                }

                if (trees.IsEmpty())
                {
                    return this;
                }

                bool referenceDirectivesChanged = false;
                var removeSet = new HashSet<SyntaxTree>();
                var declMap = rootNamespaces;
                var declTable = declarationTable;
                foreach (var tree in trees.Cast<CSharpSyntaxTree>())
                {
                    RemoveSyntaxTreeFromDeclarationMapAndTable(tree, ref declMap, ref declTable, ref referenceDirectivesChanged);
                    removeSet.Add(tree);
                }

                Debug.Assert(!removeSet.IsEmpty());

                // We're going to have to revise the ordinals of all
                // trees after the first one removed, so just build
                // a new map.
                var ordinalMap = ImmutableDictionary.Create<SyntaxTree, int>();
                var builder = ArrayBuilder<SyntaxTree>.GetInstance();
                int i = 0;
                foreach (var tree in this.SyntaxTrees)
                {
                    if (!removeSet.Contains(tree))
                    {
                        builder.Add(tree);
                        ordinalMap = ordinalMap.Add(tree, i++);
                    }
                }

                return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged);
            }
        }
Ejemplo n.º 33
0
		/// <summary>
		/// Expansion Algorithm
		/// http://json-ld.org/spec/latest/json-ld-api/#expansion-algorithm
		/// </summary>
		/// <param name="activeCtx"></param>
		/// <param name="activeProperty"></param>
		/// <param name="element"></param>
		/// <returns></returns>
		/// <exception cref="JsonLdError">JsonLdError</exception>
		/// <exception cref="JsonLD.Core.JsonLdError"></exception>
		public virtual JToken Expand(Context activeCtx, string activeProperty, JToken element
			)
		{
			// 1)
			if (element.IsNull())
			{
				return null;
			}
			// 3)
			if (element is JArray)
			{
				// 3.1)
                JArray result = new JArray();
				// 3.2)
                foreach (JToken item in (JArray)element)
				{
					// 3.2.1)
					JToken v = Expand(activeCtx, activeProperty, item);
					// 3.2.2)
					if (("@list".Equals(activeProperty) || "@list".Equals(activeCtx.GetContainer(activeProperty
						))) && (v is JArray || (v is JObject && ((IDictionary<string, JToken>)v).ContainsKey
						("@list"))))
					{
						throw new JsonLdError(JsonLdError.Error.ListOfLists, "lists of lists are not permitted."
							);
					}
					else
					{
						// 3.2.3)
						if (!v.IsNull())
						{
							if (v is JArray)
							{
								JsonLD.Collections.AddAll(result, (JArray)v);
							}
							else
							{
								result.Add(v);
							}
						}
					}
				}
				// 3.3)
				return result;
			}
			else
			{
				// 4)
				if (element is JObject)
				{
					// access helper
                    IDictionary<string, JToken> elem = (JObject)element;
					// 5)
					if (elem.ContainsKey("@context"))
					{
						activeCtx = activeCtx.Parse(elem["@context"]);
					}
					// 6)
                    JObject result = new JObject();
					// 7)
                    JArray keys = new JArray(element.GetKeys());
					keys.SortInPlace();
					foreach (string key in keys)
					{
						JToken value = elem[key];
						// 7.1)
						if (key.Equals("@context"))
						{
							continue;
						}
						// 7.2)
						string expandedProperty = activeCtx.ExpandIri(key, false, true, null, null);
                        JToken expandedValue = null;
						// 7.3)
						if (expandedProperty == null || (!expandedProperty.Contains(":") && !JsonLdUtils.IsKeyword
							(expandedProperty)))
						{
							continue;
						}
						// 7.4)
						if (JsonLdUtils.IsKeyword(expandedProperty))
						{
							// 7.4.1)
							if ("@reverse".Equals(activeProperty))
							{
								throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyMap, "a keyword cannot be used as a @reverse propery"
									);
							}
							// 7.4.2)
							if (result.ContainsKey(expandedProperty))
							{
								throw new JsonLdError(JsonLdError.Error.CollidingKeywords, expandedProperty + " already exists in result"
									);
							}
							// 7.4.3)
							if ("@id".Equals(expandedProperty))
							{
								if (!(value.Type == JTokenType.String))
								{
									throw new JsonLdError(JsonLdError.Error.InvalidIdValue, "value of @id must be a string"
										);
								}
								expandedValue = activeCtx.ExpandIri((string)value, true, false, null, null);
							}
							else
							{
								// 7.4.4)
								if ("@type".Equals(expandedProperty))
								{
                                    if (value is JArray)
									{
										expandedValue = new JArray();
										foreach (JToken v in (JArray)value)
										{
											if (v.Type != JTokenType.String)
											{
												throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a string or array of strings"
													);
											}
											((JArray)expandedValue).Add(activeCtx.ExpandIri((string)v, true, true, null
												, null));
										}
									}
									else
									{
										if (value.Type == JTokenType.String)
										{
											expandedValue = activeCtx.ExpandIri((string)value, true, true, null, null);
										}
										else
										{
											// TODO: SPEC: no mention of empty map check
											if (value is JObject)
											{
												if (((JObject)value).Count != 0)
												{
													throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a an empty object for framing"
														);
												}
												expandedValue = value;
											}
											else
											{
												throw new JsonLdError(JsonLdError.Error.InvalidTypeValue, "@type value must be a string or array of strings"
													);
											}
										}
									}
								}
								else
								{
									// 7.4.5)
									if ("@graph".Equals(expandedProperty))
									{
										expandedValue = Expand(activeCtx, "@graph", value);
									}
									else
									{
										// 7.4.6)
										if ("@value".Equals(expandedProperty))
										{
											if (!value.IsNull() && (value is JObject || value is JArray))
											{
												throw new JsonLdError(JsonLdError.Error.InvalidValueObjectValue, "value of " + expandedProperty
													 + " must be a scalar or null");
											}
											expandedValue = value;
											if (expandedValue.IsNull())
											{
												result["@value"] = null;
												continue;
											}
										}
										else
										{
											// 7.4.7)
											if ("@language".Equals(expandedProperty))
											{
												if (!(value.Type == JTokenType.String))
												{
													throw new JsonLdError(JsonLdError.Error.InvalidLanguageTaggedString, "Value of " 
														+ expandedProperty + " must be a string");
												}
												expandedValue = ((string)value).ToLower();
											}
											else
											{
												// 7.4.8)
												if ("@index".Equals(expandedProperty))
												{
													if (!(value.Type == JTokenType.String))
													{
														throw new JsonLdError(JsonLdError.Error.InvalidIndexValue, "Value of " + expandedProperty
															 + " must be a string");
													}
													expandedValue = value;
												}
												else
												{
													// 7.4.9)
													if ("@list".Equals(expandedProperty))
													{
														// 7.4.9.1)
														if (activeProperty == null || "@graph".Equals(activeProperty))
														{
															continue;
														}
														// 7.4.9.2)
														expandedValue = Expand(activeCtx, activeProperty, value);
														// NOTE: step not in the spec yet
                                                        if (!(expandedValue is JArray))
														{
                                                            JArray tmp = new JArray();
															tmp.Add(expandedValue);
															expandedValue = tmp;
														}
														// 7.4.9.3)
                                                        foreach (JToken o in (JArray)expandedValue)
														{
                                                            if (o is JObject && ((JObject)o).ContainsKey("@list"))
															{
																throw new JsonLdError(JsonLdError.Error.ListOfLists, "A list may not contain another list"
																	);
															}
														}
													}
													else
													{
														// 7.4.10)
														if ("@set".Equals(expandedProperty))
														{
															expandedValue = Expand(activeCtx, activeProperty, value);
														}
														else
														{
															// 7.4.11)
															if ("@reverse".Equals(expandedProperty))
															{
																if (!(value is JObject))
																{
																	throw new JsonLdError(JsonLdError.Error.InvalidReverseValue, "@reverse value must be an object"
																		);
																}
																// 7.4.11.1)
																expandedValue = Expand(activeCtx, "@reverse", value);
																// NOTE: algorithm assumes the result is a map
																// 7.4.11.2)
                                                                if (((IDictionary<string, JToken>)expandedValue).ContainsKey("@reverse"))
																{
                                                                    JObject reverse = (JObject)((JObject)expandedValue)["@reverse"];
																	foreach (string property in reverse.GetKeys())
																	{
                                                                        JToken item = reverse[property];
																		// 7.4.11.2.1)
																		if (!result.ContainsKey(property))
																		{
																			result[property] = new JArray();
																		}
																		// 7.4.11.2.2)
																		if (item is JArray)
																		{
                                                                            JsonLD.Collections.AddAll(((JArray)result[property]), (JArray)item);
																		}
																		else
																		{
                                                                            ((JArray)result[property]).Add(item);
																		}
																	}
																}
																// 7.4.11.3)
                                                                if (((JObject)expandedValue).Count > (((JObject)expandedValue).ContainsKey("@reverse") ? 1 : 0))
																{
																	// 7.4.11.3.1)
																	if (!result.ContainsKey("@reverse"))
																	{
                                                                        result["@reverse"] = new JObject();
																	}
																	// 7.4.11.3.2)
                                                                    JObject reverseMap = (JObject)result["@reverse"];
																	// 7.4.11.3.3)
                                                                    foreach (string property in expandedValue.GetKeys())
																	{
																		if ("@reverse".Equals(property))
																		{
																			continue;
																		}
																		// 7.4.11.3.3.1)
                                                                        JArray items = (JArray)((JObject)expandedValue)[property];
																		foreach (JToken item in items)
																		{
																			// 7.4.11.3.3.1.1)
                                                                            if (item is JObject && (((JObject)item).ContainsKey("@value") || ((JObject)item).ContainsKey("@list")))
																			{
																				throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyValue);
																			}
																			// 7.4.11.3.3.1.2)
																			if (!reverseMap.ContainsKey(property))
																			{
																				reverseMap[property] = new JArray();
																			}
																			// 7.4.11.3.3.1.3)
                                                                            ((JArray)reverseMap[property]).Add(item);
																		}
																	}
																}
																// 7.4.11.4)
																continue;
															}
															else
															{
																// TODO: SPEC no mention of @explicit etc in spec
																if ("@explicit".Equals(expandedProperty) || "@default".Equals(expandedProperty) ||
																	 "@embed".Equals(expandedProperty) || "@embedChildren".Equals(expandedProperty) 
																	|| "@omitDefault".Equals(expandedProperty))
																{
																	expandedValue = Expand(activeCtx, expandedProperty, value);
																}
															}
														}
													}
												}
											}
										}
									}
								}
							}
							// 7.4.12)
							if (!expandedValue.IsNull())
							{
								result[expandedProperty] = expandedValue;
							}
							// 7.4.13)
							continue;
						}
						else
						{
							// 7.5
							if ("@language".Equals(activeCtx.GetContainer(key)) && value is JObject)
							{
								// 7.5.1)
                                expandedValue = new JArray();
								// 7.5.2)
								foreach (string language in value.GetKeys())
								{
                                    JToken languageValue = ((IDictionary<string, JToken>)value)[language];
									// 7.5.2.1)
									if (!(languageValue is JArray))
									{
                                        JToken tmp = languageValue;
                                        languageValue = new JArray();
                                        ((JArray)languageValue).Add(tmp);
									}
									// 7.5.2.2)
                                    foreach (JToken item in (JArray)languageValue)
									{
										// 7.5.2.2.1)
										if (!(item.Type == JTokenType.String))
										{
											throw new JsonLdError(JsonLdError.Error.InvalidLanguageMapValue, "Expected " + item
												.ToString() + " to be a string");
										}
										// 7.5.2.2.2)
                                        JObject tmp = new JObject();
										tmp["@value"] = item;
										tmp["@language"] = language.ToLower();
										((JArray)expandedValue).Add(tmp);
									}
								}
							}
							else
							{
								// 7.6)
								if ("@index".Equals(activeCtx.GetContainer(key)) && value is JObject)
								{
									// 7.6.1)
									expandedValue = new JArray();
									// 7.6.2)
                                    JArray indexKeys = new JArray(value.GetKeys());
									indexKeys.SortInPlace();
									foreach (string index in indexKeys)
									{
										JToken indexValue = ((JObject)value)[index];
										// 7.6.2.1)
										if (!(indexValue is JArray))
										{
											JToken tmp = indexValue;
											indexValue = new JArray();
											((JArray)indexValue).Add(tmp);
										}
										// 7.6.2.2)
										indexValue = Expand(activeCtx, key, indexValue);
										// 7.6.2.3)
										foreach (JObject item in (JArray)indexValue)
										{
											// 7.6.2.3.1)
											if (!item.ContainsKey("@index"))
											{
												item["@index"] = index;
											}
											// 7.6.2.3.2)
											((JArray)expandedValue).Add(item);
										}
									}
								}
								else
								{
									// 7.7)
									expandedValue = Expand(activeCtx, key, value);
								}
							}
						}
						// 7.8)
						if (expandedValue.IsNull())
						{
							continue;
						}
						// 7.9)
						if ("@list".Equals(activeCtx.GetContainer(key)))
						{
							if (!(expandedValue is JObject) || !((JObject)expandedValue).ContainsKey("@list"))
							{
								JToken tmp = expandedValue;
								if (!(tmp is JArray))
								{
									tmp = new JArray();
									((JArray)tmp).Add(expandedValue);
								}
								expandedValue = new JObject();
								((JObject)expandedValue)["@list"] = tmp;
							}
						}
						// 7.10)
						if (activeCtx.IsReverseProperty(key))
						{
							// 7.10.1)
							if (!result.ContainsKey("@reverse"))
							{
								result["@reverse"] = new JObject();
							}
							// 7.10.2)
							JObject reverseMap = (JObject)result["@reverse"];
							// 7.10.3)
                            if (!(expandedValue is JArray))
							{
                                JToken tmp = expandedValue;
								expandedValue = new JArray();
								((JArray)expandedValue).Add(tmp);
							}
							// 7.10.4)
							foreach (JToken item in (JArray)expandedValue)
							{
								// 7.10.4.1)
								if (item is JObject && (((JObject)item).ContainsKey("@value") || ((JObject)item).ContainsKey("@list")))
								{
									throw new JsonLdError(JsonLdError.Error.InvalidReversePropertyValue);
								}
								// 7.10.4.2)
								if (!reverseMap.ContainsKey(expandedProperty))
								{
									reverseMap[expandedProperty] = new JArray();
								}
								// 7.10.4.3)
                                if (item is JArray)
								{
                                    JsonLD.Collections.AddAll(((JArray)reverseMap[expandedProperty]), (JArray)item);
								}
								else
								{
									((JArray)reverseMap[expandedProperty]).Add(item);
								}
							}
						}
						else
						{
							// 7.11)
							// 7.11.1)
							if (!result.ContainsKey(expandedProperty))
							{
								result[expandedProperty] = new JArray();
							}
							// 7.11.2)
                            if (expandedValue is JArray)
							{
                                JsonLD.Collections.AddAll(((JArray)result[expandedProperty]), (JArray)expandedValue);
							}
							else
							{
								((JArray)result[expandedProperty]).Add(expandedValue);
							}
						}
					}
					// 8)
					if (result.ContainsKey("@value"))
					{
						// 8.1)
						// TODO: is this method faster than just using containsKey for
						// each?
						ICollection<string> keySet = new HashSet<string>(result.GetKeys());
						keySet.Remove("@value");
						keySet.Remove("@index");
						bool langremoved = keySet.Remove("@language");
						bool typeremoved = keySet.Remove("@type");
						if ((langremoved && typeremoved) || !keySet.IsEmpty())
						{
							throw new JsonLdError(JsonLdError.Error.InvalidValueObject, "value object has unknown keys"
								);
						}
						// 8.2)
                        JToken rval = result["@value"];
						if (rval.IsNull())
						{
							// nothing else is possible with result if we set it to
							// null, so simply return it
							return null;
						}
						// 8.3)
						if (!(rval.Type == JTokenType.String) && result.ContainsKey("@language"))
						{
							throw new JsonLdError(JsonLdError.Error.InvalidLanguageTaggedValue, "when @language is used, @value must be a string"
								);
						}
						else
						{
							// 8.4)
							if (result.ContainsKey("@type"))
							{
								// TODO: is this enough for "is an IRI"
								if (!(result["@type"].Type == JTokenType.String) || ((string)result["@type"]).StartsWith("_:") ||
									 !((string)result["@type"]).Contains(":"))
								{
									throw new JsonLdError(JsonLdError.Error.InvalidTypedValue, "value of @type must be an IRI"
										);
								}
							}
						}
					}
					else
					{
						// 9)
						if (result.ContainsKey("@type"))
						{
                            JToken rtype = result["@type"];
							if (!(rtype is JArray))
							{
								JArray tmp = new JArray();
								tmp.Add(rtype);
								result["@type"] = tmp;
							}
						}
						else
						{
							// 10)
							if (result.ContainsKey("@set") || result.ContainsKey("@list"))
							{
								// 10.1)
								if (result.Count > (result.ContainsKey("@index") ? 2 : 1))
								{
									throw new JsonLdError(JsonLdError.Error.InvalidSetOrListObject, "@set or @list may only contain @index"
										);
								}
								// 10.2)
								if (result.ContainsKey("@set"))
								{
									// result becomes an array here, thus the remaining checks
									// will never be true from here on
									// so simply return the value rather than have to make
									// result an object and cast it with every
									// other use in the function.
									return result["@set"];
								}
							}
						}
					}
					// 11)
					if (result.ContainsKey("@language") && result.Count == 1)
					{
						result = null;
					}
					// 12)
					if (activeProperty == null || "@graph".Equals(activeProperty))
					{
						// 12.1)
						if (result != null && (result.Count == 0 || result.ContainsKey("@value") || result
							.ContainsKey("@list")))
						{
							result = null;
						}
						else
						{
							// 12.2)
							if (result != null && result.ContainsKey("@id") && result.Count == 1)
							{
								result = null;
							}
						}
					}
					// 13)
					return result;
				}
				else
				{
					// 2) If element is a scalar
					// 2.1)
					if (activeProperty == null || "@graph".Equals(activeProperty))
					{
						return null;
					}
					return activeCtx.ExpandValue(activeProperty, element);
				}
			}
		}
Ejemplo n.º 34
0
            getFuturesStatic(List< string> tickers , string futuresStaticMoniker, ICarbonClient client, string carbonEnv,
            out Tuple<List<Tuple<string, ContractMonths>> /*rootTickers*/, List<string> /*contracts*/> tickerSplitTuple,
            DateTime? vStartDate = null, DateTime? vEndDate = null, List<string> contractSortOrder = null )
        //------------------------------------------------------------------------------------------------
        {

            // Intialisation
            if (tickers == null)
            {
                tickers = new List<string>();
            }
            DateTime startDate, endDate;
            if (vStartDate == null)
            {
                startDate = DateTime.MinValue;
            }
            else
            {
                startDate = vStartDate.Value;
            }

            if (vStartDate == null)
            {
                endDate = DateTime.MaxValue;
            }
            else
            {
                endDate = vEndDate.Value;
            }
            if (contractSortOrder == null)
            {
                contractSortOrder = new List<string>();
            }

            string cacheKey = getCacheKey(tickers, futuresStaticMoniker, startDate, endDate, contractSortOrder);


            // Divide inputs according to whether they should be used for rolling futures or not
            tickerSplitTuple                                = splitRollingFuturesFromRawTickers(tickers);
            List<string> contractTickers                    = tickerSplitTuple.Item2;
            List<Tuple<string, ContractMonths>> rootTickers = tickerSplitTuple.Item1;

            
            // Get Static From cache here if we have it, tickersplittuple has been set.
            Frame<string, string> cachedValue;
            if (StaticCache_.TryGetValue(cacheKey, out cachedValue)) return cachedValue;
            
            // Get all the roots from list
            List< string> rollingFuturesIDs                 = new List<string>();
            foreach (var tup in rootTickers)
            {
                rollingFuturesIDs.Add(tup.Item1);
            }
            
            // Get test sets.
            //      This allows us to map back names used in futures static moniker, to our original inputs
            var bbgTickerMap            = processBBGTickerList(contractTickers); 
            HashSet<string> rollingSet  = new HashSet<string>(rollingFuturesIDs);
            HashSet<string> tickerSet   = new HashSet<string>(bbgTickerMap.Keys.AsEnumerable());

            // Processing inputs
            Frame<string, string> output;
            var rowList = new List<KeyValuePair<int/*id*/, Series<string, object>/*row*/>>();

            var df = client.GetDataFrame(futuresStaticMoniker);
            var tmp = df.ToList();
            var col = tmp[0].Value as List<object>;
            var ind = tmp[1].Value as List<object>;
            var dat = tmp[2].Value as List<object>;

            //Find it's first trade date col
            int firstTradeDtCol = 0;
            int futDeliveryDtCol = 0;
            int typeCol = 0;
            for (int j = 0; j < col.Count; ++j)
            {
                string heading = col[j].ToString();
                if (heading == "fut_first_trade_dt")
                {
                    firstTradeDtCol = j;
                }
                if (heading == "fut_dlv_dt_last")
                {
                    futDeliveryDtCol = j;
                }
                if(heading == "type")
                {
                    typeCol = j;
                }
            }

            //client.getdat
            SeriesBuilder<string> sb;
            int i;
            for (i = 0; i < ind.Count; ++i)
            {
                sb = new SeriesBuilder<string>();
                var data = dat[i] as List<object>;
                var contract = data[typeCol].ToString();
                string index = (string)ind[i];

                if ((tickerSet.IsEmpty() && rollingSet.IsEmpty())
                    || (!tickerSet.Contains(index) && !rollingSet.Contains(contract)))
                {
                    continue;
                }

                DateTime firstTradeDate = DateTime.ParseExact(data[firstTradeDtCol].ToString(), "%dd/%MM/%yyyy", CultureInfo.InvariantCulture);
                DateTime futDeliveryDate = DateTime.ParseExact(data[futDeliveryDtCol].ToString(), "%dd/%MM/%yyyy", CultureInfo.InvariantCulture);
                if (rollingSet.Contains(contract) && (futDeliveryDate < startDate || firstTradeDate > endDate))
                {
                    continue;
                }

                if (bbgTickerMap.ContainsKey(index))
                    sb.Add("ticker", bbgTickerMap[index]);
                else
                    sb.Add("ticker", index); // ignores the mappings, in the rolling contract case

                for (int h = 0; h < col.Count; ++h)
                {
                    sb.Add((string)col[h], data[h]);
                }

                rowList.Add(KeyValue.Create(i, sb.Series)); 
            }

            output = Frame.FromRows(rowList).IndexRows<string>("ticker", keepColumn: true);

            if (rootTickers.IsEmpty())
            {
                output = sortFrameByInput(output, tickers);
            }
            else
            {
                output = sortFrameByNaturalOrder(output, contractSortOrder);
            }

            StaticCache_.TryAdd(cacheKey, output.Clone());

            return output;

        }
Ejemplo n.º 35
0
		/// <exception cref="System.IO.IOException"></exception>
		private ObjectDirectory.CachedPackList ScanCachedPacks(ObjectDirectory.CachedPackList
			 old)
		{
			FileSnapshot s = FileSnapshot.Save(cachedPacksFile);
			byte[] buf;
			try
			{
				buf = IOUtil.ReadFully(cachedPacksFile);
			}
			catch (FileNotFoundException)
			{
				buf = new byte[0];
			}
			if (old != null && old.snapshot.Equals(s) && Arrays.Equals(old.raw, buf))
			{
				old.snapshot.SetClean(s);
				return old;
			}
			AList<LocalCachedPack> list = new AList<LocalCachedPack>(4);
			ICollection<ObjectId> tips = new HashSet<ObjectId>();
			int ptr = 0;
			while (ptr < buf.Length)
			{
				if (buf[ptr] == '#' || buf[ptr] == '\n')
				{
					ptr = RawParseUtils.NextLF(buf, ptr);
					continue;
				}
				if (buf[ptr] == '+')
				{
					tips.AddItem(ObjectId.FromString(buf, ptr + 2));
					ptr = RawParseUtils.NextLF(buf, ptr + 2);
					continue;
				}
				IList<string> names = new AList<string>(4);
				while (ptr < buf.Length && buf[ptr] == 'P')
				{
					int end = RawParseUtils.NextLF(buf, ptr);
					if (buf[end - 1] == '\n')
					{
						end--;
					}
					names.AddItem(RawParseUtils.Decode(buf, ptr + 2, end));
					ptr = RawParseUtils.NextLF(buf, end);
				}
				if (!tips.IsEmpty() && !names.IsEmpty())
				{
					list.AddItem(new LocalCachedPack(this, tips, names));
					tips = new HashSet<ObjectId>();
				}
			}
			list.TrimToSize();
			return new ObjectDirectory.CachedPackList(s, Sharpen.Collections.UnmodifiableList
				(list), buf);
		}
Ejemplo n.º 36
0
		/// <exception cref="System.IO.IOException"></exception>
		private void RecvWants()
		{
			HashSet<ObjectId> wantIds = new HashSet<ObjectId>();
			bool isFirst = true;
			for (; ; )
			{
				string line;
				try
				{
					line = pckIn.ReadString();
				}
				catch (EOFException eof)
				{
					if (isFirst)
					{
						break;
					}
					throw;
				}
				if (line == PacketLineIn.END)
				{
					break;
				}
				if (!line.StartsWith("want ") || line.Length < 45)
				{
					throw new PackProtocolException(MessageFormat.Format(JGitText.Get().expectedGot, 
						"want", line));
				}
				if (isFirst && line.Length > 45)
				{
					string opt = Sharpen.Runtime.Substring(line, 45);
					if (opt.StartsWith(" "))
					{
						opt = Sharpen.Runtime.Substring(opt, 1);
					}
					foreach (string c in opt.Split(" "))
					{
						options.AddItem(c);
					}
					line = Sharpen.Runtime.Substring(line, 0, 45);
				}
				wantIds.AddItem(ObjectId.FromString(Sharpen.Runtime.Substring(line, 5)));
				isFirst = false;
			}
			if (wantIds.IsEmpty())
			{
				return;
			}
			AsyncRevObjectQueue q = walk.ParseAny(wantIds.AsIterable (), true);
			try
			{
				for (; ; )
				{
					RevObject o;
					try
					{
						o = q.Next();
					}
					catch (IOException error)
					{
						throw new PackProtocolException(MessageFormat.Format(JGitText.Get().notValid, error
							.Message), error);
					}
					if (o == null)
					{
						break;
					}
					if (o.Has(WANT))
					{
					}
					else
					{
						// Already processed, the client repeated itself.
						if (o.Has(ADVERTISED))
						{
							o.Add(WANT);
							wantAll.AddItem(o);
							if (o is RevTag)
							{
								o = walk.Peel(o);
								if (o is RevCommit)
								{
									if (!o.Has(WANT))
									{
										o.Add(WANT);
										wantAll.AddItem(o);
									}
								}
							}
						}
						else
						{
							throw new PackProtocolException(MessageFormat.Format(JGitText.Get().notValid, o.Name
								));
						}
					}
				}
			}
			finally
			{
				q.Release();
			}
		}