예제 #1
0
        // public
        public static T GetService <T>()
        {
            Type type = typeof(T);

            if (!initializedServices.TryGetValue(type, out object result) && services.Contains(type))
            {
                result = initializedServices.AddIfAbsent(type, InitializeService(type));
            }

            if (result == null)
            {
                lookupCache.TryGetValue(type, out result);
            }

            if (result == null)
            {
                foreach (Type t in services)
                {
                    if (type.Equals(t) || type.IsAssignableFrom(t))
                    {
                        if (!initializedServices.TryGetValue(t, out result))
                        {
                            result = initializedServices.AddIfAbsent(type, InitializeService(t));
                        }
                        lookupCache.TryAdd(type, result);
                        break;
                    }
                }
            }

            return((result != null) ? (T)result : default(T));
        }
예제 #2
0
        public void should_test_that_an_item_is_contained()
        {
            var setToRemoveFrom = new ConcurrentSet<int>(Enumerable.Range(1, 5));

            setToRemoveFrom.Contains(3).ShouldBeTrue();
            setToRemoveFrom.Contains(7).ShouldBeFalse();
        }
예제 #3
0
        public void should_test_that_an_item_is_contained()
        {
            var setToRemoveFrom = new ConcurrentSet <int>(Enumerable.Range(1, 5));

            setToRemoveFrom.Contains(3).ShouldBeTrue();
            setToRemoveFrom.Contains(7).ShouldBeFalse();
        }
예제 #4
0
 public void Send(BulkInsertChangeNotification bulkInsertChangeNotification)
 {
     if (!matchingBulkInserts.Contains(string.Empty) &&
         !matchingBulkInserts.Contains(bulkInsertChangeNotification.OperationId.ToString()))
     {
         return;
     }
     Enqueue(new { Value = bulkInsertChangeNotification, Type = "BulkInsertChangeNotification" });
 }
예제 #5
0
        public void Contains()
        {
            var target = new ConcurrentSet <int>();

            Assert.False(target.Contains(1));

            target.TryAdd(1);

            Assert.True(target.Contains(1));
        }
예제 #6
0
        public void Send(BulkInsertChangeNotification bulkInsertChangeNotification)
        {
            var value = new { Value = bulkInsertChangeNotification, Type = "BulkInsertChangeNotification" };

            if (matchingBulkInserts.Contains(string.Empty) || matchingBulkInserts.Contains(bulkInsertChangeNotification.OperationId.ToString()))
            {
                Enqueue(value);
            }
            return;
        }
예제 #7
0
        public IObservableWithTask <BulkOperationNotification> ForBulkOperation(Guid?operationId = null)
        {
            var id = operationId != null?operationId.ToString() : string.Empty;

            var key        = "bulk-operations/" + id;
            var timeSeries = Counters.GetOrAdd(key, s =>
            {
                watchedBulkOperations.TryAdd(id);
                var bulkOperationSubscriptionTask = AfterConnection(() =>
                {
                    if (watchedBulkOperations.Contains(id)) // might have been removed in the meantime
                    {
                        return(Send("watch-bulk-operation", id));
                    }
                    return(ConnectionTask);
                });

                return(new TimeSeriesConnectionState(
                           () =>
                {
                    watchedBulkOperations.TryRemove(id);
                    Counters.Remove(key);
                    return Send("unwatch-bulk-operation", id);
                },
                           existingConnectionState =>
                {
                    TimeSeriesConnectionState _;
                    if (Counters.TryGetValue("bulk-operations/" + id, out _))
                    {
                        return _.Task;
                    }

                    Counters.GetOrAdd("bulk-operations/" + id, x => existingConnectionState);

                    return AfterConnection(() =>
                    {
                        if (watchedBulkOperations.Contains(id))     // might have been removed in the meantime
                        {
                            return Send("watch-bulk-operation", id);
                        }
                        return ConnectionTask;
                    });
                },
                           bulkOperationSubscriptionTask));
            });

            var taskedObservable = new TaskedObservable <BulkOperationNotification, TimeSeriesConnectionState>(
                timeSeries,
                notification => operationId == null || notification.OperationId == operationId);

            timeSeries.OnBulkOperationNotification += taskedObservable.Send;
            timeSeries.OnError += taskedObservable.Error;

            return(taskedObservable);
        }
예제 #8
0
        public void Send(BulkOperationNotification notification)
        {
            if (matchingBulkOperations.Contains(string.Empty) == false &&
                matchingBulkOperations.Contains(notification.OperationId.ToString()) == false)
            {
                return;
            }

            var value = new { Value = notification, Type = bulkOperationNotificationType };

            enqueue(value);
        }
예제 #9
0
        public IObservableWithTask <BulkInsertChangeNotification> ForBulkInsert(Guid?operationId = null)
        {
            var id = operationId != null?operationId.ToString() : string.Empty;

            var counter = Counters.GetOrAdd("bulk-operations/" + id, s =>
            {
                watchedBulkInserts.TryAdd(id);
                var documentSubscriptionTask = AfterConnection(() =>
                {
                    if (watchedBulkInserts.Contains(id)) // might have been removed in the meantime
                    {
                        return(Send("watch-bulk-operation", id));
                    }
                    return(Task);
                });

                return(new DatabaseConnectionState(
                           () =>
                {
                    watchedBulkInserts.TryRemove(id);
                    Send("unwatch-bulk-operation", id);
                    Counters.Remove("bulk-operations/" + operationId);
                },
                           existingConnectionState =>
                {
                    DatabaseConnectionState _;
                    if (Counters.TryGetValue("bulk-operations/" + id, out _))
                    {
                        return _.Task;
                    }

                    Counters.GetOrAdd("bulk-operations/" + id, x => existingConnectionState);

                    return AfterConnection(() =>
                    {
                        if (watchedBulkInserts.Contains(id))     // might have been removed in the meantime
                        {
                            return Send("watch-bulk-operation", id);
                        }
                        return Task;
                    });
                },
                           documentSubscriptionTask));
            });

            var taskedObservable = new TaskedObservable <BulkInsertChangeNotification, DatabaseConnectionState>(counter,
                                                                                                                notification => operationId == null || notification.OperationId == operationId);

            counter.OnBulkInsertChangeNotification += taskedObservable.Send;
            counter.OnError += taskedObservable.Error;

            return(taskedObservable);
        }
예제 #10
0
        public void AssertOpenSubscriptionConnection(long id, string connection, bool ackRequest = false)
        {
            if (deletedSubscriptions.Contains(id))
            {
                throw new SubscriptionDoesNotExistException("There is no subscription configuration for specified identifier (id: " + id + ")");
            }

            SubscriptionConnectionOptions options;

            if (openSubscriptions.TryGetValue(id, out options) == false)
            {
                throw new SubscriptionClosedException("There is no subscription with id: " + id + " being opened");
            }

            if (options.ConnectionId.Equals(connection, StringComparison.OrdinalIgnoreCase) == false)
            {
                OneTimeAcknowledgement allowance;
                if (ackRequest &&
                    allowedOneTimeAcknowledgements.TryGetValue(id, out allowance) &&
                    allowance.ValidFor(connection))
                {
                    return;
                }
                // prevent from concurrent work of multiple clients against the same subscription
                throw new SubscriptionInUseException("Subscription is being opened for a different connection.");
            }
        }
예제 #11
0
        public void Send(DocumentChangeNotification documentChangeNotification)
        {
            var value = new { Value = documentChangeNotification, Type = "DocumentChangeNotification" };

            if (watchAllDocuments > 0)
            {
                Enqueue(value);
                return;
            }

            if (documentChangeNotification.Id != null)
            {
                if (matchingDocuments.Contains(documentChangeNotification.Id))
                {
                    Enqueue(value);
                    return;
                }

                var hasPrefix = matchingDocumentPrefixes.Any(
                    x => documentChangeNotification.Id.StartsWith(x, StringComparison.InvariantCultureIgnoreCase));
                if (hasPrefix == false)
                {
                    return;
                }
            }
            Enqueue(value);
        }
예제 #12
0
        private void TransactionAfterCommit(Transaction tx)
        {
            if (_activeTransactions.Contains(tx) == false)
            {
                return;
            }

            _txCommit.EnterWriteLock();
            try
            {
                if (tx.Committed && tx.FlushedToJournal)
                {
                    _transactionsCounter = tx.Id;
                }

                State = tx.State;
            }
            finally
            {
                _txCommit.ExitWriteLock();
            }

            if (tx.FlushedToJournal == false)
            {
                return;
            }

            Interlocked.Add(ref _sizeOfUnflushedTransactionsInJournalFile, tx.GetTransactionPages().Count);
            _flushWriter.Set();
        }
예제 #13
0
        public IObservableWithTask <BulkInsertChangeNotification> ForBulkInsert(Guid operationId)
        {
            var id = operationId.ToString();

            var counter = counters.GetOrAdd("bulk-operations/" + id, s =>
            {
                watchedBulkInserts.TryAdd(id);
                var documentSubscriptionTask = AfterConnection(() =>
                {
                    if (watchedBulkInserts.Contains(id)) // might have been removed in the meantime
                    {
                        return(Send("watch-bulk-operation", id));
                    }
                    return(Task);
                });

                return(new LocalConnectionState(
                           () =>
                {
                    watchedBulkInserts.TryRemove(id);
                    Send("unwatch-bulk-operation", id);
                    counters.Remove("bulk-operations/" + operationId);
                },
                           documentSubscriptionTask));
            });

            var taskedObservable = new TaskedObservable <BulkInsertChangeNotification>(counter,
                                                                                       notification =>
                                                                                       notification.OperationId == operationId);

            counter.OnBulkInsertChangeNotification += taskedObservable.Send;
            counter.OnError += taskedObservable.Error;

            return(taskedObservable);
        }
예제 #14
0
        public static IGraph <FlowShape <Uri, Uri>, NotUsed> MyCrawler()
        {
            var index = new ConcurrentSet <Uri>();

            var graph = GraphDsl.Create(b =>
            {
                var merge = b.Add(new MergePreferred <Uri>(1));
                var bcast = b.Add(new Broadcast <Uri>(2));

                // async downlad page from provided uri
                // resolve links from it
                var flow = Flow.Create <Uri>()
                           .Where(uri => index.TryAdd(uri))
                           .SelectAsyncUnordered(4, DownloadPage)
                           .SelectMany(ResolveLinks);

                // feedback loop - take only those elements,
                // which were successfully added to index (unique)
                var flowBack = Flow.Create <Uri>()
                               .Collect(uri => !index.Contains(uri) ? uri : null)
                               .ConflateWithSeed(uri => ImmutableList.Create(uri), (uris, uri) => uris.Add(uri))
                               .SelectMany(uris => uris);

                b.From(merge).Via(flow).To(bcast);
                b.From(bcast).Via(flowBack).To(merge.Preferred);

                return(new FlowShape <Uri, Uri>(merge.In(0), bcast.Out(1)));
            });

            return(graph);
        }
예제 #15
0
        public async Task AddGameAsync(string gameName)
        {
            Game game = await Game.Find(gameName);

            if (game == null)
            {
                await Response("Couldn't locate game, please supply a valid speedrun.com url or game id");

                return;
            }

            ConcurrentSet <string> trackedGames = Context.Bot.Config
                                                  .GetOrAddGuild(Context.Guild.Id)
                                                  .GetOrAddGameList(Context.Channel.Id);

            if (trackedGames.Contains(game.Id))
            {
                await Response($"Game '{game.Name}' is already being tracked in this channel");

                return;
            }

            trackedGames.Add(game.Id);
            await Response($"Now tracking game '{game.Name}'");
        }
예제 #16
0
        public async Task <IPeeringResult> PeerChildAsync(IDipNode child)
        {
            if (m_parentNode == child)
            {
                throw new InvalidOperationException("Cannot create circular child/parent dependency");
            }

            if (m_peeringChildren.Contains(child) || m_children.Contains(child))
            {
                m_peeringChildren.TryRemove(child);
                return(PeeringSuccess(child));
            }
            else
            {
                m_peeringChildren.TryAdd(child);
                var result = this.PeerChild(child);
                m_peeringChildren.TryRemove(child);
                if (result.PeeringState == PeeringState.Connected)
                {
                    m_children.TryAdd(child);
                    m_peersByGuid.TryAdd(child.Guid, child);
                }
                return(result);
            }
        }
예제 #17
0
        private async Task OnAuthRequiredAsync(FetchAuthRequiredResponse e)
        {
            var response = "Default";

            if (_attemptedAuthentications.Contains(e.RequestId))
            {
                response = "CancelAuth";
            }
            else if (_credentials != null)
            {
                response = "ProvideCredentials";
                _attemptedAuthentications.Add(e.RequestId);
            }
            var credentials = _credentials ?? new Credentials();

            try
            {
                await _client.SendAsync("Fetch.continueWithAuth", new ContinueWithAuthRequest
                {
                    RequestId             = e.RequestId,
                    AuthChallengeResponse = new ContinueWithAuthRequestChallengeResponse
                    {
                        Response = response,
                        Username = credentials.Username,
                        Password = credentials.Password
                    }
                }).ConfigureAwait(false);
            }
            catch (PuppeteerException ex)
            {
                _logger.LogError(ex.ToString());
            }
        }
예제 #18
0
        public bool ContainsState(State state)
        {
            if (state == null)
            {
                throw new ArgumentNullException("state");
            }

            return(states.Contains(state));
        }
예제 #19
0
        public override ImmutableArray <MetadataReference> GetUsedAssemblyReferences(
            CancellationToken cancellationToken = default
            )
        {
            ConcurrentSet <AssemblySymbol>?usedAssemblies = GetCompleteSetOfUsedAssemblies(
                cancellationToken
                );

            if (usedAssemblies is null)
            {
                return(ImmutableArray <MetadataReference> .Empty);
            }

            var setOfReferences = new HashSet <MetadataReference>(
                ReferenceEqualityComparer.Instance
                );
            ImmutableDictionary <
                MetadataReference,
                ImmutableArray <MetadataReference>
                > mergedAssemblyReferencesMap = GetBoundReferenceManager().MergedAssemblyReferencesMap;

            foreach (var reference in References)
            {
                if (reference.Properties.Kind == MetadataImageKind.Assembly)
                {
                    Symbol?symbol = GetBoundReferenceManager()
                                    .GetReferencedAssemblySymbol(reference);
                    if (
                        symbol is object &&
                        usedAssemblies.Contains((AssemblySymbol)symbol) &&
                        setOfReferences.Add(reference) &&
                        mergedAssemblyReferencesMap.TryGetValue(
                            reference,
                            out ImmutableArray <MetadataReference> merged
                            )
                        )
                    {
                        // Include all "merged" references as well because they might "define" used extern aliases.
                        setOfReferences.AddAll(merged);
                    }
                }
            }

            // Use stable ordering for the result, matching the order in References.
            var builder = ArrayBuilder <MetadataReference> .GetInstance(setOfReferences.Count);

            foreach (var reference in References)
            {
                if (setOfReferences.Contains(reference))
                {
                    builder.Add(reference);
                }
            }

            return(builder.ToImmutableAndFree());
        }
예제 #20
0
        public async Task <IPeeringResult> PeerParentAsync(IDipNode parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }

            if (m_peeringParent == parent)
            {
                m_peeringParent = null;
                return(PeeringSuccess(parent));
            }
            try
            {
                this.m_parentNodeSemaphore.WaitOne();
                m_peeringParent = parent;

                if (m_parentNode == parent)
                {
                    return(PeeringSuccess(parent));
                }

                if (m_children.Contains(parent))
                {
                    throw new InvalidOperationException("Cannot create circular child/parent dependency");
                }

                var result = PeerParent(parent);
                if (result.PeeringState == PeeringState.Connected)
                {
                    m_parentNode = parent;
                    m_peersByGuid.TryAdd(parent.Guid, parent);
                    m_identifier.Parent = parent.Identifier;
                }
                return(result);
            }
            finally
            {
                this.m_parentNodeSemaphore.Release();
            }
        }
예제 #21
0
        private bool FilterDocuments(JsonDocument document)
        {
            var documentToRemove = new DocumentToRemove(document.Key, document.Etag);

            if (documentsToRemove.Contains(documentToRemove))
            {
                documentsToRemove.TryRemove(documentToRemove);
                return(true);
            }

            return(false);
        }
예제 #22
0
        public void SendOperationStatusChangeNotification(OperationStatusChange change)
        {
            if (_watchAllOperations > 0)
            {
                Send(change);
                return;
            }

            if (_matchingOperations.Contains(change.OperationId))
            {
                Send(change);
            }
        }
예제 #23
0
        public void SendIndexChanges(IndexChange change)
        {
            if (_watchAllIndexes > 0)
            {
                Send(change);
                return;
            }

            if (change.Name != null && _matchingIndexes.Contains(change.Name))
            {
                Send(change);
            }
        }
예제 #24
0
        public void Send(DocumentChangeNotification documentChangeNotification)
        {
            var value = new { Value = documentChangeNotification, Type = "DocumentChangeNotification" };

            if (watchAllDocuments > 0)
            {
                Enqueue(value);
                return;
            }

            if (documentChangeNotification.Id != null && matchingDocuments.Contains(documentChangeNotification.Id))
            {
                Enqueue(value);
                return;
            }

            var hasPrefix = documentChangeNotification.Id != null && matchingDocumentPrefixes
                            .Any(x => documentChangeNotification.Id.StartsWith(x, StringComparison.InvariantCultureIgnoreCase));

            if (hasPrefix)
            {
                Enqueue(value);
                return;
            }

            var hasCollection = documentChangeNotification.CollectionName != null && matchingDocumentsInCollection
                                .Any(x => string.Equals(x, documentChangeNotification.CollectionName, StringComparison.InvariantCultureIgnoreCase));

            if (hasCollection)
            {
                Enqueue(value);
                return;
            }

            var hasType = documentChangeNotification.TypeName != null && matchingDocumentsOfType
                          .Any(x => string.Equals(x, documentChangeNotification.TypeName, StringComparison.InvariantCultureIgnoreCase));

            if (hasType)
            {
                Enqueue(value);
                return;
            }

            if (documentChangeNotification.Id != null || documentChangeNotification.CollectionName != null || documentChangeNotification.TypeName != null)
            {
                return;
            }

            Enqueue(value);
        }
예제 #25
0
        private void EnsureIndexExists()
        {
            if (performedIndexChecks.Contains(ApplicationModel.Database.Value.Name))
            {
                return;
            }

            if (!performedIndexChecks.TryAdd(ApplicationModel.Database.Value.Name))
            {
                return;
            }

            CreateIndex();
        }
예제 #26
0
        public void SendIndexChanges(IndexChangeNotification notification)
        {
            if (_watchAllIndexes > 0)
            {
                Send(notification);
                return;
            }

            if (notification.Name != null && _matchingIndexes.Contains(notification.Name))
            {
                Send(notification);
                return;
            }
        }
예제 #27
0
            public override void OnTick()
            {
                base.OnTick();

                foreach (var command in commands)
                {
                    bool executing = executingCommands.Contains(command);

                    if (!executing && command.IsExecutable)
                    {
                        var subsystemConflict = (command.Subsystem & activeSubsystems) != 0;

                        if (((command.IsPassive || command.IsTriggered) && !subsystemConflict) || command.IsForceTriggered)
                        {
                            foreach (var executingCommand in executingCommands)
                            {
                                if ((executingCommand.Subsystem & command.Subsystem) != 0)
                                {
                                    activeSubsystems &= ~executingCommand.Subsystem;

                                    executingCommand.Cancel();
                                    executingCommands.RemoveOrThrow(executingCommand);
                                }
                            }

                            Console.WriteLine($"Start Command {command}.");
                            command.Start();
                            executing = true;
                            executingCommands.AddOrThrow(command);

                            if (!command.IsPassive)
                            {
                                activeSubsystems |= command.Subsystem;
                            }
                        }
                    }

                    if (executing)
                    {
                        var status = command.RunIteration();
                        if (status == CommandStatus.Complete || status == CommandStatus.Abort)
                        {
                            Console.WriteLine($"Command {command} finishing: {status}");
                            activeSubsystems &= ~command.Subsystem;

                            executingCommands.RemoveOrThrow(command);
                        }
                    }
                }
            }
        public static async Task <(bool success, string message)> SetUserPermission(VCommandContext context, ulong userId, string permInput, bool givePerm)
        {
            if (!MatchModuleOrCommand(context.Bot, permInput, out string perm))
            {
                return(false, $"Permission '{permInput}' is not valid");
            }

            if (await context.Guild.FetchMemberAsync(userId) is not IMember user)
            {
                return(false, "User not found");
            }

            ConcurrentSet <string> userPerms = context.Bot.Config
                                               .GetOrAddGuild(context.Guild.Id)
                                               .GetOrAddUserPerms(userId);

            // Give permission
            if (givePerm)
            {
                if (userPerms.Contains(perm))
                {
                    return(false, $"User {user.Name}#{user.Discriminator} already has permission '{perm}'");
                }

                userPerms.Add(perm);
                return(true, $"Given permission '{perm}' to user {user.Name}#{user.Discriminator}");
            }

            // Revoke permission
            if (!userPerms.Contains(perm))
            {
                return(false, $"User {user.Name}#{user.Discriminator} does not have permission '{perm}'");
            }

            userPerms.Remove(perm);
            return(true, $"Revoked permission '{perm}' from user {user.Name}#{user.Discriminator}");
        }
        public static async Task <(bool success, string message)> SetRolePermission(VCommandContext context, ulong roleId, string permInput, bool givePerm)
        {
            if (!MatchModuleOrCommand(context.Bot, permInput, out string perm))
            {
                return(false, $"Permission '{permInput}' is not valid");
            }

            if (await context.Bot.GetRoleAsync(context.GuildId, roleId) is not IRole role)
            {
                return(false, "Role not found");
            }

            ConcurrentSet <string> rolePerms = context.Bot.Config
                                               .GetOrAddGuild(context.Guild.Id)
                                               .GetOrAddRolePerms(roleId);

            // Give permission
            if (givePerm)
            {
                if (rolePerms.Contains(perm))
                {
                    return(false, $"Role '{role.Name}' already has permission '{perm}'");
                }

                rolePerms.Add(perm);
                return(true, $"Given permission '{perm}' to role '{role.Name}'");
            }

            // Revoke permission
            if (!rolePerms.Contains(perm))
            {
                return(false, $"Role '{role.Name}' does not have permission '{perm}'");
            }

            rolePerms.Remove(perm);
            return(true, $"Revoked permission '{perm}' from role '{role.Name}'");
        }
예제 #30
0
        protected bool TryGetOrCreateResourceStore(string tenantId, out Task <DocumentDatabase> database)
        {
            if (ResourcesStoresCache.TryGetValue(tenantId, out database))
            {
                if (database.IsFaulted || database.IsCanceled)
                {
                    ResourcesStoresCache.TryRemove(tenantId, out database);
                    DateTime time;
                    databaseLastRecentlyUsed.TryRemove(tenantId, out time);
                    // and now we will try creating it again
                }
                else
                {
                    return(true);
                }
            }

            if (LockedDatabases.Contains(tenantId))
            {
                throw new InvalidOperationException("Database '" + tenantId + "' is currently locked and cannot be accessed");
            }

            var config = CreateTenantConfiguration(tenantId);

            if (config == null)
            {
                return(false);
            }

            database = ResourcesStoresCache.GetOrAdd(tenantId, __ => Task.Factory.StartNew(() =>
            {
                var documentDatabase = new DocumentDatabase(config);
                AssertLicenseParameters(config);
                documentDatabase.SpinBackgroundWorkers();
                InitializeRequestResponders(documentDatabase);

                // if we have a very long init process, make sure that we reset the last idle time for this db.
                databaseLastRecentlyUsed.AddOrUpdate(tenantId, SystemTime.UtcNow, (_, time) => SystemTime.UtcNow);
                return(documentDatabase);
            }).ContinueWith(task =>
            {
                if (task.Status == TaskStatus.Faulted)                 // this observes the task exception
                {
                    logger.WarnException("Failed to create database " + tenantId, task.Exception);
                }
                return(task);
            }).Unwrap());
            return(true);
        }
예제 #31
0
        public ChainedHeader FindMaxTotalWork()
        {
            ChainedHeader maxTotalWorkHeader = null;

            foreach (var chainedHeader in this.chainedHeaders.Values)
            {
                if (!invalidBlocks.Contains(chainedHeader.Hash) &&
                    (maxTotalWorkHeader == null || chainedHeader.TotalWork > maxTotalWorkHeader.TotalWork))
                {
                    maxTotalWorkHeader = chainedHeader;
                }
            }

            return(maxTotalWorkHeader);
        }
예제 #32
0
      public MainWindow() {
         InitializeComponent();

         var pushedKeys = new ConcurrentSet<SWF.Keys>();

         var betterRunAutocompletionSource = new BetterRunAutocompletionSource();
         var webAutocompletionSource = new WebAutocompletionSource();
         webAutocompletionSource.Initialize();

         var githubAutocompletionSource = new GithubAutocompletionSource();

         var startMenuAutocompletionSource = new StartMenuAutocompletionSource();
         startMenuAutocompletionSource.Initialize();

         var bashAutocompletionSource = new BashAutocompletionSource();
         bashAutocompletionSource.Initialize();

         var viewModel = new RootViewModel(this, pushedKeys);
         viewModel.PropertyChanged += (s, e) => {
            try {
               var query = viewModel.Query;
               var autocompletionSources = new AutocompletionSource[] {
                  startMenuAutocompletionSource,
                  webAutocompletionSource,
                  githubAutocompletionSource,
                  bashAutocompletionSource,
                  betterRunAutocompletionSource
               };
               if (query.IndexOf(':') != -1 && query.IndexOf(':') <= 3) {
                  Console.WriteLine("!@#@!#" + query);
                  var bobkuh = query.Substring(0, query.IndexOf(":"));
                  query = query.Substring(bobkuh.Length + 1);
                  autocompletionSources = autocompletionSources.Where(x => x.Bobkuh?.Equals(bobkuh, StringComparison.OrdinalIgnoreCase) ?? false).ToArray();
               }
               query = query.Trim();

               if (e.PropertyName.Equals(nameof(viewModel.Query))) {
                  viewModel.Suggestions.Clear();
                  if (viewModel.Query != "") {
                     var euphius = autocompletionSources.SelectMany(x => x.Query(query)).OrderByDescending(x => x.Blithee).GroupBy(x => x.Textd).Select(x => x.First());
                     foreach (var suggesteion in euphius.Take(7)) {
                        suggesteion.ParentViewModel = viewModel;
                        viewModel.Suggestions.Add(suggesteion);
                     }
                  }
               }
            } catch (Exception ex) {
               Console.WriteLine(ex);
            }
         };
         this.DataContext = viewModel;

         this.Hide();

         this.InputTextBox.LostFocus += (s, e) => { Console.WriteLine("!@#!@##"); this.Hide(); };
         this.Deactivated += (s, e) => { this.Hide(); };

         var hwnd = new WindowInteropHelper(this).Handle;

         var globalHook = Gma.System.MouseKeyHook.Hook.GlobalEvents();
         SWF.KeyEventHandler down = null, up = null;
         ConcurrentQueue<Tuple<bool, SWF.Keys>> q = new ConcurrentQueue<Tuple<bool, SWF.Keys>>();
         var semaph = new Semaphore(0, int.MaxValue);
         InterceptKeys.Start();
         InterceptKeys.KeyUp += (key) => {
            q.Enqueue(new Tuple<bool, SWF.Keys>(false, key));
            semaph.Release();
         };
         InterceptKeys.KeyDown += (key) => {
            q.Enqueue(new Tuple<bool, SWF.Keys>(true, key));
            semaph.Release();
         };
         new Thread(() => {
            while (true) {
               semaph.WaitOne();
               Tuple<bool, SWF.Keys> result;
               if (!q.TryDequeue(out result)) {
                  throw new Exception("wtf");
               }
               if (result.Item1) {
                  pushedKeys.TryAdd(result.Item2);
                  if (pushedKeys.Count == 3 &&
                      pushedKeys.Contains(SWF.Keys.LControlKey) &&
                      pushedKeys.Contains(SWF.Keys.LWin) &&
                      pushedKeys.Contains(SWF.Keys.R)) {
                     Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                        // I have no clue how this works
                        SetWindowSizeStonerDawg();
                        viewModel.Query = "";
                        this.WindowState = WindowState.Minimized;
                        this.Show();
                        SetWindowSizeStonerDawg();
                        this.WindowState = WindowState.Normal;
                        Keyboard.Focus(InputTextBox);
                        SetWindowSizeStonerDawg();
                     }), DispatcherPriority.Send);
                  } else {
                     Console.WriteLine(pushedKeys.Join(", "));
                  }
               } else {
                  pushedKeys.TryRemove(result.Item2);
               }
            }
         }).Start();
      }