Python typing.Set() Examples
The following are 30
code examples of typing.Set().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing
, or try the search function
.
Example #1
Source File: filters.py From mutatest with MIT License | 7 votes |
def __init__(self, codes: Optional[Iterable[str]] = None): """Initialize the filter. Args: codes: An optional iterable of two-letter category codes for filtering. Optional to set at initialization of the class, can be set through properties. The codes property must be set prior to filtering. Only codes that are valid categories are added, others are discarded. Make sure you set appropriately as an iterable for single string values e.g., ``codes=("bn",)``; otherwise, the codes property will set as empty. """ # managed by class properties, no direct setters self._valid_categories = CATEGORIES # defined in transformers.py self._codes: Set[str] = set() # initialize through properties self.codes = set(codes) if codes else set()
Example #2
Source File: run_checks.py From OpenFermion-Cirq with Apache License 2.0 | 7 votes |
def topologically_sorted_checks_with_deps(checks: Iterable[check.Check] ) -> List[check.Check]: result = [] seen = set() # type: Set[check.Check] def handle(item: check.Check): if item in seen: return seen.add(item) # Dependencies first. for dep in item.dependencies: handle(dep) result.append(item) for e in checks: handle(e) return result
Example #3
Source File: test_app.py From quart with MIT License | 7 votes |
def test_add_url_rule_methods( methods: Set[str], required_methods: Set[str], automatic_options: bool ) -> None: app = Quart(__name__) def route() -> str: return "" route.methods = methods # type: ignore route.required_methods = required_methods # type: ignore non_func_methods = {"PATCH"} if not methods else None app.add_url_rule( "/", "end", route, methods=non_func_methods, provide_automatic_options=automatic_options ) result = {"PATCH"} if not methods else set() if automatic_options: result.add("OPTIONS") result.update(methods) result.update(required_methods) if "GET" in result: result.add("HEAD") assert app.url_map._rules_by_endpoint["end"][0].methods == result # type: ignore
Example #4
Source File: rules.py From pydfs-lineup-optimizer with MIT License | 6 votes |
def apply_for_iteration(self, solver, players_dict, result): current_lineup = self.lineups[self.current_iteration] unswappable_players = current_lineup.get_unswappable_players() remaining_positions = get_remaining_positions(self.optimizer.settings.positions, unswappable_players) # lock selected players for player in unswappable_players: solver.add_constraint([players_dict[player]], None, SolverSign.EQ, 1) # set remaining positions positions_combinations = set([tuple(sorted(player.positions)) for player in players_dict.keys() if len(player.positions) > 1]) positions = get_positions_for_optimizer(remaining_positions, positions_combinations) players_for_optimization = set() for position, places in positions.items(): players_with_position = [variable for player, variable in players_dict.items() if list_intersection(position, player.positions) and player not in unswappable_players] players_for_optimization.update(players_with_position) solver.add_constraint(players_with_position, None, SolverSign.GTE, places) # Set total players for optimization solver.add_constraint(players_for_optimization, None, SolverSign.EQ, len(remaining_positions)) # Exclude players with active games for player, variable in players_dict.items(): if player not in unswappable_players and player.is_game_started: solver.add_constraint([players_dict[player]], None, SolverSign.EQ, 0) self.current_iteration += 1
Example #5
Source File: factories.py From sslyze with GNU Affero General Public License v3.0 | 6 votes |
def create( server_info: ServerConnectivityInfo = ServerConnectivityInfoFactory.create(), scan_commands_results: Optional[ScanCommandResultsDict] = None, scan_commands_errors: Optional[ScanCommandErrorsDict] = None, ) -> ServerScanResult: final_results: ScanCommandResultsDict = ( scan_commands_results if scan_commands_results else {ScanCommand.TLS_COMPRESSION: CompressionScanResult(supports_compression=True)} ) final_errors: ScanCommandErrorsDict = scan_commands_errors if scan_commands_errors else {} scan_commands: Set[ScanCommandType] = set() for scan_cmd in final_results.keys(): typed_scan_cmd = cast(ScanCommandType, scan_cmd) scan_commands.add(typed_scan_cmd) for scan_cmd in final_errors.keys(): scan_commands.add(scan_cmd) return ServerScanResult( scan_commands_results=final_results, scan_commands_errors=final_errors, server_info=server_info, scan_commands=scan_commands, scan_commands_extra_arguments={}, )
Example #6
Source File: instruction_set.py From pyshgp with MIT License | 6 votes |
def set_type_library(self, type_library: PushTypeLibrary): """Set the type library attribute and return self. Parameters ---------- type_library PushTypeLibrary to set. Returns ------- InstructionSet A reference to the InstructionSet. """ self.type_library = type_library return self
Example #7
Source File: hints.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def update_text(self, matched: str, unmatched: str) -> None: """Set the text for the hint. Args: matched: The part of the text which was typed. unmatched: The part of the text which was not typed yet. """ if (config.cache['hints.uppercase'] and self._context.hint_mode in ['letter', 'word']): matched = html.escape(matched.upper()) unmatched = html.escape(unmatched.upper()) else: matched = html.escape(matched) unmatched = html.escape(unmatched) if matched: match_color = config.cache['colors.hints.match.fg'].name() self.setText('<font color="{}">{}</font>{}'.format( match_color, matched, unmatched)) else: self.setText(unmatched) self.adjustSize()
Example #8
Source File: docs_coverage_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def _api_rst_fullnames_per_section() -> List[List[str]]: result: List[List[str]] = [] section: List[str] = [] seen: Set[str] = set() with open(Path(__file__).parent / 'api.rst', mode='r') as f: for line in f.readlines(): if line.strip() == '.. autosummary::': if section: result.append(section) section = [] elif line.startswith(' openfermioncirq.'): fullname = line.strip() if fullname in seen: # coverage: ignore raise ValueError(f'{fullname} appears twice in api.rst') section.append(fullname) seen.add(fullname) if section: result.append(section) return result
Example #9
Source File: incremental_coverage.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def determine_ignored_lines(content: str) -> Set[int]: lines = content.split('\n') result = [] # type: List[int] i = 0 while i < len(lines): # Drop spacing, including internal spacing within the comment. joined_line = re.sub(r'\s+', '', lines[i]) if joined_line == EXPLICIT_OPT_OUT_COMMENT: # Ignore the rest of a block. end = naive_find_end_of_scope(lines, i) result.extend(range(i, end)) i = end elif joined_line.endswith(EXPLICIT_OPT_OUT_COMMENT): # Ignore a single line. result.append(i) i += 1 else: # Don't ignore. i += 1 # Line numbers start at 1, not 0. return {e + 1 for e in result}
Example #10
Source File: hints.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def hint(self, elems: _ElemsType) -> _HintStringsType: """Produce hint labels based on the html tags. Produce hint words based on the link text and random words from the words arg as fallback. Args: words: Words to use as fallback when no link text can be used. elems: The elements to get hint strings for. Return: A list of hint strings, in the same order as the elements. """ self.ensure_initialized() hints = [] used_hints = set() # type: typing.Set[str] words = iter(self.words) for elem in elems: hint = self.new_hint_for(elem, used_hints, words) if not hint: raise HintingError("Not enough words in the dictionary.") used_hints.add(hint) hints.append(hint) return hints
Example #11
Source File: test_converters.py From uplink with MIT License | 6 votes |
def test_methods(self, method, use_typing): List, Dict = converters.typing_._get_types(use_typing) # Verify with sequence converter = method(List[str]) assert isinstance(converter, converters.typing_.ListConverter) # Verify with mapping converter = method(Dict[str, str]) assert isinstance(converter, converters.typing_.DictConverter) # Verify with unsupported value converter = method(None) assert converter is None # Verify with unsupported type if use_typing: converter = method(typing.Set[str]) assert converter is None
Example #12
Source File: websettings.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def set_font_family(self, name: str, value: typing.Optional[str]) -> bool: """Set the given QWebSettings/QWebEngineSettings font family. With None (the default), QFont is used to get the default font for the family. Return: True if there was a change, False otherwise. """ self._assert_not_unset(value) family = self._FONT_FAMILIES[name] if value is None: font = QFont() font.setStyleHint(self._FONT_TO_QFONT[family]) value = font.defaultFamily() old_value = self._settings.fontFamily(family) self._settings.setFontFamily(family, value) return value != old_value
Example #13
Source File: test_app.py From quart with MIT License | 6 votes |
def test_add_url_rule_automatic_options( methods: Set[str], arg_automatic: Optional[bool], func_automatic: Optional[bool], expected_methods: Set[str], expected_automatic: bool, ) -> None: app = Quart(__name__) def route() -> str: return "" route.provide_automatic_options = func_automatic # type: ignore app.add_url_rule("/", "end", route, methods=methods, provide_automatic_options=arg_automatic) assert app.url_map._rules_by_endpoint["end"][0].methods == expected_methods # type: ignore assert ( app.url_map._rules_by_endpoint["end"][0].provide_automatic_options # type: ignore == expected_automatic )
Example #14
Source File: websettings.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def update_for_url(self, url: QUrl) -> typing.Set[str]: """Update settings customized for the given tab. Return: A set of settings which actually changed. """ qtutils.ensure_valid(url) changed_settings = set() for values in config.instance: if not values.opt.supports_pattern: continue value = values.get_for_url(url, fallback=False) changed = self._update_setting(values.opt.name, value) if changed: log.config.debug("Changed for {}: {} = {}".format( url.toDisplayString(), values.opt.name, value)) changed_settings.add(values.opt.name) return changed_settings
Example #15
Source File: utils.py From indy-anoncreds with Apache License 2.0 | 6 votes |
def toDictWithStrValues(d): if isNamedTuple(d): return toDictWithStrValues(d._asdict()) if not isinstance(d, Dict): return serializeToStr(d) result = OrderedDict() for key, value in d.items(): if isinstance(value, Dict): result[serializeToStr(key)] = toDictWithStrValues(value) elif isinstance(value, str): result[serializeToStr(key)] = serializeToStr(value) elif isNamedTuple(value): result[serializeToStr(key)] = toDictWithStrValues(value._asdict()) elif isinstance(value, Set): result[serializeToStr(key)] = {toDictWithStrValues(v) for v in value} elif isinstance(value, List): result[serializeToStr(key)] = [toDictWithStrValues(v) for v in value] elif value: result[serializeToStr(key)] = serializeToStr(value) return result
Example #16
Source File: utils.py From indy-anoncreds with Apache License 2.0 | 6 votes |
def fromDictWithStrValues(d): if not isinstance(d, Dict) and not isinstance(d, tuple): return deserializeFromStr(d) result = OrderedDict() for key, value in d.items(): if isinstance(value, Dict): result[deserializeFromStr(key)] = fromDictWithStrValues(value) elif isinstance(value, str): result[deserializeFromStr(key)] = deserializeFromStr(value) elif isinstance(value, Set): result[deserializeFromStr(key)] = {fromDictWithStrValues(v) for v in value} elif isinstance(value, List): result[deserializeFromStr(key)] = [fromDictWithStrValues(v) for v in value] elif value: result[deserializeFromStr(key)] = deserializeFromStr(value) return result
Example #17
Source File: adblock.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def _read_hosts_file(self, filename: str, target: typing.Set[str]) -> bool: """Read hosts from the given filename. Args: filename: The file to read. target: The set to store the hosts in. Return: True if a read was attempted, False otherwise """ if not os.path.exists(filename): return False try: with open(filename, 'rb') as f: for line in f: target |= self._read_hosts_line(line) except (OSError, UnicodeDecodeError): logger.exception("Failed to read host blocklist!") return True
Example #18
Source File: migrate_script.py From typeshed with Apache License 2.0 | 6 votes |
def get_top_imported_names(file: str) -> Set[str]: """Collect names imported in given file. We only collect top-level names, i.e. `from foo.bar import baz` will only add `foo` to the list. """ if not file.endswith(".pyi"): return set() with open(os.path.join(file), "rb") as f: content = f.read() parsed = ast.parse(content) top_imported = set() for node in ast.walk(parsed): if isinstance(node, ast.Import): for name in node.names: top_imported.add(name.name.split('.')[0]) elif isinstance(node, ast.ImportFrom): if node.level > 0: # Relative imports always refer to the current package. continue assert node.module top_imported.add(node.module.split('.')[0]) return top_imported
Example #19
Source File: filters.py From mutatest with MIT License | 6 votes |
def filter( # type: ignore self, loc_idxs: Set[LocIndex], source_file: Union[str, Path], invert: bool = False, resolve_source: bool = True, ) -> Set[LocIndex]: """Filter based on coverage measured file. This adds the source_file argument to the filter abstract method because the coverage file holds multiple measured-files, and the ``LocIndex`` object does not have a source file attribute. The choice is that the coverage file can be set and read once for the class instance, and any valid measured file can be used in the filter. Args: loc_idxs: location index set of targets source_file: source file that is measured by the coverage file invert: flag for inverted filter using NOT resolve_source: flag for using resolved source_file vs. direct str, default True. This exists mostly for testing purposes to access mocked entries in the fake coverage files. Returns: Filtered set of location index set """ measured_file = str(Path(source_file).resolve()) if resolve_source else str(source_file) covered_lines = self.coverage_data.lines(measured_file) or list() if invert: return {loc for loc in loc_idxs if loc.lineno not in covered_lines} return {loc for loc in loc_idxs if loc.lineno in covered_lines}
Example #20
Source File: websettings.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def set_font_size(self, name: str, value: int) -> bool: """Set the given QWebSettings/QWebEngineSettings font size. Return: True if there was a change, False otherwise. """ self._assert_not_unset(value) family = self._FONT_SIZES[name] old_value = self._settings.fontSize(family) self._settings.setFontSize(family, value) return old_value != value
Example #21
Source File: scanner.py From sslyze with GNU Affero General Public License v3.0 | 5 votes |
def all_queued_scan_jobs(self) -> Set[Future]: all_queued_scan_jobs = set() for scan_jobs in self.queued_scan_jobs_per_scan_command.values(): all_queued_scan_jobs.update(scan_jobs) return all_queued_scan_jobs
Example #22
Source File: mock_plugins.py From sslyze with GNU Affero General Public License v3.0 | 5 votes |
def get_all_scan_commands() -> Set[ScanCommandForTestsType]: return set(_IMPLEMENTATION_CLASSES.keys())
Example #23
Source File: log.py From qutebrowser with GNU General Public License v3.0 | 5 votes |
def __init__(self, names: typing.Set[str], *, negated: bool = False, only_debug: bool = True) -> None: super().__init__() self.names = names self.negated = negated self.only_debug = only_debug
Example #24
Source File: instruction.py From dcc with Apache License 2.0 | 5 votes |
def __init__(self): self.value: Value = None self.operands: List[Value] = [] self.parent = None # bb self.offset = -1 # current instruction's offset, used by branch instruction self.next_offset = -1 # next instruction's offset, used to get next basicblock self.dvm_instr = None # 活跃信息,如果一个引用类型变量在live_in但不在live_out,需要释放引用 self.live_in: Set[Value] = set() self.live_out: Set[Value] = set()
Example #25
Source File: models.py From bloop with MIT License | 5 votes |
def setdefault(obj, field, default): """Set an object's field to default if it doesn't have a value""" setattr(obj, field, getattr(obj, field, default))
Example #26
Source File: utils.py From pydfs-lineup-optimizer with MIT License | 5 votes |
def get_positions_for_optimizer( positions_list: List[LineupPosition], multi_positions_combinations: Optional[Set[Tuple[str, ...]]] = None ) -> Dict[Tuple[str, ...], int]: """ Convert positions list into dict for using in optimizer. """ positions = {} positions_counter = Counter([tuple(sorted(p.positions)) for p in positions_list]) for key in positions_counter.keys(): min_value = positions_counter[key] + len(list(filter( lambda p: len(p.positions) < len(key) and list_intersection(key, p.positions), positions_list ))) positions[key] = min_value if not multi_positions_combinations: return positions # Create list of required combinations for consistency of multi-positions for i in range(2, len(multi_positions_combinations)): total_combinations = len(multi_positions_combinations) for positions_tuple in combinations(multi_positions_combinations, i): flatten_positions = tuple(sorted(set(chain.from_iterable(positions_tuple)))) multi_positions_combinations.add(flatten_positions) if total_combinations == len(multi_positions_combinations): break multi_positions_combinations.update(positions.keys()) for i in range(2, len(positions)): for positions_tuple in combinations(positions_counter.keys(), i): flatten_positions = tuple(sorted(set(chain.from_iterable(positions_tuple)))) if flatten_positions in positions or flatten_positions not in multi_positions_combinations: continue min_value = sum(positions[pos] for pos in positions_tuple) positions[flatten_positions] = min_value return positions
Example #27
Source File: rules.py From pydfs-lineup-optimizer with MIT License | 5 votes |
def _create_constraints( self, solver: Solver, players_dict: Dict[Player, Any], ): players_in_stack = defaultdict(set) # type: Dict[Player, Set[Any]] for stack in self.stacks: combinations_variables = {} for group in stack.groups: group_name = ('stack_%s_%s' % (stack.uuid, group.uuid)).replace('-', '_') sub_groups = group.get_all_players_groups() if group.max_exposure is not None and group.max_exposure <= self.used_groups[group_name] / self.total_lineups: max_group = sorted(sub_groups, key=lambda t: t[1])[0] variables = [players_dict[p] for p in max_group[0]] solver.add_constraint(variables, None, SolverSign.LTE, max_group[1] - 1) continue if any(sub_group[1] is not None for sub_group in sub_groups): solver_variable = solver.add_variable(group_name) combinations_variables[group_name] = solver_variable for group_players, group_min, group_max in sub_groups: variables = [players_dict[p] for p in group_players] if group_min is not None: if not stack.can_intersect: for player in group_players: players_in_stack[player].add(solver_variable) solver.add_constraint(variables, None, SolverSign.GTE, group_min * solver_variable) if group_max is not None: solver.add_constraint(variables, None, SolverSign.LTE, group_max) if combinations_variables: solver.add_constraint(combinations_variables.values(), None, SolverSign.GTE, 1) for player, stacks_vars in players_in_stack.items(): if len(stacks_vars) > 1: solver.add_constraint(stacks_vars, None, SolverSign.LTE, 1)
Example #28
Source File: lineup_optimizer.py From pydfs-lineup-optimizer with MIT License | 5 votes |
def set_deviation(self, min_deviation: float, max_deviation: float): """ Set deviation ranges for randomness mode """ self._min_deviation = min_deviation self._max_deviation = max_deviation
Example #29
Source File: lineup_optimizer.py From pydfs-lineup-optimizer with MIT License | 5 votes |
def __init__(self, settings: Type[BaseSettings], solver: Type[Solver] = PuLPSolver): self._settings = settings() self._csv_importer = None # type: Optional[Type[CSVImporter]] self._rules = BASE_RULES.copy() # type: Set[Type[OptimizerRule]] self._players = [] # type: List[Player] self._lineup = [] # type: List[Player] self._available_positions = frozenset(chain.from_iterable( position.positions for position in self._settings.positions)) self._removed_players = [] # type: List[Player] self._search_threshold = 0.8 self._min_deviation = 0.06 self._max_deviation = 0.12 self.players_from_one_team = {} # type: Dict[str, int] self.players_with_same_position = {} # type: Dict[str, int] self.min_salary_cap = None # type: Optional[float] self.max_repeating_players = None # type: Optional[int] self._solver_class = solver self.max_projected_ownership = None # type: Optional[float] self.min_projected_ownership = None # type: Optional[float] self.opposing_teams_position_restriction = None # type: Optional[Tuple[List[str], List[str]]] self.spacing_positions = None # type: Optional[List[str]] self.spacing = None # type: Optional[int] self.teams_exposures = None # type: Optional[Dict[str, float]] self.team_stacks_for_positions = None # type: Optional[List[str]] self.same_team_restrict_positions = None # type: Optional[Tuple[Tuple[str, str], ...]] self.opposing_team_force_positions = None # type: Optional[Tuple[Tuple[str, str], ...]] self.total_teams = None # type: Optional[int] self.stacks = [] # type: List[BaseStack] self.min_starters = None # type: Optional[int]
Example #30
Source File: allennlp_file_utils.py From ConvLab with MIT License | 5 votes |
def read_set_from_file(filename: str) -> Set[str]: """ Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. """ collection = set() with open(filename, 'r') as file_: for line in file_: collection.add(line.rstrip()) return collection