Example #1
0
 public void RegisterSearchChannel(SearchContext searchContext)
 {
     this._searchService.GetSearchParameters(CLAIMS_SEARCH_SP_NAME, parameters =>
     {
         this._searchParameters = parameters;
         searchContext.RegisterSearchChannel(this.GetChannel(this._searchTypeName));
     });
 }
Example #2
0
        public bool ClaimsSearchFilter(SearchContext searchContext)
        {
            if (this.DuplicateSearchTypeFilter(searchContext))
            {
                return true;
            }

            if (searchContext.ChannelCriteria.SearchGroup == SearchGroup.Global)
            {
                return true;
            }

            return false;
        }
Example #3
0
        public void set_search_context(SearchContext context)
        {
            this.args_[1] = context.Search.ToString().ToLower();

            if (context.CardLevel != Constants.CardLevel.INVALID)
                this.set_parameter("lev", context.CardLevel.ToString());

            if (context.Bid.Min != 0)
                this.set_parameter("micr", context.Bid.Min.ToString());
            if (context.Bid.Max != 0)
                this.set_parameter("macr", context.Bid.Max.ToString());

            if (context.BuyNow.Min != 0)
                this.set_parameter("minb", context.BuyNow.Min.ToString());
            if (context.BuyNow.Max != 0)
                this.set_parameter("maxb", context.BuyNow.Max.ToString());
        }
 private static SearchTable GetDefaultTableConfig(SearchContext context)
 {
     return(new SearchTable(type, new [] { new SearchColumn("Name", "label") }.Concat(FetchColumns(context, null))));
 }
        private static IEnumerator SearchAssets(SearchContext context, List <SearchItem> items, SearchProvider provider)
        {
            var searchQuery    = context.searchQuery;
            var searchGuids    = context.categories.Any(c => c.id == "guid" && c.isEnabled);
            var searchPackages = context.categories.Any(c => c.id == "packages" && c.isEnabled);

            // Search by GUIDs
            if (searchGuids)
            {
                var gui2Path = AssetDatabase.GUIDToAssetPath(searchQuery);
                if (!String.IsNullOrEmpty(gui2Path))
                {
                    yield return(provider.CreateItem(gui2Path, -1, $"{Path.GetFileName(gui2Path)} ({searchQuery})", null, null, null));
                }
            }

            if (SearchSettings.useUberIndexing)
            {
                var adbIndex = ADBIndex.Get();

                if (!adbIndex.IsReady())
                {
                    foreach (var assetEntry in AssetDatabase.FindAssets(searchQuery)
                             .Select(AssetDatabase.GUIDToAssetPath)
                             .Select(path => provider.CreateItem(path, Path.GetFileName(path))))
                    {
                        yield return(assetEntry);
                    }
                }

                // Search index
                while (!adbIndex.IsReady())
                {
                    yield return(null);
                }

                yield return(adbIndex.Search(searchQuery).Select(e =>
                {
                    var filename = Path.GetFileName(e.path);
                    var filenameNoExt = Path.GetFileNameWithoutExtension(e.path);
                    var itemScore = e.score;
                    var words = context.searchPhrase;
                    if (filenameNoExt.Equals(words, StringComparison.OrdinalIgnoreCase))
                    {
                        itemScore = SearchProvider.k_RecentUserScore + 1;
                    }

                    string description = adbIndex.GetDebugIndexStrings(e.path);
                    return provider.CreateItem(e.path, itemScore, filename, description, null, null);
                }));
            }
            else
            {
                var fileIndexerReady = fileIndexer.IsReady();
                if (fileIndexerReady)
                {
                    if (searchQuery.IndexOfAny(k_InvalidIndexedChars) == -1)
                    {
                        foreach (var item in SearchFileIndex(searchQuery, searchPackages, provider))
                        {
                            yield return(item);
                        }
                        if (!context.wantsMore)
                        {
                            yield break;
                        }
                    }
                }

                if (!searchPackages)
                {
                    if (!searchQuery.Contains("a:assets"))
                    {
                        searchQuery = "a:assets " + searchQuery;
                    }
                }

                foreach (var assetEntry in AssetDatabase.FindAssets(searchQuery).Select(AssetDatabase.GUIDToAssetPath).Select(path => provider.CreateItem(path, Path.GetFileName(path))))
                {
                    yield return(assetEntry);
                }

                if (!fileIndexerReady)
                {
                    // Indicate to the user that we are still building the index.
                    while (!fileIndexer.IsReady())
                    {
                        yield return(null);
                    }

                    foreach (var item in SearchFileIndex(searchQuery, searchPackages, provider))
                    {
                        yield return(item);
                    }
                }
            }

            // Search file system wildcards
            if (context.searchQuery.Contains('*'))
            {
                var safeFilter   = string.Join("_", context.searchQuery.Split(k_InvalidSearchFileChars));
                var projectFiles = System.IO.Directory.EnumerateFiles(Application.dataPath, safeFilter, System.IO.SearchOption.AllDirectories);
                projectFiles = projectFiles.Select(path => path.Replace(Application.dataPath, "Assets").Replace("\\", "/"));
                foreach (var fileEntry in projectFiles.Select(path => provider.CreateItem(path, Path.GetFileName(path))))
                {
                    yield return(fileEntry);
                }
            }
        }
Example #6
0
 public IPositionGenerator <TicTacToeMove> Expand(SearchContext <object, TicTacToeState, TicTacToeMove, object, TicTacToeMove> context, TicTacToeState position)
 {
     return(new TicTacToeMoveGenerator(position));
 }
Example #7
0
        private IEnumerator BuildIndex(SearchContext context, SearchProvider provider, GameObject[] objects, SearchIndexer indexer)
        {
            #if DEBUG_TIMING
            using (new DebugTimer($"Build scene index ({objects.Length})"))
            #endif
            {
                var useFuzzySearch = context.IsFilterEnabled("fuzzy");

                indexer.Start();
                for (int i = 0; i < objects.Length; ++i)
                {
                    var gameObject = objects[i];
                    var id = objects[i].GetInstanceID();
                    var name = CleanName(gameObject.name);
                    var path = CleanName(GetTransformPath(gameObject.transform));

                    var documentId = id.ToString();
                    int docIndex = indexer.AddDocument(documentId, false);

                    int scoreIndex = 1;
                    var parts =  SearchUtils.SplitEntryComponents(name, indexer.entrySeparators, 2, indexer.maxIndexCharVariation)
                                     .Concat(SplitWords(path, indexer.entrySeparators, indexer.maxIndexCharVariation))
                                     .Distinct().Take(10).ToArray();
                    //UnityEngine.Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, gameObject, $"{path} (<b>{parts.Length}</b>) = {String.Join(",", parts)}");
                    foreach (var word in parts)
                        indexer.AddWord(word, indexer.minIndexCharVariation, indexer.maxIndexCharVariation, scoreIndex++, docIndex);

                    name = name.ToLowerInvariant();
                    indexer.AddExactWord(name, 0, docIndex);
                    if (name.Length > indexer.maxIndexCharVariation)
                        indexer.AddWord(name, indexer.maxIndexCharVariation+1, name.Length, 1, docIndex);

                    var keywords = buildKeywordComponents(objects[i]);
                    if (keywords != null)
                    {
                        foreach (var keyword in keywords)
                            foreach (var word in SplitWords(keyword, indexer.entrySeparators, indexer.maxIndexCharVariation))
                                indexer.AddWord(word, scoreIndex++, docIndex);
                    }

                    var ptype = PrefabUtility.GetPrefabAssetType(gameObject);
                    if (ptype != PrefabAssetType.NotAPrefab)
                        indexer.AddProperty("t", "prefab", 6, 6, 30, docIndex);

                    var gocs = gameObject.GetComponents<Component>();
                    for (int componentIndex = 1; componentIndex < gocs.Length; ++componentIndex)
                    {
                        var c = gocs[componentIndex];
                        if (!c || c.hideFlags.HasFlag(HideFlags.HideInInspector))
                            continue;

                        indexer.AddProperty("t", c.GetType().Name.ToLowerInvariant(), 40 + componentIndex, docIndex);
                    }

                    // While we are building the scene, lets search for objects name
                    yield return MatchItem(context, provider, documentId, name, useFuzzySearch);
                }

                indexer.Finish(true);
            }
        }
Example #8
0
 public SearchContext(SearchContext copy)
 {
     this.m_searchPage = copy.SearchPage;
     this.m_findValue  = copy.FindValue;
 }
            /// <summary>
            /// Advances the enumerator to the next element of the collection.
            /// </summary>
            /// <returns>
            /// true if the enumerator was successfully advanced to the next element;
            /// false if the enumerator has passed the end of the collection.
            /// </returns>
            /// <exception cref="T:System.InvalidOperationException">
            /// The collection was modified after the enumerator was created.
            /// </exception>
            public bool MoveNext()
            {
                bool retval = false;

                //If the handle is null, this is first call to MoveNext in the current
                // directory.  In that case, start a new search.
                if (m_currentContext.SubdirectoriesToProcess == null)
                {
                    if (m_hndFindFile == null)
                    {
                        new FileIOPermission(FileIOPermissionAccess.PathDiscovery, m_path).Demand();

                        string searchPath = Path.Combine(m_path, m_filter);
                        m_hndFindFile = FindFirstFile(searchPath, m_win_find_data);
                        retval        = !m_hndFindFile.IsInvalid;
                    }
                    else
                    {
                        //Otherwise, find the next item.
                        retval = FindNextFile(m_hndFindFile, m_win_find_data);
                    }
                }

                //If the call to FindNextFile or FindFirstFile succeeded...
                if (retval)
                {
                    if (((FileAttributes)m_win_find_data.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        //Ignore folders for now.   We call MoveNext recursively here to
                        // move to the next item that FindNextFile will return.
                        return(MoveNext());
                    }
                }
                else if (m_searchOption == SearchOption.AllDirectories)
                {
                    //SearchContext context = new SearchContext(m_hndFindFile, m_path);
                    //m_contextStack.Push(context);
                    //m_path = Path.Combine(m_path, m_win_find_data.cFileName);
                    //m_hndFindFile = null;

                    if (m_currentContext.SubdirectoriesToProcess == null)
                    {
                        string[] subDirectories = Directory.GetDirectories(m_path);
                        m_currentContext.SubdirectoriesToProcess = new Stack <string>(subDirectories);
                    }

                    if (m_currentContext.SubdirectoriesToProcess.Count > 0)
                    {
                        string subDir = m_currentContext.SubdirectoriesToProcess.Pop();

                        m_contextStack.Push(m_currentContext);
                        m_path           = subDir;
                        m_hndFindFile    = null;
                        m_currentContext = new SearchContext(m_path);
                        return(MoveNext());
                    }

                    //If there are no more files in this directory and we are
                    // in a sub directory, pop back up to the parent directory and
                    // continue the search from there.
                    if (m_contextStack.Count > 0)
                    {
                        m_currentContext = m_contextStack.Pop();
                        m_path           = m_currentContext.Path;
                        if (m_hndFindFile != null)
                        {
                            m_hndFindFile.Close();
                            m_hndFindFile = null;
                        }

                        return(MoveNext());
                    }
                }

                return(retval);
            }
Example #10
0
 //private string source_dirname_;
 /// <summary>
 /// 
 /// </summary>
 public FileSearcher()
 {
     this.context_ = new SearchContext();
 }
Example #11
0
        public FutbotWeb.Json.SearchInfo.RootObject<FutbotWeb.Json.ItemData.PlayerItemData> search_players(SearchContext context)
        {
            AuctionHouseSearch ahs = new AuctionHouseSearch(this._context, Constants.Search.Player);

            ahs.set_search_context(context);
            this.ProcessRequest(ahs);

            return (FutbotWeb.Json.SearchInfo.RootObject<FutbotWeb.Json.ItemData.PlayerItemData>)this._context.Fifa.last_info;
        }
Example #12
0
        private bool DuplicateSearchTypeFilter(SearchContext searchContext)
        {
            if (searchContext == null || searchContext.ChannelCriteria == null)
            {
                return false;
            }

            if (searchContext.ChannelCriteria.SearchGroup == SearchGroup.Global)
            {
                return true;
            }

            return false;
        }
Example #13
0
 public void ClaimsSearch(SearchContext searchContext)
 {
     this._container.Resolve<AXAClaimSearch>().RegisterSearchChannel(searchContext);
 }
        internal static List <object> UnityObjectSearch(string input, string customTypeInput, SearchContext context,
                                                        ChildFilter childFilter, SceneFilter sceneFilter)
        {
            var results = new List <object>();

            Type searchType = null;

            if (!string.IsNullOrEmpty(customTypeInput))
            {
                if (ReflectionUtility.GetTypeByName(customTypeInput) is Type customType)
                {
                    if (typeof(UnityEngine.Object).IsAssignableFrom(customType))
                    {
                        searchType = customType;
                    }
                    else
                    {
                        ExplorerCore.LogWarning($"Custom type '{customType.FullName}' is not assignable from UnityEngine.Object!");
                    }
                }
                else
                {
                    ExplorerCore.LogWarning($"Could not find any type by name '{customTypeInput}'!");
                }
            }

            if (searchType == null)
            {
                searchType = typeof(UnityEngine.Object);
            }

            var allObjects = RuntimeProvider.Instance.FindObjectsOfTypeAll(searchType);

            // perform filter comparers

            string nameFilter = null;

            if (!string.IsNullOrEmpty(input))
            {
                nameFilter = input;
            }

            bool shouldFilterGOs = searchType == typeof(GameObject) || typeof(Component).IsAssignableFrom(searchType);

            foreach (var obj in allObjects)
            {
                // name check
                if (!string.IsNullOrEmpty(nameFilter) && !obj.name.ContainsIgnoreCase(nameFilter))
                {
                    continue;
                }

                GameObject go   = null;
                var        type = obj.GetActualType();

                if (type == typeof(GameObject))
                {
                    go = obj.TryCast <GameObject>();
                }
                else if (typeof(Component).IsAssignableFrom(type))
                {
                    go = obj.TryCast <Component>()?.gameObject;
                }

                if (go)
                {
                    // hide unityexplorer objects
                    if (go.transform.root.name == "ExplorerCanvas")
                    {
                        continue;
                    }

                    if (shouldFilterGOs)
                    {
                        // scene check
                        if (sceneFilter != SceneFilter.Any)
                        {
                            if (!Filter(go.scene, sceneFilter))
                            {
                                continue;
                            }
                        }

                        if (childFilter != ChildFilter.Any)
                        {
                            if (!go)
                            {
                                continue;
                            }

                            // root object check (no parent)
                            if (childFilter == ChildFilter.HasParent && !go.transform.parent)
                            {
                                continue;
                            }
                            else if (childFilter == ChildFilter.RootObject && go.transform.parent)
                            {
                                continue;
                            }
                        }
                    }
                }

                results.Add(obj);
            }

            return(results);
        }
Example #15
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="currentDirName"></param>
 public FileSearcher(string __context_directory_name)
 {
     this.context_ = new SearchContext( __context_directory_name );
 }
Example #16
0
 private static IEnumerable <string> FetchTagKeywords(SearchContext context, string lastToken)
 {
     return(UnityEditorInternal.InternalEditorUtility.tags);
 }
 private SearchContext LoadSearchContext(GlobalSearchControllerArgs args)
 {
     SearchContext context = new SearchContext();
     context.ChannelCriteria = args.SearchCriteria.GetChannelCriteria();
     context.RegisterSearchChannel = this.RegisterChannel;
     // Set the task arguments in the serach request.
     this.ClaimSearchModel.SearchCriteria = args;
     return context;
 }
Example #18
0
 public SearchService(SearchContext DbContext)
 {
     this.DbContext = DbContext;
 }
Example #19
0
 public IEnumerable <BuilderType> FindTypesByInterfaces(SearchContext searchContext, params Type[] interfaceTypes) => this.FindTypesByInterfaces(searchContext, interfaceTypes.Select(x => x.FullName).ToArray());
Example #20
0
 private void OnSearchContextChanged(string searchContextName)
 {
     _searchContext = (SearchContext) Enum.Parse(typeof (SearchContext), searchContextName, false);
 }
Example #21
0
 public IEnumerable <AttributedField> FindFieldsByAttribute(SearchContext searchContext, Type attributeType) => FindFieldsByAttribute(searchContext, attributeType.FullName);
Example #22
0
 public bool Done(SearchContext <object, TicTacToeState, TicTacToeMove, object, TicTacToeMove> context, TicTacToeState position)
 {
     UpdateState(position);
     return(position.Done);
 }
Example #23
0
 public IEnumerable <Field> FindFieldsByName(SearchContext searchContext, string fieldName) => this.GetTypes(searchContext).SelectMany(x => x.Fields).Where(x => x.Name == fieldName);
Example #24
0
        /// <inheritdoc />
        /// <summary>
        /// See <see cref="https://en.wikipedia.org/wiki/Tic-tac-toe#Strategy"/>
        /// </summary>
        public TicTacToeMove Act(SearchContext <object, TicTacToeState, TicTacToeMove, object, TicTacToeMove> context, TicTacToeState state)
        {
            var possibilities = TicTacToeMoveGenerator.AllEmptyPositions(state);
            var myID          = state.ActivePlayerID;
            var oppID         = TicTacToeState.SwitchPlayerID(myID);
            var oppMove       = oppID == TicTacToeState.PLAYER_ONE_ID ? TicTacToeState.PLAYER_ONE_MOVE : TicTacToeState.PLAYER_TWO_MOVE;
            var openCorners   = possibilities.Where(i => CornerPositions.Contains(i)).ToList();
            var openEdges     = possibilities.Where(i => EdgePositions.Contains(i)).ToList();

            #region Opening and response

            // Opening move to corner or middle position
            if (possibilities.Count == 9)
            {
                //return new TicTacToeMove(CornerPositions.RandomElementOrDefault(), myID);
                return(new TicTacToeMove(4, myID));
            }

            // Second turn
            if (possibilities.Count == 8)
            {
                // If the middle position was opened with, play corner
                if (!possibilities.Contains(4))
                {
                    return(new TicTacToeMove(CornerPositions.RandomElementOrDefault(), myID));
                }
                // If a corner or an edge was opened with, play middle
                return(new TicTacToeMove(4, myID));
            }

            #endregion

            #region 1. Win

            // Check for own winning moves
            var myWins = CheckWinningPositions(state, myID);
            // Take the win
            if (!myWins.IsNullOrEmpty())
            {
                return(new TicTacToeMove(myWins.RandomElementOrDefault(), myID));
            }

            #endregion

            #region 2. Block

            // Check for opponent's winning moves
            var oppWins = CheckWinningPositions(state, oppID);
            // Prevent the loss
            if (!oppWins.IsNullOrEmpty())
            {
                return(new TicTacToeMove(oppWins.RandomElementOrDefault(), myID));
            }

            #endregion

            #region 3. Fork

            // Check if we have any forks available
            var forks = CheckForks(state, myID);
            // Move to one of the available forks
            if (!forks.IsNullOrEmpty())
            {
                return(new TicTacToeMove(forks.RandomElementOrDefault(), myID));
            }

            #endregion

            #region 4. Blocking an opponent's fork

            // Check if the opponent has any forks available
            var oppForks = CheckForks(state, oppID);
            if (!oppForks.IsNullOrEmpty())
            {
                // If there is only one possible fork for the opponent, the player should block it.
                if (oppForks.Count == 1)
                {
                    return(new TicTacToeMove(oppForks[0], myID));
                }
                // Otherwise, the player should block any forks in any way that simultaneously allows them to create two in a row, as long as it doesn't result in them creating a fork.
                var threats             = CheckThreats(state, myID);
                var safeThreats         = threats.Where(i => !DoesThisThreatCreateAForkForOpponent(state, i, myID)).ToList();
                var safeBlockingThreats = safeThreats.Where(i => oppForks.Contains(i)).ToList();
                if (!safeBlockingThreats.IsNullOrEmpty())
                {
                    return(new TicTacToeMove(safeBlockingThreats.RandomElementOrDefault(), myID));
                }
                // Otherwise, the player should create a two in a row to force the opponent into defending, as long as it doesn't result in them creating a fork.
                if (!safeThreats.IsNullOrEmpty())
                {
                    return(new TicTacToeMove(safeThreats.RandomElementOrDefault(), myID));
                }
            }

            #endregion

            #region 5. Center

            // If middle is open, play it
            if (possibilities.Contains(4))
            {
                return(new TicTacToeMove(4, myID));
            }

            #endregion

            #region 6. Opposite corner

            // If the opponent is in a corner and the opposite corner is available, move there
            foreach (var cornerPosition in CornerPositions)
            {
                var oppositeCorner = OppositeCorner(cornerPosition);
                if (state.State[cornerPosition] == oppMove && openCorners.Contains(oppositeCorner))
                {
                    return(new TicTacToeMove(oppositeCorner, myID));
                }
            }

            #endregion

            #region 7. Empty corner

            // If a corner is open, play it
            if (!openCorners.IsNullOrEmpty())
            {
                return(new TicTacToeMove(openCorners.RandomElementOrDefault(), myID));
            }

            #endregion

            #region 8. Empty side

            // If an edge is open, play it
            if (!openEdges.IsNullOrEmpty())
            {
                return(new TicTacToeMove(openEdges.RandomElementOrDefault(), myID));
            }

            #endregion

            // Otherwise, act random
            var index          = rng.Next(possibilities.Count);
            var randomPosition = possibilities.ToArray()[index];
            // Return a random position to play for the active player
            return(new TicTacToeMove(randomPosition, myID));
        }
Example #25
0
 public IEnumerable <Method> FindMethods(SearchContext searchContext, string regexPattern) => this.GetTypes(searchContext).SelectMany(x => x.Methods).Where(x => Regex.IsMatch(x.Name, regexPattern, RegexOptions.Singleline));
Example #26
0
        static IEnumerable <SearchItem> FetchTextures(Type type, TextureDimension textureDimension, SearchContext context)
        {
            var userQuery = context.searchQuery;
            var providers = new[] { Search.SearchService.GetProvider("adb") };

            using (var query = Search.SearchService.CreateContext(providers, $"t:{type.Name} {userQuery}", context.options))
                using (var request = Search.SearchService.Request(query))
                {
                    foreach (var r in request)
                    {
                        if (r == null)
                        {
                            yield return(null);
                        }
                        else
                        {
                            r.provider = Search.SearchUtils.CreateGroupProvider(r.provider, "Texture 2D", 0, true);
                            yield return(r);
                        }
                    }
                }

            if (type != typeof(RenderTexture))
            {
                using (var query = Search.SearchService.CreateContext(providers, $"t:{nameof(RenderTexture)} {userQuery}", context.options))
                    using (var request = Search.SearchService.Request(query))
                    {
                        foreach (var r in request)
                        {
                            if (r == null)
                            {
                                continue;
                            }
                            var rt = r.ToObject <RenderTexture>();
                            if (rt.dimension == textureDimension)
                            {
                                r.provider = Search.SearchUtils.CreateGroupProvider(r.provider, "Render Texture", 0, true);
                                yield return(r);
                            }
                        }
                    }
            }
        }
Example #27
0
 public IEnumerable <AttributedMethod> FindMethodsByAttribute(SearchContext searchContext, Type attributeType) => this.FindMethodsByAttribute(searchContext, attributeType.FullName);
Example #28
0
 private static void TrackSelection(SearchItem item, SearchContext context)
 {
     EditorGUIUtility.systemCopyBuffer = item.id;
 }
Example #29
0
 public IEnumerable <Method> FindMethodsByName(SearchContext searchContext, string methodName, int parameterCount) => this.GetTypes(searchContext).SelectMany(x => x.GetMethods(methodName, parameterCount, false));
Example #30
0
        public static IEnumerable <FindResult> Search(SearchContext context, SearchProvider provider, FindOptions options)
        {
            var searchQuery = context.searchQuery;

            if (string.IsNullOrEmpty(searchQuery) || searchQuery.Length < 2)
            {
                yield break;
            }

            #if DEBUG_FIND_PROVIDER
            using (new DebugTimer($"Searching {s_FileCount} files with <i>{searchQuery}</i> ({options})"))
            #endif
            {
                var roots      = GetRoots(options);
                var results    = new ConcurrentBag <FindResult>();
                var searchTask = Task.Run(() =>
                {
                    Regex globRx   = null, rxm = null;
                    var validRx    = options.HasFlag(FindOptions.Regex) && ParseRx(searchQuery, out rxm);
                    var validGlob  = options.HasFlag(FindOptions.Glob) && ParseGlob(searchQuery, out globRx);
                    var validWords = options.HasFlag(FindOptions.Words);
                    var validFuzzy = options.HasFlag(FindOptions.Fuzzy);
                    Parallel.ForEach(roots, r =>
                    {
                        var isPackage = options.HasFlag(FindOptions.Packages) && r.StartsWith("Packages/", StringComparison.Ordinal);
                        if (!options.HasFlag(FindOptions.Packages) && isPackage)
                        {
                            return;
                        }

                        if (!s_RootFilePaths.TryGetValue(r, out var files))
                        {
                            files = new ConcurrentDictionary <string, byte>(Directory.EnumerateFiles(r, "*.meta", SearchOption.AllDirectories)
                                                                            .Select(p => p.Substring(0, p.Length - 5).Replace("\\", "/")).ToDictionary(p => p, p => (byte)0));
                            s_RootFilePaths.TryAdd(r, files);
                            #if DEBUG_FIND_PROVIDER
                            s_FileCount += files.Length;
                            #endif
                        }

                        Parallel.ForEach(files, kvp =>
                        {
                            try
                            {
                                var f           = kvp.Key;
                                long fuzzyScore = 0;
                                int score       = isPackage ? (int)FindOptions.Packages : 0;
                                if (validWords && SearchUtils.MatchSearchGroups(context, f, true))
                                {
                                    results.Add(new FindResult(f, score | (int)FindOptions.Words));
                                }
                                else if (validRx && rxm.IsMatch(f))
                                {
                                    results.Add(new FindResult(f, score | (int)FindOptions.Regex));
                                }
                                else if (validGlob && globRx.IsMatch(f))
                                {
                                    results.Add(new FindResult(f, score | (int)FindOptions.Glob));
                                }
                                else if (validFuzzy && FuzzySearch.FuzzyMatch(searchQuery, f, ref fuzzyScore))
                                {
                                    results.Add(new FindResult(f, ComputeFuzzyScore(score, fuzzyScore)));
                                }
                            }
                            catch
                            {
                                // ignore
                            }
                        });
                    });
                });

                while (results.Count > 0 || !searchTask.Wait(1) || results.Count > 0)
                {
                    if (results.TryTake(out var e))
                    {
                        yield return(e);
                    }
                }
            }
        }
Example #31
0
 public IEnumerable <Method> FindMethodsByName(SearchContext searchContext, string methodName) => this.GetTypes(searchContext).SelectMany(x => x.GetMethods(methodName, 0));
Example #32
0
        public async Task <SearchResponse> SearchAsync(
            string query,
            int skip = 0,
            int take = 20,
            bool includePrerelease = true,
            bool includeSemVer2    = true,
            string packageType     = null,
            string framework       = null,
            CancellationToken cancellationToken = default)
        {
            var searchText = BuildSeachQuery(query, packageType, framework);
            var filter     = BuildSearchFilter(includePrerelease, includeSemVer2);
            var parameters = new SearchParameters
            {
                IncludeTotalResultCount = true,
                QueryType = QueryType.Full,
                Skip      = skip,
                Top       = take,
                Filter    = filter
            };

            var response = await _searchClient.Documents.SearchAsync <PackageDocument>(searchText, parameters, cancellationToken : cancellationToken);

            var results = new List <SearchResult>();

            foreach (var result in response.Results)
            {
                var document = result.Document;
                var versions = new List <SearchResultVersion>();

                if (document.Versions.Length != document.VersionDownloads.Length)
                {
                    throw new InvalidOperationException($"Invalid document {document.Key} with mismatched versions");
                }

                for (var i = 0; i < document.Versions.Length; i++)
                {
                    var downloads = long.Parse(document.VersionDownloads[i]);
                    var version   = NuGetVersion.Parse(document.Versions[i]);
                    var url       = _url.GetRegistrationLeafUrl(document.Id, version);

                    versions.Add(new SearchResultVersion(url, version, downloads));
                }

                results.Add(new SearchResult(
                                document.Id,
                                NuGetVersion.Parse(document.Version),
                                document.Description,
                                document.Authors,
                                document.IconUrl,
                                document.LicenseUrl,
                                document.ProjectUrl,
                                _url.GetRegistrationIndexUrl(document.Id),
                                document.Summary,
                                document.Tags,
                                document.Title,
                                document.TotalDownloads,
                                versions));
            }

            return(new SearchResponse(
                       response.Count.Value,
                       results,
                       SearchContext.Default(_url.GetPackageMetadataResourceUrl())));
        }
Example #33
0
 public IEnumerable <BuilderType> GetTypes(SearchContext searchContext) => this.GetTypesInternal(searchContext).Select(x => new BuilderType(this, x)).ToArray();
Example #34
0
 public GetRandomCharitiesRequestHandler(SearchContext context, IMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
Example #35
0
 public IEnumerable <BuilderType> GetTypesInNamespace(SearchContext searchContext, string namespaceName) => this.GetTypes(searchContext).Where(x => x.Namespace == namespaceName);
        public static IEnumerable <SearchDocument> Search(string searchQuery, IEnumerable <string> roots, SearchContext context, SearchProvider provider, FindOptions options)
        {
            var query = s_QueryEngine.ParseQuery(searchQuery, new FindFilesQueryFactory(args =>
            {
                {
                    if (args.op == SearchIndexOperator.None)
                    {
                        return(FindFilesQuery.EvalResult.None);
                    }
                    else if (args.op == SearchIndexOperator.Equal)
                    {
                        options &= ~(FindOptions.Fuzzy | FindOptions.Glob | FindOptions.Regex);
                        options |= FindOptions.Exact;
                    }

                    IEnumerable <SearchDocument> subset = args.andSet ??
                                                          roots.SelectMany(root => GetRootPaths(root, options));

                    IEnumerable <SearchDocument> results = Enumerable.Empty <SearchDocument>();
                    if (args.name == null && args.value is string word && word.Length > 0)
                    {
                        results = SearchWord(args.exclude, word, options, subset);
                    }

                    if (args.orSet != null)
                    {
                        results = results.Concat(args.orSet);
                    }

                    return(FindFilesQuery.EvalResult.Combined(results));
                }
            }));

            if (!query.valid)
            {
                context.AddSearchQueryErrors(query.errors.Select(e => new SearchQueryError(e, context, provider)));
                yield break;
            }

            if (query.HasToggle("packages"))
            {
                options |= FindOptions.Packages;
            }
            roots = roots ?? GetRoots(options);

            var results    = new ConcurrentBag <SearchDocument>();
            var searchTask = Task.Run(() =>
            {
                foreach (var r in query.Apply(null))
                {
                    results.Add(r);
                }
            });

            while (results.Count > 0 || !searchTask.Wait(1) || results.Count > 0)
            {
                while (results.TryTake(out var e))
                {
                    yield return(e);
                }

                if (searchTask.IsFaulted || searchTask.IsCanceled)
                {
                    yield break;
                }
                yield return(SearchDocument.invalid);
            }
        }
Example #37
0
 public IEnumerable <BuilderType> FindTypes(SearchContext searchContext, string regexPattern) =>
 this.GetTypesInternal(searchContext)
 .Where(x => Regex.IsMatch(x.FullName, regexPattern, RegexOptions.Singleline))
 .Select(x => new BuilderType(this, x));
Example #38
0
        /// <inheritdoc />
        public SabberStoneAction Act(SabberStoneState state)
        {
            var timer     = Stopwatch.StartNew();
            var stateCopy = (SabberStoneState)state.Copy();

            if (_debug)
            {
                Console.WriteLine();
            }
            if (_debug)
            {
                Console.WriteLine(Name());
            }
            if (_debug)
            {
                Console.WriteLine($"Starting an LSI search in turn {(stateCopy.Game.Turn + 1) / 2}");
            }

            // Create a new LSI search
            var search = new LSI <List <SabberStoneAction>, SabberStoneState, SabberStoneAction, object, TreeSearchNode <SabberStoneState, SabberStoneAction>, OddmentTable <SabberStonePlayerTask> >(
                SideInformationStrategy,
                SamplingStrategy,
                Playout,
                Evaluation,
                GameLogic,
                BudgetEstimationStrategy
                );

            // Reset the solutions collection
            EnsembleSolutions = new List <SabberStoneAction>();

            // Create a SearchContext that just holds the current state as Source and the Search.
            var context = SearchContext <List <SabberStoneAction>, SabberStoneState, SabberStoneAction, object, SabberStoneAction> .Context(EnsembleSolutions, stateCopy, null, null, search, null);

            // The Playout strategy will call the Goal strategy from the context, so we set it here
            context.Goal = Goal;

            // Execute the search
            Ensemble.EnsembleSearch(context, Searcher.Search, EnsembleSize);
            SamplesSpent = EnsembleSolutions.Sum(i => i.BudgetUsed);

            // Determine a solution
            var solution = Searcher.VoteForSolution(EnsembleSolutions, state);

            timer.Stop();
            if (_debug)
            {
                Console.WriteLine();
            }
            if (_debug)
            {
                Console.WriteLine($"LSI returned with solution: {solution}");
            }
            if (_debug)
            {
                Console.WriteLine($"My total calculation time was: {timer.ElapsedMilliseconds}ms");
            }

            // Check if the solution is a complete action.
            if (!solution.IsComplete())
            {
                // Otherwise add an End-Turn task before returning.
                solution.Tasks.Add((SabberStonePlayerTask)EndTurnTask.Any(Player));
            }

            // If we are estimating the budget by using the previous search's results, save these now
            if (BudgetEstimation == BudgetEstimationType.PreviousSearchAverage && BudgetEstimationStrategy is PreviousSearchAverageBudgetEstimationStrategy estimationStrategy)
            {
                estimationStrategy.PreviousSearchTime       = timer.ElapsedMilliseconds;
                estimationStrategy.PreviousSearchIterations = SamplesSpent;
            }

            if (_debug)
            {
                Console.WriteLine();
            }
            return(solution);
        }
Example #39
0
        public List <Main> GetCalls(SearchContext search)
        {
            IQueryable <Main> result = DbSet.AsQueryable();


            if (search.RecordId.GetValueOrDefault(0) > 0)
            {
                result = result.Where(x => x.MainId == search.RecordId)
                         .Include(type => type.OrderDetails)
                         .Include(type => type.OrderDetails.Select(p => p.Program))
                         .Include(type => type.User)
                         .Include(type => type.User.Vendor);

                foreach (Main call in result)
                {
                    foreach (OrderDetail detail in call.OrderDetails)
                    {
                        detail.Main = null;
                        if (detail.Program != null)
                        {
                            detail.Program.OrderDetails   = null;
                            detail.Program.PremiseType    = null;
                            detail.Program.ProgramVendors = null;
                            detail.Program.UnitOfMeasure  = null;
                            detail.Program.Utility        = null;
                            detail.Program.UtilityType    = null;
                            detail.Program.Vendor         = null;
                        }
                    }

                    if (call.User != null)
                    {
                        call.User.Office   = null;
                        call.User.UserType = null;
                        call.User.Mains    = null;
                        call.User.UserLogs = null;

                        if (call.User.Vendor != null)
                        {
                            call.User.Vendor.Offices        = null;
                            call.User.Vendor.ProgramVendors = null;
                            call.User.Vendor.Users          = null;
                        }

                        if (call.User.Office != null)
                        {
                            call.User.Office.SalesChannel = null;
                        }
                    }
                }

                return(result.ToList());
            }

            if (search.StartDate.HasValue && search.EndDate.HasValue)
            {
                result = result.Where(x => x.CallDateTime >= search.StartDate.Value && x.CallDateTime < search.EndDate.Value);
            }

            if (search.Disposition != null)
            {
                result = result.Where(x => x.Concern == search.Disposition.Concern);
            }

            if (!String.IsNullOrEmpty(search.TpvAgentId))
            {
                result = result.Where(x => x.TpvAgentId == search.TpvAgentId);
            }

            if (!String.IsNullOrEmpty(search.VendorAgentId))
            {
                result = result.Where(x => x.User.AgentId == search.VendorAgentId);
            }

            if (!String.IsNullOrEmpty(search.PhoneNumber))
            {
                result = result.Where(x => x.Btn == search.PhoneNumber);
            }

            if (search.AccountNumber != "")
            {
                result = result.Where(x => x.OrderDetails.Any(d => d.AccountNumber == search.AccountNumber));
            }

            if (search.VendorId.HasValue)
            {
                result = result.Where(x => x.User.VendorId == search.VendorId.Value);
            }

            if (search.OfficeId.HasValue)
            {
                result = result.Where(x => x.User.OfficeId == search.OfficeId.Value);
            }

            result = result.Include(type => type.OrderDetails);
            result = result.Include(type => type.OrderDetails.Select(p => p.Program));
            result = result.Include(type => type.User);
            result = result.Include(type => type.User.Vendor);

            //TODO: Return custom object instead of model.
            foreach (Main call in result)
            {
                foreach (OrderDetail detail in call.OrderDetails)
                {
                    detail.Main = null;
                    if (detail.Program != null)
                    {
                        detail.Program.OrderDetails   = null;
                        detail.Program.PremiseType    = null;
                        detail.Program.ProgramVendors = null;
                        detail.Program.UnitOfMeasure  = null;
                        detail.Program.Utility        = null;
                        detail.Program.UtilityType    = null;
                        detail.Program.Vendor         = null;
                    }
                }

                if (call.User != null)
                {
                    call.User.Office   = null;
                    call.User.UserType = null;
                    call.User.Mains    = null;
                    call.User.UserLogs = null;

                    if (call.User.Vendor != null)
                    {
                        call.User.Vendor.Offices        = null;
                        call.User.Vendor.ProgramVendors = null;
                        call.User.Vendor.Users          = null;
                    }

                    if (call.User.Office != null)
                    {
                        call.User.Office.SalesChannel = null;
                    }
                }
            }

            return(result.Take(500).ToList());
        }
Example #40
0
 public CategoryRepository(SearchContext context)
 {
     this.db = context;
 }
Example #41
0
 private SearchContext getSearchContext(String searchValue)
 {
     SearchContext context = new SearchContext();
     context.provider = null;
     context.code = null;
     context.value = searchValue;
     // get searchtype and value
     Match regMatch = Regex.Match(context.value, "(?i)(?:([a-z]{1,2})\\s+)?(.*)");
     if (regMatch.Groups[1] != null) {
         context.code = regMatch.Groups[1].Value;
         context.value = regMatch.Groups[2].Value;
     }
     // get provider code
     if (this.ApplicationSettings.IdentCodes.ContainsKey(context.code)) {
         String providerFullname = this.ApplicationSettings.IdentCodes[context.code];
         context.provider = this.getProvider(providerFullname);
     }
     //
     return context;
 }