static IEnumerable <string> GetSyllables(string word, bool english = false)
    {
        var vowelsArr = english
            ? new[] { 'a', 'e', 'i', 'o', 'u' }
            : new[] { 'а', 'о', 'у', 'и', 'э', 'ы', 'я', 'ю', 'е', 'ё' };
        var vowelsIndexes = new List <int>();
        var result        = new HashSet <string>();

        word = word.ToLower();

        for (var i = 0; i < word.Length; i++)
        {
            if (vowelsArr.Contains(word[i]))
            {
                vowelsIndexes.Add(i);
            }
        }

        for (var i = vowelsIndexes.Count - 1; i > 0; i--)
        {
            if (vowelsIndexes[i] - vowelsIndexes[i - 1] == 1)
            {
                continue;
            }
            var consonantCount = vowelsIndexes[i] - vowelsIndexes[i - 1] - 1;
            var startIndex     = vowelsIndexes[i - 1] + 1 + consonantCount / 2;
            result.Add(word.Substring(startIndex));
            word = word.Remove(startIndex);
        }
        result.Add(word);

        return(result.Reverse());
    }
Exemple #2
0
        public IEnumerable <IFeatureInfo> GetFeatureDependencies(string featureId)
        {
            EnsureInitialized();

            return(_featureDependencies.GetOrAdd(featureId, (key) => new Lazy <IEnumerable <IFeatureInfo> >(() =>
            {
                if (!_features.ContainsKey(key))
                {
                    return Enumerable.Empty <IFeatureInfo>();
                }

                var feature = _features[key].FeatureInfo;

                var dependencies = new HashSet <IFeatureInfo>()
                {
                    feature
                };
                var stack = new Stack <IFeatureInfo[]>();

                stack.Push(GetFeatureDependenciesFunc(feature, _allOrderedFeatureInfos));

                while (stack.Count > 0)
                {
                    var next = stack.Pop();
                    foreach (var dependency in next.Where(dependency => !dependencies.Contains(dependency)))
                    {
                        dependencies.Add(dependency);
                        stack.Push(GetFeatureDependenciesFunc(dependency, _allOrderedFeatureInfos));
                    }
                }

                return dependencies.Reverse();
            })).Value);
        }
Exemple #3
0
        /// <summary>
        /// decodes the contexts at the current position </summary>
        protected internal virtual ISet <BytesRef> DecodeContexts(BytesRef scratch, ByteArrayDataInput tmpInput)
        {
            tmpInput.Reset(scratch.Bytes);
            tmpInput.SkipBytes(scratch.Length - 2); //skip to context set size
            ushort ctxSetSize = (ushort)tmpInput.ReadShort();

            scratch.Length -= 2;

            var contextSet = new HashSet <BytesRef>();

            for (ushort i = 0; i < ctxSetSize; i++)
            {
                tmpInput.Position = scratch.Length - 2;
                ushort curContextLength = (ushort)tmpInput.ReadShort();
                scratch.Length   -= 2;
                tmpInput.Position = scratch.Length - curContextLength;
                BytesRef contextSpare = new BytesRef(curContextLength);
                tmpInput.ReadBytes(contextSpare.Bytes, 0, curContextLength);
                contextSpare.Length = curContextLength;
                contextSet.Add(contextSpare);
                scratch.Length -= curContextLength;
            }

            // LUCENENET TODO: We are writing the data forward.
            // Not sure exactly why, but when we read it back it
            // is reversed. So, we need to fix that before returning the result.
            // If the underlying problem is found and fixed, then this line can just be
            // return contextSet;
            return(new HashSet <BytesRef>(contextSet.Reverse()));
        }
Exemple #4
0
        private string Part2(HashSet <int> possibleRows)
        {
            var reverseList = possibleRows.Reverse();
            var finishTest  = false;
            var itteration  = 0;
            var finalAcc    = 0;

            while (finishTest == false)
            {
                var rowToTest = reverseList.ElementAt(itteration);
                var tempRow   = dayInput[rowToTest];
                var tempSplit = tempRow.Split(" ");
                if (tempSplit[0] == "jmp")
                {
                    dayInput[rowToTest] = "nop " + tempSplit[1];
                }
                else if (tempSplit[0] == "nop")
                {
                    dayInput[rowToTest] = "jmp " + tempSplit[1];
                }

                var testRun = RetriveAccumulation(dayInput);

                if (testRun.Value == true)
                {
                    finalAcc   = testRun.Key;
                    finishTest = testRun.Value;
                }

                dayInput[rowToTest] = tempRow;
                itteration++;
            }
            return(string.Format("Part2: {0}", finalAcc));
        }
        /// <summary>
        /// Returns all shortest paths in a graph
        /// </summary>
        public HashSet <ShortestPathSet <T> > GetAllShortestPathsInGraph(HashSet <Node <T> > nodes)
        {
            HashSet <ShortestPathSet <T> > shortestPaths = new HashSet <ShortestPathSet <T> >();

            for (int i = 0; i < nodes.Count; i++)
            {
                Node <T> nodei = nodes.ElementAt(i);
                for (int j = i + 1; j < nodes.Count; j++)
                {
                    Node <T> nodej = nodes.ElementAt(j);
                    {
                        Func <Node <T>, HashSet <Node <T> > > shortestPath = ShortestPathFunction(nodei);
                        HashSet <Node <T> > path = shortestPath(nodej);
                        shortestPaths.Add(new ShortestPathSet <T>()
                        {
                            StartNode = nodei, EndNode = nodej, ShortestPath = path
                        });
                        IEnumerable <Node <T> > reversePath = path.Reverse();
                        shortestPaths.Add(new ShortestPathSet <T>()
                        {
                            StartNode = nodej, EndNode = nodei, ShortestPath = new HashSet <Node <T> >(reversePath)
                        });
                    }
                }
            }
            return(shortestPaths);
        }
Exemple #6
0
    public IEnumerator DomainClashResult(int aDomainRemoved)
    {
        int i = 0;

        foreach (FloorNode node in m_NodeInDomainRange.Reverse())
        {
            if (i == aDomainRemoved)
            {
                break;
            }

            i++;

            //  GameManager.Instance.mMCombatCameraController.m_CameraPositionInGrid = node.m_PositionInGrid;
            m_NodeInDomainRange.Remove(node);


            if (i < 10)
            {
                yield return(new WaitForSeconds(1.0f / i));
            }
            else
            {
                yield return(new WaitForSeconds(0.1f));
            }
        }
    }
Exemple #7
0
        public IEnumerable <IFeatureInfo> GetFeatureDependencies(string featureId)
        {
            return(_featureDependencies.GetOrAdd(featureId, (key) =>
            {
                var unorderedFeatures = GetAllUnorderedFeatures().ToArray();

                var feature = unorderedFeatures.FirstOrDefault(x => x.Id == key);
                if (feature == null)
                {
                    return Enumerable.Empty <IFeatureInfo>();
                }

                var dependencies = new HashSet <IFeatureInfo>()
                {
                    feature
                };
                var stack = new Stack <IFeatureInfo[]>();

                stack.Push(GetFeatureDependenciesFunc(feature, unorderedFeatures));

                while (stack.Count > 0)
                {
                    var next = stack.Pop();
                    foreach (var dependency in next.Where(dependency => !dependencies.Contains(dependency)))
                    {
                        dependencies.Add(dependency);
                        stack.Push(GetFeatureDependenciesFunc(dependency, unorderedFeatures));
                    }
                }

                return dependencies.Reverse();
            }));
        }
        public override void WritePacket()
        {
            var root = DefaultCommands.GetCommands();
            HashSet <CommandNode> nodes = new HashSet <CommandNode>();
            HashSet <CommandNode> Work  = new HashSet <CommandNode>()
            {
                root
            };

            while (Work.Count != 0)
            {
                foreach (var v in Work.ToArray())
                {
                    nodes.Add(v);
                    Work.Remove(v);
                    foreach (var v2 in v.CommandNodes)
                    {
                        if (v2.GetType() != typeof(FunctionCommandNode))
                        {
                            Work.Add(v2);
                        }
                    }
                }
            }
            var array = nodes.Reverse().ToArray();

            Write((VarInt)array.Length);
            foreach (var v in array)
            {
                WriteNode(v, array);
            }
            var rootI = Array.IndexOf(array, array.First(x => x.GetType() == typeof(RootCommandNode)));

            Write((VarInt)rootI);
        }
        public static bool execute(KevoreeCoreBean originCore, IContainerNodeMarshalled rootNode, AdaptationModel adaptionModel, NodeType nodeInstance, Func<bool> afterUpdateFunc, Func<bool> preRollBack, Func<bool> postRollback)
        {
            var processedActions = new HashSet<AdaptationPrimitive>();
            bool success = true;
            foreach (AdaptationPrimitive action in adaptionModel.ToArray())
            {
                processedActions.Add(action);
                var resultAction = processAction(action, nodeInstance);
                if (!resultAction)
                {
                    success = false;
                    break;
                }
            }

            if (!success)
            {
                originCore.getLogger().Error("Adaptation failed");
                foreach (var act in processedActions.Reverse())
                {
                    processUndoAction(act, nodeInstance);
                }
            }
            else
            {
                originCore.getLogger().Debug("Adaptation succeeded");
            }
            return success;
        }
        public static HashSet <IState> PopulateStatesPartOfALoop(this HashSet <IState> statesTracker,
                                                                 IState currentState,
                                                                 HashSet <Transition> transitionsTracker,
                                                                 HashSet <IState> statesInALoop)
        {
            statesTracker.Add(currentState);
            foreach (var direction in currentState.Directions)
            {
                if (direction.Key.Equals(currentState))
                {
                    continue;
                }
                if (statesTracker.Contains(direction.Key))
                {
                    if (!direction.Value.Contains(new DirectionValue {
                        Letter = Alphabet.EPSILON_LETTER
                    }))
                    {
                        statesInALoop.Add(direction.Key);
                        break;
                    }

                    foreach (var transition in transitionsTracker.Reverse())
                    {
                        if (transition.From.Equals(direction.Key))
                        {
                            if (!transition.Value.Letter.IsEpsilon &&
                                transition.To.CanReachStates(new HashSet <IState>()
                            {
                                currentState
                            }))
                            {
                                statesInALoop.Add(direction.Key);
                            }
                            break;
                        }
                        if (!transition.Value.Letter.IsEpsilon &&
                            !transition.From.Equals(currentState) &&
                            transition.From.CanReachStates(new HashSet <IState>()
                        {
                            direction.Key
                        }))
                        {
                            statesInALoop.Add(direction.Key);
                            break;
                        }
                    }
                }
                else
                {
                    foreach (var value in direction.Value)
                    {
                        transitionsTracker.Add(new Transition(1, currentState, direction.Key, value));
                    }
                    PopulateStatesPartOfALoop(statesTracker, direction.Key, transitionsTracker, statesInALoop);
                }
            }
            statesTracker.Remove(currentState);
            return(statesInALoop);
        }
Exemple #11
0
        public string PathFromRoot()
        {
            HashSet <ProblemState> states = new HashSet <ProblemState> {
                State
            };
            Node node = Parent;

            while (node != null)
            {
                states.Add(node.State);
                node = node.Parent;
            }

            states = states.Reverse().ToHashSet();
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < states.Count; i++)
            {
                ProblemState nextState = states.ElementAt(i);
                sb.Append(nextState);

                if (i + 1 != states.Count)
                {
                    sb.Append("->");
                }
            }

            return(sb.ToString());
        }
Exemple #12
0
        private void GetSolution(bool result)
        {
            Console.WriteLine(longName + " : " + code);
            char[] delimiters = new char[] { '=', '>' };

            if (result)
            {
                HashSet <string> set = new HashSet <string>();
                foreach (string item in knowledgeBase)
                {
                    string[] val = item.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                    if (val.Length == 1)
                    {
                        set.Add(val[0]);
                    }
                    else
                    {
                        set.Add(val[1]);
                    }
                }

                Console.WriteLine("Yes: " + string.Join(",", set.Reverse()));
            }
            else
            {
                Console.WriteLine("NO:");
            }
        }
Exemple #13
0
 public void RemoveDuplicates()
 {
     Infos.Reverse();
     Infos = Infos.GroupBy(i => i.Id)
             .Select(i => i.First())
             .ToHashSet();
     Infos.Reverse();
 }
Exemple #14
0
 public void CleanupDuplicatedInfos()
 {
     Infos.Reverse();
     Infos = Infos.GroupBy(i => i.Id)
             .Select(i => i.First())
             .ToHashSet();
     Infos.Reverse();
 }
 /// <summary>
 /// 全てのDetectorの解除
 /// </summary>
 public void ReleaseAllDetector()
 {
     foreach (var d in detectors.Reverse())
     {
         ReleaseDetector(d);
     }
     detectors.Clear();
 }
Exemple #16
0
 /// <summary>
 /// 全てのオブジェクトの解除
 /// </summary>
 public void ReleaseAllObject()
 {
     foreach (var o in objects.Reverse())
     {
         ReleaseObject(o);
     }
     objects.Clear();
 }
Exemple #17
0
        public async Task <HashSet <PathNode> > GetPath(Point start, Point end)
        {
            var startNode = new PathNode(start.X, start.Y, null, end);

            var path = new HashSet <PathNode>();

            await Task.Factory.StartNew(() =>
            {
                var closedList = new HashSet <PathNode>();
                var openList   = new HashSet <PathNode>();
                var curNode    = startNode;

                openList.Add(curNode);

                do
                {
                    closedList.Add(curNode);
                    openList.Remove(curNode);

                    foreach (var i in curNode.Neighbors().OrderBy(_ => _.F))
                    {
                        if (i.Point == end)
                        {
                            closedList.Add(i);
                            goto AssignPath;
                        }

                        if (!openList.Contains(i) && !closedList.Contains(i))
                        {
                            openList.Add(i);
                        }
                    }

                    curNode = openList.OrderBy(_ => _.F).OrderBy(_ => _.H).FirstOrDefault();

                    if (curNode == null)
                    {
                        App.Warn("No path found!");
                        return;
                    }
                } while (!openList.ToList().Exists(_ => _.Point == end));

AssignPath:

                var endNode     = closedList.Where(_ => _.Point == end).FirstOrDefault();
                var curPathNode = endNode;

                while (curPathNode != startNode)
                {
                    path.Add(curPathNode);

                    curPathNode = curPathNode.Parent;
                }
            });

            return(path.Reverse().ToHashSet());
        }
Exemple #18
0
        private static string ComputeWord(HashSet <char> visitedNodes, List <char> sortedNodes)
        {
            HashSet <char> hashSet = new HashSet <char>(visitedNodes);

            hashSet.RemoveWhere(sortedNodes.Contains);
            IEnumerable <char> reverse = hashSet.Reverse();

            return($"{string.Join("", reverse)}");
        }
 private void SetItemSources(HashSet <Match> matchScheduleWithMatches, List <Team> homeTeamList, List <Team> visitorTeamList, bool reverse)
 {
     if (reverse)
     {
         matchProtocolList.ItemsSource  = matchScheduleWithMatches.Reverse();
         homeTeamListBox.ItemsSource    = homeTeamList.ToObservableCollection().Reverse();
         visitorTeamListBox.ItemsSource = visitorTeamList.ToObservableCollection().Reverse();
         dateListBox.ItemsSource        = matchScheduleWithMatches.Reverse();
         resultListBox.ItemsSource      = matchScheduleWithMatches.Reverse();
     }
     else
     {
         matchProtocolList.ItemsSource  = matchScheduleWithMatches;
         homeTeamListBox.ItemsSource    = homeTeamList;
         visitorTeamListBox.ItemsSource = visitorTeamList;
         dateListBox.ItemsSource        = matchScheduleWithMatches;
         resultListBox.ItemsSource      = matchScheduleWithMatches;
     }
 }
Exemple #20
0
 public Func <Unit, Task <S> > FoldBackAsync <S>(HashSet <A> fa, S state, Func <S, A, Task <S> > f) => _ =>
 {
     Task <S> s = Task.FromResult(state);
     foreach (var item in fa.Reverse())
     {
         s = from x in s
             from y in f(x, item)
             select y;
     }
     return(s);
 };
Exemple #21
0
 /// <summary>
 /// Reverses order of hashset
 /// </summary>
 /// <typeparam name="T">Hashset type</typeparam>
 /// <param name="set">Hashset to reverse</param>
 /// <returns> Hashset in reverse item order</returns>
 public static HashSet <T> ReverseHashSet <T>(this HashSet <T> set)
 {
     try
     {
         return(set?.Reverse().ToHashSet());
     }
     catch
     {
         return(null);
     }
 }
Exemple #22
0
        public static int RemoveDuplicates(int[] nums)
        {
            var set = new HashSet <int>(nums);
            int i   = 0;

            foreach (var s in set.Reverse())
            {
                nums[i] = s;
                i++;
            }
            return(set.Count());
        }
Exemple #23
0
        static void Main(string[] args)
        {
            DirectoryEntry searchRoot = new DirectoryEntry("LDAP://rootDSE");
            Object         domainDCs  = searchRoot.Properties["defaultNamingContext"][0];

            searchRoot.Dispose();

            Console.WriteLine("Domain is: " + domainDCs);

            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            String          username = identity.Name.Substring(identity.Name.IndexOf(@"\") + 1);


            DirectoryEntry userEntry = FindUserInActiveDirectory(domainDCs, username);

            if (userEntry == null)
            {
                Environment.Exit(100);
            }
            else
            {
                Console.WriteLine("Found user object in ActiveDirectory: " + userEntry.Name);
            }

            HashSet <DirectoryEntry> path = BuildOUPath(userEntry);

            Dictionary <char, String> nmlsPathes    = new Dictionary <char, string>();
            Dictionary <char, bool>   nmlsDelDrives = new Dictionary <char, bool>();

            foreach (DirectoryEntry elem in path.Reverse())
            {
                ReadNmlsUncPathfromLDAP(elem, nmlsPathes);
                ReadNmlsDelDriveFromLDAP(elem, nmlsDelDrives);
            }

            foreach (KeyValuePair <char, bool> item in nmlsDelDrives)
            {
                if (item.Value)
                {
                    // Console.WriteLine("Deleting drive " + item.Key);
                    MapNetworkDriveDisconnect(item.Key.ToString());
                }
            }

            foreach (KeyValuePair <char, string> item in nmlsPathes)
            {
                if (item.Value != null && item.Value != "")
                {
                    Console.WriteLine("Connecting drive " + item.Key + " with " + item.Value);
                    MapNetworkDriveConnect(item.Key.ToString(), item.Value);
                }
            }
        }
        public HashSet <T> GetPath(T from, T to, Dictionary <T, T> predecessors)
        {
            var resultPath = new HashSet <T>();

            for (var i = to; !i.Equals(from); i = predecessors[i])
            {
                resultPath.Add(i);
            }
            resultPath.Add(from);

            return(resultPath.Reverse().ToHashSet());
        }
Exemple #25
0
        public IEnumerable <T> GetCommonElements(Hierarchy <T> other)
        {
            var set = new HashSet <T>();

            foreach (var item in other.nodeByValue.Select(p => p.Key).ToArray())
            {
                if (this.nodeByValue.ContainsKey(item))
                {
                    set.Add(item);
                }
            }

            return(set.Reverse());
        }
Exemple #26
0
                private static void AddVRMappingToPrompt(ref string text, List <InputCommand> commandList)
                {
                    if (ControllerInput.buttonActions == null || ControllerInput.axisActions == null)
                    {
                        return;
                    }

                    var actionTexts = new HashSet <string>();


                    for (var i = 0; i < commandList.Count; i++)
                    {
                        var command = commandList[i];

                        if (command.GetType() == typeof(SingleAxisCommand))
                        {
                            var singleAxisCommand = (SingleAxisCommand)command;
                            var gamepadBinding    = singleAxisCommand.GetGamepadBinding();
                            if (gamepadBinding != null)
                            {
                                var button = gamepadBinding.gamepadButtonPos;
                                if (ControllerInput.buttonActions.ContainsKey(button))
                                {
                                    AddTextIfNotExisting(text, actionTexts, ControllerInput.buttonActions[button]);
                                }
                                var axis = gamepadBinding.axisID;
                                if (ControllerInput.axisActions.ContainsKey(axis))
                                {
                                    AddTextIfNotExisting(text, actionTexts, ControllerInput.axisActions[axis]);
                                }
                            }
                        }
                        else if (command.GetType() == typeof(DoubleAxisCommand))
                        {
                            var doubleAxisCommand = (DoubleAxisCommand)command;
                            var axis = doubleAxisCommand.GetGamepadAxis();
                            if (ControllerInput.axisActions.ContainsKey(axis))
                            {
                                AddTextIfNotExisting(text, actionTexts, ControllerInput.axisActions[axis]);
                            }
                        }
                    }

                    actionTexts.Reverse();
                    var cleanOriginalText = text.Replace("+", "");
                    var actionText        = string.Join(" + ", actionTexts.ToArray());

                    text = $"{actionText} {cleanOriginalText}";
                }
Exemple #27
0
        private static string DescribePath(Dictionary <string, string> parents)
        {
            var pathParts = new HashSet <string>();

            var pathPart = "Finish";

            while (pathPart != "Start")
            {
                pathParts.Add(pathPart);
                pathPart = parents[pathPart];
            }

            pathParts.Add("Start");
            return(string.Join(",", pathParts.Reverse()));
        }
        /// <summary>
        /// Shortest path function
        /// </summary>
        public Func <Node <T>, HashSet <Node <T> > > ShortestPathFunction(Node <T> start)
        {
            Dictionary <Node <T>, Node <T> > previous = new Dictionary <Node <T>, Node <T> >();

            Queue <Node <T> > queue = new Queue <Node <T> >();

            queue.Enqueue(start);

            while (queue.Count > 0)
            {
                Node <T>            node          = queue.Dequeue();
                HashSet <Node <T> > adjacentNodes = _graph.GetAdjacentNodes(node);
                foreach (Node <T> neighbor in adjacentNodes)
                {
                    if (previous.Keys.Any(x => x.Id == neighbor.Id))
                    {
                        continue;
                    }

                    previous[neighbor] = node;
                    queue.Enqueue(neighbor);
                }
            }

            Func <Node <T>, HashSet <Node <T> > > shortestPath = v =>
            {
                HashSet <Node <T> > path = new HashSet <Node <T> >();

                Node <T> current = v;

                while (current != null && !current.Equals(start))
                {
                    path.Add(current);

                    Node <T> current1 = current;
                    current = previous.Where(pair => pair.Key.Id == current1.Id)
                              .Select(pair => pair.Value)
                              .FirstOrDefault();
                }

                path.Add(start);
                path.Reverse();

                return(path);
            };

            return(shortestPath);
        }
Exemple #29
0
        IEnumerable <View> GetToplevelSubviews(bool isForward)
        {
            if (SuperView == null)
            {
                return(null);
            }

            HashSet <View> views = new HashSet <View> ();

            foreach (var v in SuperView.Subviews)
            {
                views.Add(v);
            }

            return(isForward ? views : views.Reverse());
        }
        /// <summary>
        /// 获取Voronoi多边形的线
        /// </summary>
        /// <param name="points"></param>
        /// <param name="envelope"></param>
        /// <param name="minDistanceTolerance"></param>
        /// <returns></returns>
        public static List <GraphEdge> BuildLine(List <TysonGeoPoint> points,
                                                 double[] envelope = null, double minDistanceTolerance = 1e-8)
        {
            envelope ??= GetEnvelope(points);

            double[] xVal = new double[points.Count];
            double[] yVal = new double[points.Count];

            var i = 0;

            foreach (var point in points)
            {
                xVal[i] = point.X;
                yVal[i] = point.Y;
                i      += 1;
            }

            var voronoiObject = new Voronoi(minDistanceTolerance);
            var graphEdgeList = voronoiObject.GenerateVoronoi(xVal, yVal,
                                                              envelope[0], envelope[2],
                                                              envelope[1], envelope[3]);
            var graphEdges   = new HashSet <GraphEdge>(graphEdgeList).ToList();
            var index        = 0;
            var removeIndexs = new HashSet <int>();

            foreach (var graphEdge in graphEdges)
            {
                var edgeLinePt1 = graphEdge.Start;
                var edgeLinePt2 = graphEdge.End;
                if (edgeLinePt1 == edgeLinePt2)
                {
                    removeIndexs.Add(index);
                }

                index++;
            }


            removeIndexs.Reverse();
            foreach (var i1 in removeIndexs)
            {
                graphEdges.RemoveAt(i1);
            }

            return(graphEdges);
        }
Exemple #31
0
        private IList <int> GetParendIds(int id)
        {
            var dic = DefaultStorage.ModuleIdDic();
            var hs  = new HashSet <int>();

            hs.Add(id);
            var i = id;

            while (i > 0)
            {
                i = dic[i];
                if (i > 0)
                {
                    hs.Add(i);
                }
            }
            return(hs.Reverse().ToList());
        }
Exemple #32
0
 static void Recurse(int n, int depth, HashSet<int> set)
 {
     if (depth == n)
     {
         Console.Write("{");
         Console.Write(string.Join(" ", set.Reverse()));
         Console.WriteLine("}");
     }
     else
     {
         for (int ii = 1; ii <= n; ++ii)
         {
             if (set.Contains(ii))
                 continue;
             set.Add(ii);
             Recurse(n, depth + 1, set);
             set.Remove(ii);
         }
     }
 }
        void OffsetConnectorViewState(UIElement view, Point oldLocation, Point newLocation, bool offsetNonContainedConnectors)
        {
            // There is no need to do anything for the StartSymbol
            if (view is VirtualizedContainerService.VirtualizingContainer)
            {
                Vector offset = new Vector(newLocation.X - oldLocation.X, newLocation.Y - oldLocation.Y);

                // connectors whose dest points are outside the state and the src points are inside/on the state
                HashSet<Connector> outgoingConnectors = new HashSet<Connector>();
                // connectors whose src points are outside the state and the dest points are inside/on the state
                HashSet<Connector> incomingConnectors = new HashSet<Connector>();
                // connectors whose src points and dest points are both inside/on the state
                HashSet<ModelItem> containedTransitions = new HashSet<ModelItem>();

                if (view != null)
                {
                    // Here the incomingConnectors and outgoingConnectors contains connectors whose src points and dest
                    // points are both inside/on the state; they will be removed later on
                    List<Connector> connectors = StateContainerEditor.GetIncomingConnectors(view);
                    foreach (Connector connector in connectors)
                    {
                        incomingConnectors.Add(connector);
                    }
                    connectors = StateContainerEditor.GetOutgoingConnectors(view);
                    foreach (Connector connector in connectors)
                    {
                        outgoingConnectors.Add(connector);
                    }
                }

                // Add common connectors to the containedConnectors set and remove them
                // from the outgoingConnectors and incomingConnectors sets
                foreach (Connector connector in outgoingConnectors.Reverse<Connector>())
                {
                    if (incomingConnectors.Contains(connector))
                    {
                        containedTransitions.Add(StateContainerEditor.GetConnectorModelItem(connector));
                        outgoingConnectors.Remove(connector);
                        incomingConnectors.Remove(connector);
                    }
                }

                // For contained connectors, we offset all the points.
                this.OffsetLocationViewStates(offset, null, containedTransitions, true);

                if (offsetNonContainedConnectors)
                {
                    // For incoming connectors, we offset the end point and invalidate the view state.
                    // This way the start and end point will still connect to the same connection points
                    // on the source and destination shapes and later on the connector will be rerouted using
                    // those two fixed points.
                    foreach (Connector connector in incomingConnectors)
                    {
                        this.SetEndPointsAndInvalidateViewState(connector, offset, false);
                    }

                    // for outgoing connectors, we offset the start point and invalidate the view state.
                    foreach (Connector connector in outgoingConnectors)
                    {
                        this.SetEndPointsAndInvalidateViewState(connector, offset, true);
                    }
                }
                else
                {                    
                    HashSet<ModelItem> nonSelfTransitions = new HashSet<ModelItem>();

                    foreach (Connector connector in incomingConnectors)
                    {
                        nonSelfTransitions.Add(StateContainerEditor.GetConnectorModelItem(connector));
                    }
                    
                    foreach (Connector connector in outgoingConnectors)
                    {
                        nonSelfTransitions.Add(StateContainerEditor.GetConnectorModelItem(connector));
                    }

                    // Store ViewState for all non-self transitions to support undo/redo.
                    this.OffsetLocationViewStates(offset, null, nonSelfTransitions, true);
                }
            }
        }
        /// <summary>
        /// Explain one query node.
        /// </summary>
        /// <param name="plan">Return plan here.</param>
        /// <param name="n">Node to explain.</param>
        internal static void ExplainNode(StringBuilder plan, DryadQueryNode n)
        {
            if (n is DryadTeeNode || n is DryadOutputNode)
            {
                return;
            }
            else if (n is DryadInputNode)
            {
                plan.AppendLine("Input:");
                plan.Append("\t");
                n.BuildString(plan);
                plan.AppendLine();
                return;
            }

            plan.Append(n.m_vertexEntryMethod);
            plan.AppendLine(":");

            HashSet<DryadQueryNode> allchildren = new HashSet<DryadQueryNode>();

            if (n is DryadSuperNode)
            {
                DryadSuperNode sn = n as DryadSuperNode;
                List<DryadQueryNode> tovisit = new List<DryadQueryNode>();

                tovisit.Add(sn.RootNode);

                while (tovisit.Count > 0)
                {
                    DryadQueryNode t = tovisit[0];
                    tovisit.RemoveAt(0);
                    if (!(t is DryadSuperNode))
                        allchildren.Add(t);
                    foreach (DryadQueryNode tc in t.Children)
                    {
                        if (!allchildren.Contains(tc) && sn.Contains(tc))
                            tovisit.Add(tc);
                    }
                }
            }
            else
                allchildren.Add(n);

            foreach (DryadQueryNode nc in allchildren.Reverse())
            {
                Expression expression = null; // expression to print
                List<string> additional = new List<string>(); // additional arguments to print
                int argsToSkip = 0;
                string methodname = nc.OpName;

                plan.Append("\t");

                if (nc is DryadMergeNode)
                {
                    expression = ((DryadMergeNode)nc).ComparerExpression;
                }
                else if (nc is DryadHashPartitionNode)
                {
                    DryadHashPartitionNode hp = (DryadHashPartitionNode)nc;
                    expression = hp.KeySelectExpression;
                    additional.Add(hp.NumberOfPartitions.ToString());
                }
                else if (nc is DryadGroupByNode)
                {
                    DryadGroupByNode gb = (DryadGroupByNode)nc;
                    expression = gb.KeySelectExpression;
                    if (gb.ElemSelectExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(gb.ElemSelectExpression));
                    if (gb.ResSelectExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(gb.ResSelectExpression));
                    if (gb.ComparerExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(gb.ComparerExpression));
                    if (gb.SeedExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(gb.SeedExpression));
                    if (gb.AccumulatorExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(gb.AccumulatorExpression));
                }
                else if (nc is DryadOrderByNode)
                {
                    DryadOrderByNode ob = (DryadOrderByNode)nc;
                    expression = ob.KeySelectExpression;
                    if (ob.ComparerExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(ob.ComparerExpression));
                }
                else if (nc is DryadWhereNode) {
                    expression = ((DryadWhereNode)nc).WhereExpression;
                }
                else if (nc is DryadSelectNode) {
                    DryadSelectNode s = (DryadSelectNode)nc;
                    expression = s.SelectExpression;
                    if (s.ResultSelectExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(s.ResultSelectExpression));
                }
                else if (nc is DryadAggregateNode)
                {
                    DryadAggregateNode a = (DryadAggregateNode)nc;
                    expression = a.FuncLambda;
                    if (a.SeedExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(a.SeedExpression));
                    if (a.ResultLambda != null)
                        additional.Add(HpcLinqExpression.Summarize(a.ResultLambda));
                }
                else if (nc is DryadPartitionOpNode) {
                    expression = ((DryadPartitionOpNode)nc).ControlExpression;
                }
                else if (nc is DryadJoinNode)
                {
                    DryadJoinNode j = (DryadJoinNode)nc;
                    expression = j.OuterKeySelectorExpression;
                    additional.Add(HpcLinqExpression.Summarize(j.InnerKeySelectorExpression));
                    additional.Add(HpcLinqExpression.Summarize(j.ResultSelectorExpression));
                    if (j.ComparerExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(j.ComparerExpression));
                }
                else if (nc is DryadDistinctNode)
                {
                    expression = ((DryadDistinctNode)nc).ComparerExpression;
                }
                else if (nc is DryadContainsNode)
                {
                    DryadContainsNode c = (DryadContainsNode)nc;
                    expression = c.ValueExpression;
                    if (c.ComparerExpression != null)
                        additional.Add(HpcLinqExpression.Summarize(c.ComparerExpression));
                }
                else if (nc is DryadBasicAggregateNode)
                {
                    expression = ((DryadBasicAggregateNode)nc).SelectExpression;
                }
                else if (nc is DryadConcatNode)
                    // nothing to do
                {
                }
                else if (nc is DryadSetOperationNode)
                {
                    expression = ((DryadSetOperationNode)nc).ComparerExpression;
                }
                else if (nc is DryadRangePartitionNode)
                {
                    DryadRangePartitionNode r = (DryadRangePartitionNode)nc;
                    expression = r.CountExpression;
                    // TODO: there's some other possible interesting info
                }
                else if (nc is DryadApplyNode)
                {
                    expression = ((DryadApplyNode)nc).LambdaExpression;
                }

                else if (nc is DryadForkNode)
                {
                    expression = ((DryadForkNode)nc).ForkLambda;
                }

                else if (nc is DryadTeeNode)
                {
                    // nothing
                }
                else if (nc is DryadDynamicNode)
                {
                    // nothing
                }
                else
                {
                    expression = nc.QueryExpression;
                }

                if (expression is MethodCallExpression)
                {
                    MethodCallExpression mc = (MethodCallExpression)expression;
                    methodname = mc.Method.Name;  // overwrite methodname

                    // determine which arguments to skip
                    #region LINQMETHODS
                    switch (mc.Method.Name)
                    {
                        case "Aggregate":
                        case "AggregateAsQuery":
                        case "Select":
                        case "LongSelect":
                        case "SelectMany":
                        case "LongSelectMany":
                        case "OfType":
                        case "Where":
                        case "LongWhere":
                        case "First":
                        case "FirstOrDefault":
                        case "FirstAsQuery":
                        case "Single":
                        case "SingleOrDefault":
                        case "SingleAsQuery":
                        case "Last":
                        case "LastOrDefault":
                        case "LastAsQuery":
                        case "Distinct":
                        case "Any":
                        case "AnyAsQuery":
                        case "All":
                        case "AllAsQuery":
                        case "Count":
                        case "CountAsQuery":
                        case "LongCount":
                        case "LongCountAsQuery":
                        case "Sum":
                        case "SumAsQuery":
                        case "Min":
                        case "MinAsQuery":
                        case "Max":
                        case "MaxAsQuery":
                        case "Average":
                        case "AverageAsQuery":
                        case "GroupBy":
                        case "OrderBy":
                        case "OrderByDescending":
                        case "ThenBy":
                        case "ThenByDescending":
                        case "Take":
                        case "TakeWhile":
                        case "LongTakeWhile":
                        case "Skip":
                        case "SkipWhile":
                        case "LongSkipWhile":
                        case "Contains":
                        case "ContainsAsQuery":
                        case "Reverse":
                        case "Merge":
                        case "HashPartition":
                        case "RangePartition":
                        case "Fork":
                        case "ForkChoose":
                        case "AssumeHashPartition":
                        case "AssumeRangePartition":
                        case "AssumeOrderBy":
                        case "ToPartitionedTableLazy":
                        case "AddCacheEntry":
                        case "SlidingWindow":
                        case "SelectWithPartitionIndex":
                        case "ApplyWithPartitionIndex":
                            argsToSkip = 1;
                            break;
                        case "Join":
                        case "GroupJoin":
                        case "Concat":
                        case "MultiConcat":
                        case "Union":
                        case "Intersect":
                        case "Except":
                        case "SequenceEqual":
                        case "SequenceEqualAsQuery":
                        case "Zip":
                            argsToSkip = 2;
                            break;
                        case "Apply":
                        case "ApplyPerPartition":
                            if (mc.Arguments.Count < 3)
                                argsToSkip = 1;
                            else
                                argsToSkip = 2;
                            break;
                        default:
                            throw DryadLinqException.Create(HpcLinqErrorCode.OperatorNotSupported,
                                                          String.Format(SR.OperatorNotSupported, mc.Method.Name),
                                                          expression);
                    }
                    #endregion

                    plan.Append(methodname);
                    plan.Append("(");

                    int argno = 0;
                    foreach (var arg in mc.Arguments)
                    {
                        argno++;
                        if (argno <= argsToSkip) continue;
                        if (argno > argsToSkip + 1)
                        {
                            plan.Append(",");
                        }
                        plan.Append(HpcLinqExpression.Summarize(arg));
                    }
                    plan.AppendLine(")");
                }
                else
                {
                    // expression is not methodcall
                    plan.Append(methodname);
                    plan.Append("(");
                    if (expression != null)
                    {
                        plan.Append(HpcLinqExpression.Summarize(expression));
                    }
                    foreach (string e in additional)
                    {
                        plan.Append(",");
                        plan.Append(e);
                    }
                    plan.AppendLine(")");
                }
            }
        }