Esempio n. 1
0
        public void Drop(ICollection collection)
        {
            if (collection is IInternalCollection collectionToRemove && _collections.Contains(collectionToRemove))
            {
                using (var transaction = _connection.BeginTransaction())
                {
                    var tableName = collectionToRemove.TableName;
                    using (var command = _connection.CreateCommand())
                    {
                        command.CommandText = string.Format("DROP TABLE {0}", tableName);
                        command.ExecuteNonQuery();
                    }

                    using (var command = _connection.CreateCommand())
                    {
                        command.CommandText = string.Format("DELETE FROM {0} WHERE tableName = @tableName", TableName);
                        command.Parameters.AddWithValue("@tableName", tableName);
                        command.ExecuteNonQuery();
                    }

                    transaction.Commit();
                }

                _collectionsByName.Remove(collectionToRemove.Name);
                _collections.Remove(collectionToRemove);
                collectionToRemove.MarkAsDropped();
            }
        }
Esempio n. 2
0
        protected void SelectClicked(
            Func <List <MediaCardViewModel> > getSortedItems,
            MediaCardViewModel card,
            MouseEventArgs e)
        {
            if (_selectedItems.Contains(card))
            {
                _selectedItems.Remove(card);
            }
            else
            {
                if (e.ShiftKey && _recentlySelected.IsSome)
                {
                    List <MediaCardViewModel> sorted = getSortedItems();

                    int start  = sorted.IndexOf(_recentlySelected.ValueUnsafe());
                    int finish = sorted.IndexOf(card);
                    if (start > finish)
                    {
                        int temp = start;
                        start  = finish;
                        finish = temp;
                    }

                    for (int i = start; i < finish; i++)
                    {
                        _selectedItems.Add(sorted[i]);
                    }
                }

                _recentlySelected = card;
                _selectedItems.Add(card);
            }
        }
Esempio n. 3
0
        private IEnumerable <NewEvent> ProcessEvent(Event evnt)
        {
            var eventValue = evnt.Value;

            List <NewEvent> newEvents = new List <NewEvent>();

            switch (eventValue.Type)
            {
            case EventType.NewStory:
                newEvents.Add(new NewEvent(Distribution.NextStory, new EventValue(EventType.NewStory)));
                var storyId = _storyIdCounter++;
                _storiesInProgress.Add(storyId);
                newEvents.Add(new NewEvent(Distribution.StoryCycleTime, new EventValue(EventType.StoryFinish, storyId)));
                break;

            case EventType.StoryFinish:
                var cycleTime = evnt.Time - evnt.StartTime;
                _simulatedStoryCycleTimes.Add(cycleTime);
                _storiesInProgress.Remove(eventValue.StoryId);
                break;

            case EventType.Sample:
                newEvents.Add(new NewEvent(Distribution.Unit, new EventValue(EventType.Sample)));
                _storiesInProgressSample.Add(_storiesInProgress.Count);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(newEvents);
        }
 public override bool Remove(object element)
 {
     if (table.Remove((T)element))
     {
         list.Remove((T)element);
         return(true);
     }
     return(false);
 }
Esempio n. 5
0
        /// <summary>
        /// Handler for the <see cref="ShowChildrenCommand"/>
        /// </summary>
        public async void ShowChildrenExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var node = (e.Parameter ?? graphControl.CurrentItem) as INode;

            if (node != null && !doingLayout)
            {
                int count = hiddenNodesSet.Count;
                foreach (var childEdge in filteredGraphWrapper.WrappedGraph.OutEdgesAt(node))
                {
                    var child = childEdge.GetTargetNode();
                    if (hiddenNodesSet.Remove(child))
                    {
                        filteredGraphWrapper.WrappedGraph.SetNodeCenter(child, node.Layout.GetCenter());
                        filteredGraphWrapper.WrappedGraph.ClearBends(childEdge);
                    }
                }
                await RefreshLayout(count, node);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 返回未能成功下载的块标记
        /// </summary>
        List <int> DownloadData(byte[] hash, int[] indexs, IPAddress iP)
        {
            var failStat = $"target: {iP} don't have this block";
            List <P2PMessage> result;
            StringBuilder     @string = new StringBuilder();

            foreach (var i in indexs)
            {
                @string.Append($"{i} ");
            }
            _logger.Info($"Now Download {@string} from {iP}");
            using (var transMan = new DownloadTransManager(iP))
            {
                transMan.GetData(hash, indexs);
                result = transMan.GetReply(indexs.Length);
                if (result.Count == 0)
                {
                    transMan.SendCloseMessage();
                    // 如果进入了这里,说明请求的IP里,请求的块一个也没有
                    return(new List <int>(indexs));
                }
                HashSet <int> set = new System.Collections.Generic.HashSet <int>(indexs);
                foreach (var i in result)
                {
                    _logger.Info($"Get {i.type} from {iP}");
                    if (i.type == P2PMessageType.DATA)
                    {
                        var data  = (DataMessage)i;
                        var index = data.p2PDatas.block.index;
                        if (set.Contains(index))
                        {
                            transMan.SendOkMessage(hash, data.p2PDatas.block.index);
                            try
                            {
                                fmanager.OnBlockDownloadSuccess(hash, index, data.p2PDatas.data);
                                set.Remove(index);
                            }
                            catch (FailToDownloadException)
                            {
                            }
                        }
                    }
                    else if (i.type == P2PMessageType.ERROR)
                    {
                        var index = ((ErrorMessage)i).Block.index;
                        fmanager.SetRemoteBlockPresentStat(hash, iP, index, false);
                    }
                }
                transMan.SendCloseMessage();
                return(set.ToList());
            }
        }
Esempio n. 7
0
        //! Calculate path.
        public State RunOnce()
        {
            // While we got something
            while (openSet.Count > 0)
            {
                K current = openSetPriority.Pop().tile;
                openSet.Remove(current);
                // Got the goal
                if (current.Equals(end_))
                {
                    result = ReconstructPath(cameFrom, end_).ToArray();
                    return(State.DONE);
                }
                closedSet.Add(current);
                // Get tile from current
                foreach (K neigh in GetNeigbours(current))
                {
                    float tentative_g = g_score[current] + Distance(current, neigh);
                    // Got some tile in closed set
                    if (closedSet.Contains(neigh))
                    {
                        // If actual g(x) is bigger, no need to examine
                        if (tentative_g >= g_score[neigh])
                        {
                            continue;
                        }
                    }

                    // New tile to examine or g(x) has got better
                    if (!openSet.Contains(neigh) || tentative_g < g_score[neigh])
                    {
                        cameFrom[neigh] = current;
                        g_score[neigh]  = tentative_g;
                        f_score[neigh]  = tentative_g + Heurestic(neigh, end_);

                        if (!openSet.Contains(neigh))
                        {
                            openSet.Add(neigh);
                            openSetPriority.Push(new NodeTag(f_score[neigh], neigh));
                        }
                    }
                }

                return(State.WAIT);
            }

            return(State.FAIL);
        }
Esempio n. 8
0
        /// <summary>
        /// delete a node(a PIN) from HashSet
        /// </summary>
        /// <param name="t">PIN</param>
        /// <returns>Operation is sucessful,return true otherwise false</returns>
        public bool Delete(int t)
        {
            bool rtn = true;

            try
            {
                hash.Remove(t);
            }
            catch (Exception ex)
            {
                rtn = false;
            }
            finally
            {
            }
            return(rtn);
        }
Esempio n. 9
0
 private void Validate_ExceptWith(ISet <T> set, IEnumerable <T> enumerable)
 {
     if (set.Count == 0 || enumerable == set)
     {
         set.ExceptWith(enumerable);
         Assert.Equal(0, set.Count);
     }
     else
     {
         System.Collections.Generic.HashSet <T> expected = new System.Collections.Generic.HashSet <T>(set, GetIEqualityComparer());
         foreach (T element in enumerable)
         {
             expected.Remove(element);
         }
         set.ExceptWith(enumerable);
         Assert.Equal(expected.Count, set.Count);
         Assert.True(expected.SetEquals(set));
     }
 }
Esempio n. 10
0
        public void EnumeratorWork()
        {
            mySet.Add(11);
            mySet.Add(22);
            mySet.Add(44);
            mySet.Add(33);
            mySet.Remove(44);

            System.Collections.Generic.HashSet <int> hs = new System.Collections.Generic.HashSet <int>();
            hs.Add(11);
            hs.Add(22);
            hs.Add(33);

            int foreachcount = 0;

            foreach (int item in mySet)
            {
                foreachcount++;
                Assert.IsTrue(hs.Contains(item));
                hs.Remove(item);//На случай, если в mySet 3 одинаковых элемента
            }
            Assert.AreEqual(3, foreachcount);
        }
        public void greedySolve()
        {
            timer = new Stopwatch();
            timer.Start();
            Route = new ArrayList(Cities.Length);
            System.Collections.Generic.HashSet<int> unvisitedIndexes = new System.Collections.Generic.HashSet<int>(); // using a city's index in Cities, we can interate through indexes that have yet to be added
            for (int index = 0; index < Cities.Length; index++)
            {
                unvisitedIndexes.Add(index);
            }

            print("\n\nTESTING\n");

            City city;
            for (int i = 0; i < Cities.Length; i++) // keep trying start nodes until a solution is found
            {
                if (Route.Count == Cities.Length)
                {
                    break; // DONE!
                }
                else
                {
                    Route.Clear();
                    for (int index = 0; index < Cities.Length; index++)
                    {
                        unvisitedIndexes.Add(index);
                    }
                    city = Cities[i];
                }

                for (int n = 0; n < Cities.Length; n++) // add nodes n times
                {

                    double shortestDistance = Double.PositiveInfinity;
                    int closestIndex = -1;
                    foreach (int check in unvisitedIndexes) //find the closest city to add to route
                    {
                        double distance = city.costToGetTo(Cities[check]);
                        if (distance < shortestDistance)
                        {
                            shortestDistance = distance;
                            closestIndex = check;
                        }
                    }

                    if (closestIndex != -1)
                    {
                        city = Cities[closestIndex];
                        Route.Add(city);
                        unvisitedIndexes.Remove(closestIndex);
                    }
                    else
                    {
                        break; // try again
                    }
                }
            }

            // call this the best solution so far.  bssf is the route that will be drawn by the Draw method.
            bssf = new TSPSolution(Route);
            // update the cost of the tour.
            Program.MainForm.tbCostOfTour.Text = " " + bssf.costOfRoute();
            TimeSpan ts = timer.Elapsed;
            Program.MainForm.tbElapsedTime.Text = ts.TotalSeconds.ToString();
            // do a refresh.
            Program.MainForm.Invalidate();
        }
Esempio n. 12
0
 public bool Remove(T item)
 {
     return(Inner.Remove(item));
 }
Esempio n. 13
0
 /// <summary>
 /// マウス操作時のイベントを削除します。
 /// </summary>
 /// <param name="hookHandler"></param>
 public static void RemoveEvent(HookHandler hookHandler)
 {
     HookEvent -= hookHandler;
     Events.Remove(hookHandler);
 }
Esempio n. 14
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //_tcRows 存放要处理的数据
            for (i = 0; i < _tcRows.Length; Interlocked.Increment(ref i))
            {
                if (CheckState())
                {
                    e.Cancel = true; return;
                }

                ReportStat rs0 = new ReportStat();
                rs0.step         = 0;
                rs0.currentIndex = i;
                rs0.msg          = string.Format("正在处理:{0}。 获取数据...", _tcRows[i]["NAME"]);
                backgroundWorker1.ReportProgress(i * 100 / _tcRows.Length, rs0);

                ReportStat rs1;
                string     strTcData = string.Empty;
                if (CheckState())
                {
                    e.Cancel = true; return;
                }
                try
                {
                    //正常处理信息,错误throw 抛出异常
                    //////
                    DoSomething(i, _tcRows[i]["ID"].ToString(), _tcRows[i]["NAME"].ToString());
                }
                catch (Exception ex)
                {
                    rs1 = new ReportStat();
                    if (!_bIgnoreError && i != _tcRows.Length)
                    {
                        int bOldPause = Interlocked.CompareExchange(ref _bPause, 1, 0);
                        rs1.step = 4;
                    }
                    else
                    {
                        rs1.step = 1;
                    }
                    rs1.currentIndex = i;
                    rs1.msg          = ex.Message;
                    backgroundWorker1.ReportProgress((i + 1) * 100 / _tcRows.Length, rs1);
                    if (CheckState())
                    {
                        e.Cancel = true; return;
                    }

                    continue;
                }

                //成功
                rs1              = new ReportStat();
                rs1.step         = 1;
                rs1.currentIndex = i;
                rs1.msg          = "成功!";
                backgroundWorker1.ReportProgress((i + 1) * 100 / _tcRows.Length, rs1);

                _setErrorList.Remove((int)_tcRows[i]["ID"]);
            }
        }
        public void greedySolve()
        {
            timer = new Stopwatch();
            timer.Start();
            Route = new ArrayList(Cities.Length);
            System.Collections.Generic.HashSet <int> unvisitedIndexes = new System.Collections.Generic.HashSet <int>(); // using a city's index in Cities, we can interate through indexes that have yet to be added
            for (int index = 0; index < Cities.Length; index++)
            {
                unvisitedIndexes.Add(index);
            }

            print("\n\nTESTING\n");

            City city;

            for (int i = 0; i < Cities.Length; i++) // keep trying start nodes until a solution is found
            {
                if (Route.Count == Cities.Length)
                {
                    break; // DONE!
                }
                else
                {
                    Route.Clear();
                    for (int index = 0; index < Cities.Length; index++)
                    {
                        unvisitedIndexes.Add(index);
                    }
                    city = Cities[i];
                }

                for (int n = 0; n < Cities.Length; n++) // add nodes n times
                {
                    double shortestDistance = Double.PositiveInfinity;
                    int    closestIndex     = -1;
                    foreach (int check in unvisitedIndexes) //find the closest city to add to route
                    {
                        double distance = city.costToGetTo(Cities[check]);
                        if (distance < shortestDistance)
                        {
                            shortestDistance = distance;
                            closestIndex     = check;
                        }
                    }

                    if (closestIndex != -1)
                    {
                        city = Cities[closestIndex];
                        Route.Add(city);
                        unvisitedIndexes.Remove(closestIndex);
                    }
                    else
                    {
                        break; // try again
                    }
                }
            }

            // call this the best solution so far.  bssf is the route that will be drawn by the Draw method.
            bssf = new TSPSolution(Route);
            // update the cost of the tour.
            Program.MainForm.tbCostOfTour.Text = " " + bssf.costOfRoute();
            TimeSpan ts = timer.Elapsed;

            Program.MainForm.tbElapsedTime.Text = ts.TotalSeconds.ToString();
            // do a refresh.
            Program.MainForm.Invalidate();
        }
Esempio n. 16
0
        public void HeapWithIndicesTest(int numberOfIterations, int heapSize)
        {
            List <int>                 actions  = new List <int>();
            List <int>                 actions1 = new List <int>();
            Random                     rand     = new Random(55);
            HeapWithIndices <long>     heap     = new HeapWithIndices <long>(new LongComparer());
            ListHeapWithIndices <long> list     = new ListHeapWithIndices <long>(new LongComparer());

            System.Collections.Generic.HashSet <int> listKeys = new System.Collections.Generic.HashSet <int>();
            System.Collections.Generic.HashSet <int> heapKeys = new System.Collections.Generic.HashSet <int>();
            for (int i = 0; i < heapSize; ++i)
            {
                int x = rand.Next() % 100;
                list.Add(x);
                heap.Add(x);
                actions.Add(x);
                actions1.Add(x);
            }
            for (int i = 0; i < numberOfIterations; ++i)
            {
                if (i < heapSize)
                {
                    actions[i] = actions[i] + rand.Next() % 10000000;
                }
                else
                {
                    actions.Add(actions[i - heapSize] + rand.Next() % 10000000);
                }
                if (i < heapSize)
                {
                    actions1[i] = actions1[i] + rand.Next() % 10000000;
                }
                else
                {
                    actions1.Add(actions1[i - heapSize] + rand.Next() % 10000000);
                }
            }
            long      heapSum = 0;
            long      listSum = 0;
            Stopwatch timer   = new Stopwatch();

            timer.Start();
            for (int i = 0; i < actions.Count; ++i)
            {
                ListHeapWithIndices <long> .HeapEntry heapEntry = list.Pop();
                listSum += heapEntry.Value;
                listKeys.Remove(heapEntry.Key);
                listKeys.Add(list.Add(actions[i]));
                if (i % 10 == 0)
                {
                    int key = listKeys.First();
                    listKeys.Remove(key);
                    list.Remove(key);
                    listKeys.Add(list.Add(actions1[i]));
                }
            }

            timer.Stop();

            System.Console.WriteLine(timer.ElapsedMilliseconds);

            timer.Reset();
            timer.Start();
            for (int i = 0; i < actions.Count; ++i)
            {
                HeapWithIndices <long> .HeapEntry heapEntry = heap.Pop();
                heapSum += heapEntry.Value;
                heapKeys.Remove(heapEntry.Key);
                heapKeys.Add(heap.Add(actions[i]));
                if (i % 10 == 0)
                {
                    int key = heapKeys.First();
                    heapKeys.Remove(key);
                    heap.Remove(key);
                    heapKeys.Add(heap.Add(actions1[i]));
                }
            }

            timer.Stop();
            System.Console.WriteLine(timer.ElapsedMilliseconds);

            Assert.AreEqual(heapSum, listSum);
        }