Example #1
0
        private static void LoadImages()
        {
            HashSet<string> images = new HashSet<string>();

            using (WebClient client = new WebClient())
            {
                //string str = client.DownloadString(@"http://www.skovboernehave.dk/Album/20131119Jager/index.html");
                //File.WriteAllText(@"C:\Private\GitHub\Projects\ImageLoader\Image Loader Test\20131119Jager.txt", str);
                string str = File.ReadAllText(@"C:\Private\GitHub\Projects\ImageLoader\Image Loader Test\20131119Jager.txt");

                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(str);

                var first_page = doc.DocumentNode.SelectNodes("//a[@href]")
                                                 .Select(l => l.Attributes["href"].Value)
                                                 .Where(a => a.Contains("slides"))
                                                 .First();
                var page = Path.GetFileName(first_page);
                Console.WriteLine("Parsing page " + page);

                while (ParsePage(page, images))
                {
                    page = Path.ChangeExtension(images.Last(), ".html");
                    Console.WriteLine("Parsing page " + page);
                }
            }

            Console.WriteLine("Downloading images");
            foreach (var image in images)
                DownloadImage(image);
            Console.WriteLine("Images found " + images.Count);
        }
Example #2
0
        public IList<int> GrayCode(int n)
        {
            //List<int> re = new List<int>();
            HashSet<int> re = new HashSet<int>();

            re.Add(0);
            while(true)
            {
                var val = re.Last();
                int i = 0;
                while(i < n)
                {
                    int nextval = val ^ (1 << i);
                    if (!re.Contains(nextval))
                    {
                        re.Add(nextval);
                        break;
                    }
                    i++;                 
                }
                if (i == n)
                    break;
            }
            
            return re.ToList();
        }
Example #3
0
    static void Main()
    {
#if DEBUG
        Console.SetIn(new System.IO.StreamReader("../../input.txt"));
#endif

        var nodes = new HashSet<int>();
        var edges = new List<KeyValuePair<Tuple<int, int>, int>>();

        foreach (int i in Enumerable.Range(0, int.Parse(Console.ReadLine())))
        {
            int[] parts = Console.ReadLine().Split().Select(int.Parse).ToArray();

            nodes.Add(parts[0]);
            nodes.Add(parts[1]);

            edges.Add(new KeyValuePair<Tuple<int, int>, int>(
                new Tuple<int, int>(parts[0], parts[1]),
                parts[2]
            ));
        }

        var trees = new HashSet<HashSet<int>>();

        foreach (int node in nodes)
        {
            var tree = new HashSet<int>();
            tree.Add(node);

            trees.Add(tree);
        }

        int result = 0;

        foreach (var currentEdge in edges.OrderBy(kvp => kvp.Value))
        {
            var tree1 = trees.First(tree => tree.Contains(currentEdge.Key.Item1));
            var tree2 = trees.Last(tree => tree.Contains(currentEdge.Key.Item2));

            if (tree1 == tree2)
                continue;

            tree1.UnionWith(tree2);
            trees.Remove(tree2);

            result += currentEdge.Value;

            if (trees.Count == 1)
                break;
        }

        Console.WriteLine(result);
    }
Example #4
0
        public static void FixConsistency(Client client, List<ConfigState.ShardServer> shardServers, Int64 tableID, string startKey, string endKey)
        {
            if (shardServers.Count <= 1)
                return;

            var keyDiffs = new HashSet<string>();
            var serverKeys = new string[shardServers.Count][];
            var i = 0;

            while (true)
            {
                System.Console.WriteLine("StartKey: " + startKey);
                serverKeys = ConfigStateHelpers.ParallelFetchTableKeysHTTP(shardServers, tableID, startKey, endKey, true);

                for (i = 1; i < serverKeys.Length; i++)
                {
                    if (serverKeys[0].Length > 0 && serverKeys[i].Length > 1 &&
                        serverKeys[0].First().CompareTo(serverKeys[i].Last()) < 0)
                    {
                        foreach (var diff in serverKeys[i].Except(serverKeys[0]))
                            keyDiffs.Add(diff);
                    }

                    if (serverKeys[0].Length > 1 && serverKeys[i].Length > 0 &&
                        serverKeys[i].First().CompareTo(serverKeys[0].Last()) < 0)
                    {
                        foreach (var diff in serverKeys[0].Except(serverKeys[i]))
                            keyDiffs.Add(diff);
                    }
                }

                if (keyDiffs.Count != 0)
                {
                    FixDiffs(client, shardServers, tableID, keyDiffs.ToList());
                    startKey = keyDiffs.Last();
                    keyDiffs = new HashSet<string>();
                    continue;
                }

                if (serverKeys[0].Length <= 1)
                    break;

                startKey = serverKeys[0][serverKeys[0].Length - 1];
            }
        }
		private GraphicsMode GetDefaultGraphicsMode()
		{
			int[] aaLevels = new int[] { 0, 2, 4, 6, 8, 16 };
			HashSet<GraphicsMode> availGraphicsModes = new HashSet<GraphicsMode>(new GraphicsModeComparer());
			foreach (int samplecount in aaLevels)
			{
				GraphicsMode mode = new GraphicsMode(32, 24, 0, samplecount, new OpenTK.Graphics.ColorFormat(0), 2, false);
				if (!availGraphicsModes.Contains(mode)) availGraphicsModes.Add(mode);
			}
			int highestAALevel = MathF.RoundToInt(MathF.Log(MathF.Max(availGraphicsModes.Max(m => m.Samples), 1.0f), 2.0f));
			int targetAALevel = highestAALevel;
			if (DualityApp.AppData.MultisampleBackBuffer)
			{
				switch (DualityApp.UserData.AntialiasingQuality)
				{
					case AAQuality.High:	targetAALevel = highestAALevel;		break;
					case AAQuality.Medium:	targetAALevel = highestAALevel / 2; break;
					case AAQuality.Low:		targetAALevel = highestAALevel / 4; break;
					case AAQuality.Off:		targetAALevel = 0;					break;
				}
			}
			else
			{
				targetAALevel = 0;
			}
			int targetSampleCount = MathF.RoundToInt(MathF.Pow(2.0f, targetAALevel));
			return availGraphicsModes.LastOrDefault(m => m.Samples <= targetSampleCount) ?? availGraphicsModes.Last();
		}
Example #6
0
        static bool getMaxNumPrimes(string s)
        {
            int minPrime = 0;
            int tempCount = 1;
            int maxCount = 1;
            
            
               
                for (int j = 0; j < s.Length; j++)
                {
                    for (int k = j + 1; k < s.Length; k++)
                    {
                        for (int x = k + 1; x < s.Length; x++)
                        {
                            
                                tempCount = 1;
                                HashSet<int> primes = new HashSet<int>();
                                for (int i = 0; i < 10; i++)
                                {
                                    char iLetter = i.ToString()[0];
                                    StringBuilder buffString = new StringBuilder(s);
                                    buffString[j] = iLetter;
                                    buffString[k] = iLetter;
                                    buffString[x] = iLetter;
                                    int newInt = int.Parse(buffString.ToString());

                                    if (newInt < isPrime.Length && isPrime[newInt])
                                    {
                                        if (primes.Count > 0 && primes.Last().ToString().Length != buffString.ToString().Length)
                                        {
                                            primes.Clear();
                                        }
                                        //   isPrime[newInt] = false;
                                        primes.Add(newInt);
                                    }


                                    if (tempCount > maxCount)
                                    {
                                        maxCount = tempCount;
                                        minPrime = int.Parse(s.ToString());
                                    }



                                    if (primes.Count == 8)
                                    {
                                        foreach (int num in primes)
                                        {
                                            Console.WriteLine(num);
                                        }
                                        return true;
                                    }

                                }
                            
                             
                        }
                        
                    }
                }
                return false;   
        }
        public void HashSetExtensions_Last_ThrowsExceptionIfHashSetIsEmpty()
        {
            var set = new HashSet<Int32>();

            set.Last();
        }
        public int GetNesting(MethodDeclarationSyntax method)
        {
            var set = new HashSet<int>() { 0 };

            var nodes = method.DescendantNodes().OfType<StatementSyntax>().Where(IsEnlargersNesting).ToList();
            int c = 0;

            for (var j = 0; j < nodes.Count; )
            {
                var list = new List<Tuple<SyntaxNode, int>> { Tuple.Create((SyntaxNode)nodes[j], 1) };
                for (var i = 0; i < list.Count; ++i)
                {
                    //Console.WriteLine("Родитель = {0} ,  {1}   -   {2}  !!!!!!!!!", list[i].Item1, list[i].Item2, list[i].Item1.GetType());

                    var li = list[i].Item1.ChildNodes().OfType<SyntaxNode>();
                    set.Add(list[i].Item2);
                    foreach (var statementSyntax in li)
                    {
                        //Console.Write("Ребёнок = ");
                        //Console.WriteLine(statementSyntax);

                        if (IsEnlargersNesting(statementSyntax))
                        {
                            list.Add(Tuple.Create(statementSyntax, list[i].Item2 + 1));
                        }
                        else
                        {
                            if (!(statementSyntax is LiteralExpressionSyntax || statementSyntax is ExpressionStatementSyntax || statementSyntax is IdentifierNameSyntax || statementSyntax is BinaryExpressionSyntax))
                                list.Add(Tuple.Create(statementSyntax, list[i].Item2));
                        }
                        //Console.WriteLine("++++++++++++");
                    }
                    //list.AddRange(li.Where(ii => !(ii is ExpressionStatementSyntax || ii is LiteralExpressionSyntax)));

                    // Console.WriteLine("###########");
                }
                var count = list.Count(ii => IsEnlargersNesting(ii.Item1));
                // Console.WriteLine(count.ToString());
                //Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\n");
                // j++;
                j += count;
            }

            return set.Last();
        }
Example #9
0
        //节点开始新建一个匿名组
        public void JoinAnonyGroup(object o)
        {
            GroupArgs args = (GroupArgs)o;
            int k = args.k;
            int L = args.l;
            int random = args.random;

            if (random > 0)//需要从匿名组中随机选择一个节点
            {
                int nodeId = PrivacyReader.rootReader.SelectOneFromGroup();
                PrivacyReader reader = (PrivacyReader)Node.getNode(nodeId, NodeType.READER);
                if(reader !=null)
                    reader.JoinAnonyGroup(new GroupArgs(k, L, 0));
                return;
            }

            if (!this.anonGroups.ks.Contains(k))
                this.anonGroups.ks.Add(k);
            //this.AnonGroups.group.Add(k, new HashSet<int>());

            //native 方法
            if (global.method == 1)
            {
                this.lastesth = 2;
                Console.WriteLine("{0:F4} [JOIN_ANON_GROUP] {1}{2} start to join group k={3}, l={4}. [IN]", scheduler.currentTime, this.type, this.Id, k, this.lastesth);
                SendNativeGroupRequest(this.lastesth, this.lastesth, k, this.Id);
                string groupident = this.Id + "-" + k + "-" + this.lastesth;
                this.pendingNativeGroupResponses.Add(groupident, new Dictionary<int, NativeGroupResponseEntry>());
                this.cachedRecvRequest.Add(groupident, scheduler.currentTime);
                Event.AddEvent(new Event(scheduler.currentTime + 0.3f, EventType.CHK_NATGROUP, this, groupident));
                return;
            }

            //是否建立了匿名树
            int groupTreeRoot = -1;
            foreach (KeyValuePair<string, AnonyTreeEntry> pair in this.CachedTreeEntries)
            {
                AnonyTreeEntry subTreeInfo = pair.Value;
                if (subTreeInfo.rootId > 0 && subTreeInfo.status != SubNodeStatus.OUTSIDE)
                {
                    groupTreeRoot = subTreeInfo.rootId;
                    break;
                }
            }

            //如果建立了匿名树,则不是第一次,或者是native2的方法,那也先获取频繁子集
            HashSet<int> freqSet = new HashSet<int>();
            //if (groupRoot >= 0 || global.nativeMethod == 2)
            //第二种方法, native2
            if (global.method == 2)
            {
                Console.WriteLine("{0:F4} [JOIN_ANON_GROUP] {1}{2} start to join group k={3}, l={4}. [IN]", scheduler.currentTime, this.type, this.Id, k, this.lastesth);

                //比较现有匿名组中出现次数最多的节点
                Dictionary<int, int> h = new Dictionary<int, int>();
                foreach (KeyValuePair<int, HashSet<int>> pair in this.anonGroups.groups)
                {
                    int k1 = pair.Key;
                    HashSet<int> g = pair.Value;
                    foreach (int n in g)
                    {
                        if (!h.ContainsKey(n))
                            h.Add(n, 0);
                        h[n]++;
                    }
                }

                int[] sortedh = Utility.SortDictionary(h);
                int num = 0;
                for (int i = 0; i < sortedh.Length; i++)
                {
                    //选出最大的若干项
                    //为了增加概率,增加1.5倍候选节点
                    if (num >= k)
                        break;
                    //如果出现的次数小于阈值,则忽略
                    if (h[sortedh[i]] < 1)
                        continue;
                    //查找该节点是否已在其他k-匿名组中了
                    if (groupTreeRoot >= 0)
                    {
                        bool found = false;
                        foreach (int c in this.CachedTreeEntries[groupTreeRoot + ""].subtree.Keys)
                        {
                            string key1 = c + "-" + k;
                            if (!this.anonGroups.subUnavailAnonyNodes.ContainsKey(key1))
                            {
                                found = true;
                                break;
                            }
                        }
                        if (found == true)
                            continue;
                    }
                    freqSet.Add(sortedh[i]);
                    num++;
                }
                if (freqSet.Count > 0 && !freqSet.Contains(this.Id))
                {
                    freqSet.Remove(freqSet.Last());
                    freqSet.Add(this.Id);
                }

                if (freqSet.Count == 0)
                {
                    this.lastesth = 2;
                    SendNativeGroupRequest(this.lastesth, this.lastesth, k, this.Id);
                    string groupident = this.Id + "-" + k + "-" + this.lastesth;
                    this.pendingNativeGroupResponses.Add(groupident, new Dictionary<int, NativeGroupResponseEntry>());
                    this.cachedRecvRequest.Add(groupident, scheduler.currentTime);
                    Event.AddEvent(new Event(scheduler.currentTime + 0.3f, EventType.CHK_NATGROUP, this, groupident));
                    return;
                }
                else
                {
                    this.cachedCandidateNodes.Add(k, new HashSet<int>());
                    foreach (int x in freqSet)
                        SendSetLongNativeGroupRequest(this.Id, k, 0, x);

                    string groupident = this.Id + "-" + k;
                    this.pendingNativeGroupResponses.Add(groupident, new Dictionary<int, NativeGroupResponseEntry>());
                    this.cachedRecvRequest.Add(groupident, scheduler.currentTime);
                    Event.AddEvent(new Event(scheduler.currentTime + global.native2WaitingTimeout, EventType.CHK_NATGROUP1, this, groupident));
                }
                return;
            }

            //否则,为我们改进的方法
            int rootId = this.Id;
            string key = rootId+"";
            if (groupTreeRoot < 0)//本节点未在匿名树中,新建树,再建组
            {
                Console.WriteLine("{0:F4} [JOIN_ANON_GROUP] {1}{2} start to join group k={3}, l={4}. [IN]", scheduler.currentTime, this.type, this.Id, k, L);

                int hops = 0;
                int m = -1;

                //if (!this.CachedRegionEntries.ContainsKey(key))
                    this.CachedRegionEntries.Add(key, new AnonyRegionEntry(rootId, hops));
                //if(!this.CachedDistEntries.ContainsKey(this.Id))
                    this.CachedDistEntries.Add(this.Id, new DistanceEntry(this.Id, 0, scheduler.currentTime));
                //init
                double includedAngle = global.includedAngle;
                SendTreeGroupRequest(rootId,m, L, 0, 0, 0);
                //if(!this.CachedTreeEntries.ContainsKey(key))
                    this.CachedTreeEntries.Add(key, new AnonyTreeEntry(rootId, null, m));
                this.CachedTreeEntries[key].status = SubNodeStatus.NORMAL;
            }
            else
            {
                Console.WriteLine("{0:F4} [JOIN_ANON_GROUP] {1}{2} start to join group k={3}, l={4}. [OUT]", scheduler.currentTime, this.type, this.Id, k, L);
                //之前建立过匿名组,在原有的匿名树的基础上新建一个
                ProcessNewGroupRequest(groupTreeRoot, k, this.Id, L, 0, 0, 0, null);
                //ProcessNewGroup(groupRoot, k, k, this.id, id);
            }
        }
        public int FindLabelForTheBiggestCharBlob(HashSet<short> char_blob_idx_set)
        {
            int idx1 = char_blob_idx_set.First(); // char_blob_idx_set has exactly two elements
            int idx2 = char_blob_idx_set.Last();
            // check if any of the connecting CC has two neighbors already
            if ((connected_char_blob_idx_set_list[idx1].Count == 2 && !connected_char_blob_idx_set_list[idx1].Contains(idx2))
                || (connected_char_blob_idx_set_list[idx2].Count == 2 && !connected_char_blob_idx_set_list[idx2].Contains(idx1)))
                return 0;
            if (BreakingAngle(idx1, idx2)) return 0;
            // check for size ratio
            int size2 = (int)(char_blob_idx_max_size_table[idx2]);
            int size1 = (int)(char_blob_idx_max_size_table[idx1]);

            if ((double)size1 / (double)size2 > size_ratio
                || (double)size2 / (double)size1 > size_ratio)
                return 0;
            else
            {
                if (size1 > size2) return idx1 + 1;
                else return idx2 + 1;
            }
        }
        public bool ValidateConnection(HashSet<short> char_blob_idx_set)
        {
            // check if it has a weak link
            int idx1 = char_blob_idx_set.First(); // the set has exactly two elements
            int idx2 = char_blob_idx_set.Last();

            // check regular stuff
            if (FindLabelForTheBiggestCharBlob(char_blob_idx_set) != 0)
            {
                //if (weak_link_set.Count > 0) // now I know the real connecting nodes
                //{
                //    // the second confirmation check
                //    if (weak_link_set.Contains(idx1 + ":" + idx2)
                //        && weak_link_set.Contains(idx2 + ":" + idx1))
                //    {
                //        connected_char_blob_idx_set_list[idx1].Remove(idx2);
                //        connected_char_blob_idx_set_list[idx2].Remove(idx1);
                //        return false;
                //    }
                //}
                connected_char_blob_idx_set_list[idx1].Add(idx2);
                connected_char_blob_idx_set_list[idx2].Add(idx1);
                return true;
            }
            else
                return false;
        }
        public void HashSetExtensions_Last_ThrowsExceptionIfHashSetIsEmpty()
        {
            var set = new HashSet<Int32>();

            Assert.That(() => set.Last(),
                Throws.TypeOf<InvalidOperationException>());
        }
        public void HashSetExtensions_Last_ReturnsLastItemInHashSet()
        {
            var set = new HashSet<Int32>() { 1, 2, 3 };

            var result = set.Last();

            TheResultingValue(result).ShouldBe(3);
        }
Example #14
0
        /// <summary>
        /// Check for conflicts of versions in the referenced assemblies of the workflow.
        /// </summary>
        /// <param name="referencedTypes">Referenced types in the project</param>
        /// <param name="referencedAssemblies">Referenced assemblies in the project</param>
        /// <param name="projectName">Name of the main type (workflow) of the project</param>
        private static void CheckForConflictingVersions(HashSet<Type> referencedTypes, HashSet<Assembly> referencedAssemblies, string projectName)
        {
            // XamlBuildTask cannot support two different versions of the same dependency in XAML.
            // As a workaround, we raise an error here if the workflow contains activities/variables/etc.
            // from different versions of the same assembly.
            var conflicts =
                referencedAssemblies.GroupBy(asm => asm.GetName().Name).Where(grp => grp.Count() > 1).ToList();

            if (conflicts.Any())
            {
                var conflict = conflicts.First();
                Assembly asm1 = referencedAssemblies.First(item => item.GetName().Name == conflict.Key);
                Assembly asm2 = referencedAssemblies.Last(item => item.GetName().Name == conflict.Key);

                var type1 = referencedTypes.First(item => item.Assembly.GetName().Name == asm1.GetName().Name &&
                    item.Assembly.GetName().Version == asm1.GetName().Version);
                var type2 = referencedTypes.First(item => item.Assembly.GetName().Name == asm2.GetName().Name &&
                    item.Assembly.GetName().Version == asm2.GetName().Version);

                string message = string.Format(CompileMessages.MultipleVersionsUsed,
                        type1.Name, asm1.FullName, type2.Name, asm2.FullName, conflict.Key);
                throw new CompileException(message);
            }

            // Check if the workflow contains a previous version of itself
            var referencesToItself = new List<Assembly>(
                                      from assemblies in referencedAssemblies
                                      where assemblies.GetName().Name == projectName
                                      select assemblies);

            if (referencesToItself.Any())
            {
                string message = string.Format(CompileMessages.PreviousSelfVersion,
                                               referencesToItself.First().GetName().Name,
                                               referencesToItself.First().GetName().FullName);
                throw new CompileException(message);
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            Console.Out.WriteLine();
            Console.Out.WriteLine("Specify a file with a list of invoice IDs to archive, one on each line.");
            Console.Out.WriteLine();

            Console.Out.Write("Filename: ");
            string filenameIn = Console.In.ReadLine();

            string outLocation;
            Console.Out.Write("Output to desktop? (Y if yes)");
            if (Console.ReadKey().KeyChar == 'y')
            {
                outLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                        string.Concat(Path.GetFileNameWithoutExtension(filenameIn), "_out.txt"));
            }
            else
            {
                outLocation = string.Concat(Path.GetFileNameWithoutExtension(filenameIn), "_out.txt");
            }

            Console.WriteLine();

            string[] invoiceIdsStrArr = File.ReadAllLines(filenameIn);
            HashSet<string> invoiceIds = new HashSet<string>();
            foreach (var item in invoiceIdsStrArr)
            {
                invoiceIds.Add(item);
            }

            using (FileStream fs = File.OpenWrite(string.Concat(outLocation)))
            {
                StreamWriter sw = new StreamWriter(fs);
                List<string> illegalRows = new List<string>();

                try
                {
                    int rowCount = 0;
                    string last = invoiceIds.Last();
                    foreach (var item in invoiceIds)
                    {
                        if (!Regex.IsMatch(item, "[0-9]{8}"))
                        {
                            illegalRows.Add(item);
                            continue;
                        }

                        if (item != last)
                        {
                            if (rowCount < 499)
                            {
                                sw.Write(string.Concat(item, ","));
                                rowCount++;
                            }
                            else
                            {
                                sw.Write(item);
                                sw.WriteLine();
                                rowCount = 0;
                            }
                        }
                        else if (rowCount < 500)
                        {
                            sw.Write(item);
                        }
                        else if (rowCount == 500)
                        {
                            sw.WriteLine();
                            sw.Write(item);
                        }
                    }
                }
                catch (IOException e)
                {
                    Console.Out.WriteLine("IO exception:");
                    Console.Out.WriteLine(e.Message);
                }
                finally
                {
                    if (!illegalRows.Any<string>())
                    {
                        Console.WriteLine(illegalRows.Count().ToString(), " rows contain bad invoice IDs:");
                        foreach (var item in illegalRows)
                        {
                            Console.WriteLine("  ", item);
                        }
                        Console.WriteLine("Press a key");
                        Console.ReadKey();
                    }

                    sw.Close();
                    sw.Dispose();
                }
            }
        }
Example #16
0
        public void StreamDocCalled_PageSize_NotIgnored()
        {
            ValidateConstantValues();

            int[] streamDocsRequestCounter = {0};
            using (var ravenServer = GetNewServer())
            {
				ravenServer.Server.RequestManager.BeforeRequest += (sender, args) =>
				{
					if (args.Controller.InnerRequest.RequestUri.PathAndQuery.Contains("/streams/docs?"))
					{
						Interlocked.Increment(ref streamDocsRequestCounter[0]);
					}
				};

                using (var documentStore = NewRemoteDocumentStore(ravenDbServer: ravenServer))
                {
                    AddDummyDocuments(documentStore);

                    var fetchedDocumentsCollection1 = new HashSet<DummyDocument>();

                    using (var docStream = documentStore.DatabaseCommands.StreamDocs(start: 0,pageSize: TestPageSize))
                    {
                        while (docStream.MoveNext())
                        {
                            Assert.NotNull(docStream.Current);
                            fetchedDocumentsCollection1.Add(docStream.Current.Deserialize<DummyDocument>(new DocumentConvention()));
                        }

                        Assert.Equal(TestPageSize, fetchedDocumentsCollection1.Count);
                        Assert.Equal(1, streamDocsRequestCounter[0]);
                    }

                    var fetchedDocumentsCollection2 = new HashSet<DummyDocument>();
                    using (var docStream = documentStore.DatabaseCommands.StreamDocs(start: TestPageSize - 1, pageSize: TestPageSize))
                    {
                        while (docStream.MoveNext())
                        {
                            Assert.NotNull(docStream.Current);
                            fetchedDocumentsCollection2.Add(docStream.Current.Deserialize<DummyDocument>(new DocumentConvention()));
                        }

                        Assert.Equal(TestPageSize, fetchedDocumentsCollection2.Count);
                    }


                    Assert.Equal(1, fetchedDocumentsCollection1.Intersect(fetchedDocumentsCollection2).Count());
                    Assert.True(fetchedDocumentsCollection1.Last().Equals(fetchedDocumentsCollection2.First()));
                
                }
            }
        }
Example #17
0
        private bool FindAnnonces(WebBrowser webbrowser3)
        {
            HashSet<string> anonnces = new HashSet<string>();
            string[] str_separators = new string[] { ":::", " ;;;" };
            string[] strs_in = { "" };
            if (one_site["InAnnonce"] != null && one_site["InAnnonce"].ToString().Length > 7)
                strs_in = one_site["InAnnonce"].ToString().Split(str_separators, StringSplitOptions.RemoveEmptyEntries);
            string[] strs_ex = { "" };
            if (one_site["ExAnnonce"] != null && one_site["ExAnnonce"].ToString().Length > 7)
                strs_ex = one_site["ExAnnonce"].ToString().Split(str_separators, StringSplitOptions.RemoveEmptyEntries);

            foreach (HtmlElement link in webbrowser3.Document.All)
            {
                bool findannonce = true;
                IHTMLElement4 ilink4 = (IHTMLElement4)link.DomElement;
                if (linksTrouve.Contains(link.OuterHtml))
                    continue;
                for (int tmp1 = 0; tmp1 < (strs_in.Length / 2); tmp1++)
                {
                    if (ilink4.getAttributeNode(strs_in[tmp1 * 2]) != null && ilink4.getAttributeNode(strs_in[tmp1 * 2]).nodeValue != null)
                    {
                        if (!ilink4.getAttributeNode(strs_in[tmp1 * 2]).nodeValue.ToString().Contains(strs_in[tmp1 * 2 + 1]))
                        {
                            findannonce = false;
                            break;
                        }
                    }
                    else if (!link.GetAttribute(strs_in[tmp1 * 2]).Contains(strs_in[tmp1 * 2 + 1]))
                    {
                        findannonce = false;
                        break;
                    }
                }
                for (int tmp2 = 0; tmp2 < (strs_ex.Length / 2); tmp2++)
                {
                    if (ilink4.getAttributeNode(strs_ex[tmp2 * 2]) != null && ilink4.getAttributeNode(strs_ex[tmp2 * 2]).nodeValue != null)
                    {
                        if (ilink4.getAttributeNode(strs_ex[tmp2 * 2]).nodeValue.ToString().Contains(strs_ex[tmp2 * 2 + 1]) || !findannonce)
                        {
                            findannonce = false;
                            break;
                        }
                    }
                    else if (link.GetAttribute(strs_ex[tmp2 * 2]).Contains(strs_ex[tmp2 * 2 + 1]) || !findannonce)
                    {
                        findannonce = false;
                        break;
                    }
                }
                if (findannonce)
                {
                    anonnces.Add(link.OuterHtml);
                    linksTrouve.Add(link.OuterHtml);
                    //Console.WriteLine("npage : " + npage.ToString() + " nb linksTrouve :" + linksTrouve.Count.ToString() + " link.OuterHtml :" + link.OuterHtml);

                    if (fullpage)
                    {
                        try
                        {
                            infindannonce = true;
                            this.webBrowser1.DocumentCompleted -= new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted);
                            this.webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted_2);
                            try
                            {
                                //link.Focus();
                                //SendKeys.Send("ENTER");
                                bool bonclik = false;
                                for (int tmp1 = 0; tmp1 < (strs_in.Length / 2); tmp1++)
                                {
                                    if (strs_in[tmp1 * 2].IndexOf("onclick", StringComparison.OrdinalIgnoreCase) >= 0)
                                    {
                                        bonclik = true;
                                        link.RaiseEvent("onclick");
                                        break;
                                    }
                                }
                                if (!bonclik)
                                link.InvokeMember("click");

                            }
                            catch (Exception exc)
                            {
                                Console.WriteLine("findAnnonce click " + exc.Message);
                            }
                        }
                        catch (Exception exc)
                        {
                            MessageBox.Show("findAnnonce fullpage " + exc.Message);
                        }
                        break;
                    }
                    else
                    {
                        //SQL.Connect();
                        int site_id = Convert.ToInt16(SQL.Get(@"select id from sites where ENTREPRISE = '" + one_site["ENTREPRISE"].ToString().Replace("'", "''") + "'"));
                        /*
                         DataRow row = dtAnnIn.NewRow();
                        row["id"] = site_id;
                        row["Entreprise"] = one_site["ENTREPRISE"].ToString();
                        row["link"] = link.GetAttribute("href");
                        row["link_hash"] = CreateMD5Hash(link.GetAttribute("href"));
                        dtAnnIn.Rows.Add(row);
                        */
                        //dtAnnIn.Rows.Add(site_id, one_site["ENTREPRISE"].ToString(),one_site["ENTREPRISE"].ToString(), link.GetAttribute("href"), CreateMD5Hash(link.GetAttribute("href")));
                        if (extract && site_id != 0)
                        {
                            if (SQL.Requet(@"insert into liens (id_site, nom, link, link_hash) values (" + site_id + ", '" + one_site["ENTREPRISE"].ToString().Replace("'", "''") + "', '"
                                        + link.GetAttribute("href") + "','" + CreateMD5Hash(link.GetAttribute("href")) + "')"))
                            {
                                anonnces.Add(link.GetAttribute("href"));
                                allanonnces.Add(anonnces.Last());
                                //dtAnnIn.Rows.Add(dr);
                            }
                            else
                            {
                                insertfail++;
                                if (insertfail > 5 && one_site["MAXPAGES"].ToString() == "99")
                                    webClose();
                            }
                        }
                        //SQL.Disconnect();
                    }
                }
            }
            //nbannonces += anonnces.Count();
            if (anonnces.Count() > 0)
                return true;
            else
                return false;
        }
Example #18
0
        /// <summary>
        /// Replacements finder for the document
        /// </summary>
        /// <param name="doc">NormaCSAPI.Document object</param>
        /// <returns>Replacements list</returns>
        private HashSet<NormaCSAPI.Document> findReplacements(NormaCSAPI.Document doc)
        {
            HashSet<NormaCSAPI.Document> replacers = new HashSet<NormaCSAPI.Document>();
            NormaCSAPI.Replacements replacedBy = doc.ReplacedBy;

            while (replacedBy.Count > 0)
            {
                foreach (NormaCSAPI.Replacement repl in replacedBy)
                    replacers.Add(repl.get_Document());
                replacedBy = replacers.Last().ReplacedBy;
            }

            return replacers;
        }
Example #19
0
        private static bool Delaunay2DInsertPoints(List<Vertex> vertices, Adjacency adjacency)
        {
            // Insert points

            HashSet<int> toCheck = new HashSet<int>();

            for (int i = 0; i < vertices.Count; i++)
            {

                // Insert Vi
                Vertex Vi = vertices[i];

                bool skip = false;
                for (int j = 0; j < adjacency.vertices.Count; j++)
                {
                    if ((Vi - adjacency.vertices[j]).Length() <= COINCIDENT_POINTS_DISTANCE_EPSILON)
                    {
                        // the point has already been inserted. Skip it
                        skip = true;
                        break;
                    }
                }
                if (skip)
                {
                    continue;
                }

                if (OnDelaunayInsertPoint != null)
                    OnDelaunayInsertPoint(adjacency, Vi);

                int tri = adjacency.PointInTriangle(Vi);

                if (tri < 0)
                {
                    Debug.Assert(false);
                    return false;
                }

                // check whether the point lies exactly on one edge of the triangle
                int edgeIdx = adjacency.PointInTriangleEdge(Vi, tri);
                if (edgeIdx >= 0)
                {
                    // split the edge by Vi
                    int[] result;
                    adjacency.SplitEdge(edgeIdx, Vi, out result);
                    for (int j = 0; j < 4; j++)
                    {
                        if (result[j] >= 0)
                        {
                            toCheck.Add(result[j]);
                        }
                    }
                }
                else
                {
                    // split the triangle in 3
                    int[] result;
                    adjacency.SplitTriangle(tri, Vi, out result);
                    for (int j = 0; j < 3; j++)
                    {
                        toCheck.Add(result[j]);
                    }
                }

                while (toCheck.Count > 0)
                {
                    int t = toCheck.Last<int>();
                    toCheck.Remove(t);

                    Adjacency.Triangle triangle = adjacency.triangles[t];
                    if (!triangle.valid)
                    {
                        continue;
                    }

                    if (OnDelaunayTriangleCheck != null)
                        OnDelaunayTriangleCheck(adjacency, t);

                    // check Delaunay condition
                    for (int e = 0; e < 3; e++)
                    {
                        if (!adjacency.triangles[t].valid) continue;

                        int adjacentIdx = adjacency.AdjacentTriangle(t, e);
                        if (adjacentIdx < 0)
                        {
                            continue;
                        }
                        int globalEdgeIndex = Math.Abs(triangle.edges[e]) - 1;
                        Adjacency.Triangle adjacent = adjacency.triangles[adjacentIdx];
                        if (!adjacent.valid)
                        {
                            continue;
                        }
                        Debug.Assert(adjacent.valid);
                        int edgeFromAdjacent = adjacent.LocalEdgeIndex(globalEdgeIndex);
                        Debug.Assert(edgeFromAdjacent >= 0);
                        int v = adjacency.VertexOutOfTriEdge(adjacentIdx, edgeFromAdjacent);
                        Debug.Assert(v >= 0);
                        Debug.Assert(!triangle.Contains(v));

                        if (triangle.InsideCircumcircle(adjacency.vertices[v], adjacency.vertices) > INSIDE_CIRCUMCIRCLE_EPSILON)
                        {
                            int[] result;
                            if (adjacency.FlipTriangles(t, adjacentIdx, out result))
                            {
                                toCheck.Add(result[0]);
                                toCheck.Add(result[1]);
                                //break;
                            }
                        }
                    }
                }

                if (OnDelaunayStep != null)
                    OnDelaunayStep(adjacency);
            }
            return true;
        }
Example #20
0
        private static void Main(string[] args)
        {
            SyntaxTree tree = SyntaxTree.ParseText(
                @"using System;
class Sample
{
       public class A
       {
            
             override protected void SendBuffer(LoggingEvent[] events)
		{
			 if (m_reconnectOnError && (m_dbConnection == null || m_dbConnection.State != ConnectionState.Open))
			{

				InitializeDatabaseConnection();
				InitializeDatabaseCommand();
			}
				else if (x == 0)
				{
					TestDelegate myDel = n => { string s = n; Console.WriteLine(s); };
				}

                try{

                }
                catch(Exception ex){
                
                }
			}
		}

       }
}");

            var root = (CompilationUnitSyntax) tree.GetRoot();
            var firstMember = root.Members[0];
            //var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember;
            //var programDeclaration = (ClassDeclarationSyntax)helloWorldDeclaration.Members[0];
            // var mainDeclaration = (MethodDeclarationSyntax)programDeclaration.Members[1];

            var methods = root.DescendantNodes()
                .OfType<MethodDeclarationSyntax>();

            var helloWorldString = root.DescendantNodes()
                .OfType<StatementSyntax>();

            int count = 0;

            foreach (var method in methods)
            {
                var set = new HashSet<int>() {0};
                
                var nodes = method.DescendantNodes().OfType<StatementSyntax>().Where(IsEnlargersNesting).ToList();
               
               
                for(var j = 0; j < nodes.Count;)
                {
                    var list = new List<Tuple<SyntaxNode, int>>();
                    list.Add(Tuple.Create((SyntaxNode)nodes[j], 1));
                    for (var i = 0; i < list.Count; ++i)
                    {
                        Console.WriteLine("Родитель = {0} ,  {1}   -   {2}  !!!!!!!!!", list[i].Item1, list[i].Item2, list[i].Item1.GetType());
                       
                        var li = list[i].Item1.ChildNodes().OfType<SyntaxNode>();
                        set.Add(list[i].Item2);
                        foreach (var statementSyntax in li)
                        {
                            Console.Write("Ребёнок = ");
                            Console.WriteLine(statementSyntax);
                            
                            if (IsEnlargersNesting(statementSyntax))
                            {
                                list.Add(Tuple.Create(statementSyntax, list[i].Item2 + 1));
                            }
                            else
                            {
                                if (!(statementSyntax is LiteralExpressionSyntax || statementSyntax is ExpressionStatementSyntax || statementSyntax is IdentifierNameSyntax || statementSyntax is BinaryExpressionSyntax))
                                    list.Add(Tuple.Create(statementSyntax, list[i].Item2));
                            }
                            Console.WriteLine("++++++++++++");
                        }
                         //list.AddRange(li.Where(ii => !(ii is ExpressionStatementSyntax || ii is LiteralExpressionSyntax)));
                        
                        Console.WriteLine("###########");
                    }
                    count = list.Where(ii => IsEnlargersNesting(ii.Item1)).Count();
                    Console.WriteLine(count.ToString());
                    Console.WriteLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\n");
                   // j++;
                    j += count;
                }

                Console.WriteLine("NESTING   ==   {0}", set.Last());
            }

            
        }