當前位置: 首頁>>代碼示例>>Python>>正文


Python typing.DefaultDict方法代碼示例

本文整理匯總了Python中typing.DefaultDict方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.DefaultDict方法的具體用法?Python typing.DefaultDict怎麽用?Python typing.DefaultDict使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在typing的用法示例。


在下文中一共展示了typing.DefaultDict方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def __init__(self, name: str, channel_service, peer_id, channel_name, store_identity):
        self.__channel_service: ChannelService = channel_service
        self.__channel_name = channel_name
        self.__pre_validate_strategy = self.__pre_validate
        self.__peer_id = peer_id

        self.__tx_queue = AgingCache(max_age_seconds=conf.MAX_TX_QUEUE_AGING_SECONDS,
                                     default_item_status=TransactionStatusInQueue.normal)
        self.blockchain = BlockChain(channel_name, store_identity, self)
        self.__peer_type = None
        self.__consensus_algorithm = None
        self.candidate_blocks = CandidateBlocks(self.blockchain)
        self.__block_height_sync_bad_targets = {}
        self.__block_height_sync_lock = threading.Lock()
        self.__block_height_thread_pool = ThreadPoolExecutor(1, 'BlockHeightSyncThread')
        self.__block_height_future: Future = None
        self.__precommit_block: Block = None
        self.set_peer_type(loopchain_pb2.PEER)
        self.name = name
        self.__service_status = status_code.Service.online

        # old_block_hashes[height][new_block_hash] = old_block_hash
        self.__old_block_hashes: DefaultDict[int, Dict[Hash32, Hash32]] = defaultdict(dict)
        self.epoch: Epoch = None 
開發者ID:icon-project,項目名稱:loopchain,代碼行數:26,代碼來源:block_manager.py

示例2: _busiest_week

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def _busiest_week(feed: Feed) -> Dict[datetime.date, FrozenSet[str]]:
    service_ids_by_date = _service_ids_by_date(feed)
    trip_counts_by_date = _trip_counts_by_date(feed)

    weekly_trip_counts: DefaultDict[Week, int] = defaultdict(int)
    weekly_dates: DefaultDict[Week, Set[datetime.date]] = defaultdict(set)
    for date in service_ids_by_date.keys():
        key = Week.withdate(date)
        weekly_trip_counts[key] += trip_counts_by_date[date]
        weekly_dates[key].add(date)

    def max_by(kv: Tuple[Week, int]) -> Tuple[int, int]:
        week, count = kv
        return count, -week.toordinal()

    week, _ = max(weekly_trip_counts.items(), key=max_by)
    dates = sorted(weekly_dates[week])

    return {date: service_ids_by_date[date] for date in dates} 
開發者ID:remix,項目名稱:partridge,代碼行數:21,代碼來源:readers.py

示例3: _get_table_cells

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def _get_table_cells(table: Table) -> DefaultDict[Cell, List[Sentence]]:
    """Cache table cells and the cells' sentences.

    This function significantly improves the speed of `get_row_ngrams`
    primarily by reducing the number of queries that are made (which were
    previously the bottleneck. Rather than taking a single mention, then its
    sentence, then its table, then all the cells in the table, then all the
    sentences in each cell, and performing operations on that series of
    queries, this performs a single query for all the sentences in a table and
    returns all of the cells and the cells sentences directly.

    :param table: the Table object to cache.
    :return: an iterator of (Cell, [Sentence._asdict(), ...]) tuples.
    """
    sent_map: DefaultDict[Cell, List[Sentence]] = defaultdict(list)
    for sent in table.sentences:
        sent_map[sent.cell].append(sent)
    return sent_map 
開發者ID:HazyResearch,項目名稱:fonduer,代碼行數:20,代碼來源:tabular.py

示例4: load_parents

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def load_parents() -> DefaultDict[str, Set[str]]:
    ''' Generates a dictionary with child to parent mapping. '''
    def recursive_parse(parents: DefaultDict[str, Set[str]], node: Any) -> None:
        name = node['LabelName']

        if 'Subcategory' in node:
            for child in node['Subcategory']:
                child_name = child['LabelName']

                if name != '/m/0bl9f':
                    parents[child_name].add(name)
                    parents[child_name].update(parents[name])

                recursive_parse(parents, child)

    with open('../data/challenge-2019-label500-hierarchy.json') as f:
        hierarchy = json.load(f)

    parents: DefaultDict[str, Set[str]] = defaultdict(set)
    recursive_parse(parents, hierarchy)

    return parents 
開發者ID:artyompal,項目名稱:tpu_models,代碼行數:24,代碼來源:gen_sub.py

示例5: _aggregate_losses

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def _aggregate_losses(self) -> Metrics:
        """Calculate the task specific loss, average micro loss and learning rate."""

        metric_dict = dict()

        # Log task specific loss
        self.running_losses: DefaultDict[str, float]
        self.running_counts: DefaultDict[str, float]
        for identifier in self.running_losses.keys():
            if self.running_counts[identifier] > 0:
                metric_dict[identifier] = (
                    self.running_losses[identifier] / self.running_counts[identifier]
                )

        # Calculate average micro loss
        total_loss = sum(self.running_losses.values())
        total_count = sum(self.running_counts.values())
        if total_count > 0:
            metric_dict["model/all/train/loss"] = total_loss / total_count

        # Log the learning rate
        metric_dict["model/all/train/lr"] = self.optimizer.param_groups[0]["lr"]

        return metric_dict 
開發者ID:snorkel-team,項目名稱:snorkel,代碼行數:26,代碼來源:trainer.py

示例6: get_borg_eval_gist

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def get_borg_eval_gist(self, pr: Dict[str, Any]) -> Optional[Dict[str, Set[str]]]:
        packages_per_system: DefaultDict[str, Set[str]] = defaultdict(set)
        statuses = self.get(pr["statuses_url"])
        for status in statuses:
            url = status.get("target_url", "")
            if (
                status["description"] == "^.^!"
                and status["creator"]["login"] == "ofborg[bot]"
                and url != ""
            ):
                url = urllib.parse.urlparse(url)
                raw_gist_url = (
                    f"https://gist.githubusercontent.com/GrahamcOfBorg{url.path}/raw/"
                )
                for line in urllib.request.urlopen(raw_gist_url):
                    if line == b"":
                        break
                    system, attribute = line.decode("utf-8").split()
                    packages_per_system[system].add(attribute)
                return packages_per_system
        return None 
開發者ID:Mic92,項目名稱:nixpkgs-review,代碼行數:23,代碼來源:github.py

示例7: test_defaultdict_raise_error

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def test_defaultdict_raise_error():
    elem = collections.defaultdict(int)
    elem[5] = [1, 2, 3]

    validator = type_validator()

    attr = MagicMock()
    attr.name = "foo"
    attr.type = DefaultDict[int, List[str]]

    with pytest.raises(ValueError) as error:
        validator(None, attr, elem)

    assert (
        "<foo must be typing.DefaultDict[int, typing.List[str]] "
        "(got 1 that is a {}) in [1, 2, 3] in "
        "defaultdict({}, {{5: [1, 2, 3]}})>"
    ).format(int, int) == repr(error.value) 
開發者ID:bloomberg,項目名稱:attrs-strict,代碼行數:20,代碼來源:test_dict.py

示例8: parameter_count

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def parameter_count(model: nn.Module) -> typing.DefaultDict[str, int]:
    """
    Count parameters of a model and its submodules.

    Args:
        model: a torch module

    Returns:
        dict (str-> int): the key is either a parameter name or a module name.
            The value is the number of elements in the parameter, or in all
            parameters of the module. The key "" corresponds to the total
            number of parameters of the model.
    """
    r = defaultdict(int)
    for name, prm in model.named_parameters():
        size = prm.numel()
        name = name.split(".")
        for k in range(0, len(name) + 1):
            prefix = ".".join(name[:k])
            r[prefix] += size
    return r 
開發者ID:facebookresearch,項目名稱:fvcore,代碼行數:23,代碼來源:parameter_count.py

示例9: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def __init__(self, logger=None):
        self._user_token = None
        self._user_client = None
        self._bot_token = None
        self._bot_client = None
        self._verification_token = None
        self._executor = concurrent.futures.ThreadPoolExecutor()
        self.logger = logger or logging.getLogger("uqcsbot")
        self._handlers: DefaultDict[str, list] = collections.defaultdict(list)
        self._command_registry: DefaultDict[str, list] = collections.defaultdict(list)
        self._scheduler = AsyncIOScheduler()

        self.register_handler('message', self._handle_command)
        self.register_handler('hello', self._handle_hello)
        self.register_handler('goodbye', self._handle_goodbye)

        self.channels = ChannelWrapper(self)
        self.users = UsersWrapper(self) 
開發者ID:UQComputingSociety,項目名稱:uqcsbot,代碼行數:20,代碼來源:base.py

示例10: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def __init__(self, optimizer, all_players, params):
        super(LockedPlayersRule, self).__init__(optimizer, all_players, params)
        self.used_players = defaultdict(int)  # type: DefaultDict[Player, int]
        self.total_lineups = params.get('n')
        self.remaining_iteration = params.get('n') + 1 
開發者ID:DimaKudosh,項目名稱:pydfs-lineup-optimizer,代碼行數:7,代碼來源:rules.py

示例11: get_players_grouped_by_teams

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def get_players_grouped_by_teams(
        players: Iterable['Player'],
        for_teams: Optional[List[str]] = None,
        for_positions: Optional[List[str]] = None,
) -> DefaultDict[str, List['Player']]:
    players_by_teams = defaultdict(list)  # type: DefaultDict[str, List['Player']]
    for player in players:
        if for_teams is not None and player.team not in for_teams:
            continue
        if for_positions is not None and not list_intersection(player.positions, for_positions):
            continue
        players_by_teams[player.team].append(player)
    return players_by_teams 
開發者ID:DimaKudosh,項目名稱:pydfs-lineup-optimizer,代碼行數:15,代碼來源:utils.py

示例12: merge_dicts

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def merge_dicts(
    d1: DefaultDict[str, List[str]],
    d2: Union[DefaultDict[str, List[str]], Dict[str, List[str]]],
) -> DefaultDict[str, List[str]]:
    """
    Merge two `dict()` objects

    """
    for k, v in d2.items():
        d1[k].extend(v)
    return d1 
開發者ID:PUNCH-Cyber,項目名稱:stoq,代碼行數:13,代碼來源:__init__.py

示例13: get_downloads_by_category

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def get_downloads_by_category(*, category: str, name: str) -> List[Dict[str, Any]]:
    url = CATEGORIES_URLS[category].format(name)
    with requests_session() as session:
        response = session.get(url)
    response.raise_for_status()
    body = response.json()['data']

    yesterday = date.today() - timedelta(1)
    grouped: DefaultDict[str, DateList]
    grouped = defaultdict(lambda: DateList(start=yesterday - timedelta(30), end=yesterday))
    for line in body:
        category = line['category'].replace('.', '')
        grouped[category].add(date=line['date'], value=line['downloads'])

    result = []
    for category, dates in grouped.items():
        downloads = list(dates)
        if sum(downloads) == 0:
            continue
        result.append(dict(
            category=category,
            day=downloads[-1],
            week=sum(downloads[-7:]),
            month=sum(downloads),
            chart=make_chart(downloads[-28:], group=7),
        ))
    return result 
開發者ID:dephell,項目名稱:dephell,代碼行數:29,代碼來源:_downloads.py

示例14: attach_cli

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def attach_cli(self, args, sep: str = '_') -> Dict[str, Any]:
        data = defaultdict(dict)  # type: DefaultDict[str, Any]
        for name, value in args._get_kwargs():
            if value is None or value is False:
                continue
            parsed = name.split(sep, maxsplit=1)
            if len(parsed) == 1:
                data[name] = value
            else:
                # if old content isn't a dict, override it
                if not isinstance(data[parsed[0]], dict):
                    data[parsed[0]] = dict()
                data[parsed[0]][parsed[1]] = value
        self.attach(data)
        return dict(data) 
開發者ID:dephell,項目名稱:dephell,代碼行數:17,代碼來源:manager.py

示例15: attach_env_vars

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import DefaultDict [as 別名]
def attach_env_vars(self, *, env_vars: Dict[str, str] = None, sep: str = '_') -> dict:
        if env_vars is None:
            env_vars = dict(environ)
        data = defaultdict(dict)  # type: DefaultDict[str, Any]
        for name, value in env_vars.items():
            # drop templated part from name
            match = ENV_VAR_REX.fullmatch(name)
            if not match:
                continue
            name = match.groups()[0].lower()
            if name in ('env', 'config'):
                continue

            # convert value to the correct type
            try:
                value = tomlkit.parse('key={}'.format(value))['key']
            except TOMLKitError:
                pass

            # do the same as in `attach_cli`
            parsed = name.split(sep, maxsplit=1)
            if len(parsed) == 1:
                data[name] = value
            else:
                # if old content isn't a dict, override it
                if not isinstance(data[parsed[0]], dict):
                    data[parsed[0]] = dict()
                data[parsed[0]][parsed[1]] = value
        self.attach(data)
        return dict(data) 
開發者ID:dephell,項目名稱:dephell,代碼行數:32,代碼來源:manager.py


注:本文中的typing.DefaultDict方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。