repository_name
stringlengths
7
107
function_path
stringlengths
4
190
function_identifier
stringlengths
1
236
language
stringclasses
1 value
function
stringlengths
9
647k
docstring
stringlengths
5
488k
function_url
stringlengths
71
285
context
stringlengths
0
2.51M
license
stringclasses
5 values
fangshi1991/zipline_chstock
zipline/pipeline/engine.py
SimplePipelineEngine._mask_and_dates_for_term
python
def _mask_and_dates_for_term(self, term, workspace, graph, dates): mask = term.mask offset = graph.extra_rows[mask] - graph.extra_rows[term] return workspace[mask][offset:], dates[offset:]
Load mask and mask row labels for term.
https://github.com/fangshi1991/zipline_chstock/blob/7911642780fa57f92e1705b9c0acaeb837b3d98f/zipline/pipeline/engine.py#L240-L246
from abc import ( ABCMeta, abstractmethod, ) from uuid import uuid4 from six import ( iteritems, with_metaclass, ) from numpy import array from pandas import ( DataFrame, date_range, MultiIndex, ) from toolz import groupby, juxt from toolz.curried.operator import getitem from zipline.lib.adj...
Apache License 2.0
olitheolix/aiokubernetes
aiokubernetes/models/v1_stateful_set_condition.py
V1StatefulSetCondition.__init__
python
def __init__(self, last_transition_time=None, message=None, reason=None, status=None, type=None): self._last_transition_time = None self._message = None self._reason = None self._status = None self._type = None self.discriminator = None if last_transition_time i...
V1StatefulSetCondition - a model defined in Swagger
https://github.com/olitheolix/aiokubernetes/blob/266718b210dff2a9b2212183261ea89adf89115e/aiokubernetes/models/v1_stateful_set_condition.py#L48-L65
import pprint import re class V1StatefulSetCondition(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in defini...
Apache License 2.0
gobot1234/steam.py
steam/abc.py
BaseUser.favourite_badge
python
async def favourite_badge(self) -> FavouriteBadge | None: badge = await self._state.fetch_user_favourite_badge(self.id64) if not badge.has_favorite_badge: return return FavouriteBadge( id=UserBadge.try_value(badge.badgeid), item_id=badge.communityitemid, ...
The user's favourite badge
https://github.com/gobot1234/steam.py/blob/73fcb94eeba7d0d318252b899af80516efc17b0a/steam/abc.py#L583-L596
from __future__ import annotations import abc import asyncio import re from collections.abc import Coroutine from datetime import datetime from typing import TYPE_CHECKING, Any, TypeVar import attr from typing_extensions import Final, Protocol, TypedDict, runtime_checkable from .badge import FavouriteBadge, UserBadges ...
MIT License
albertogeniola/merossiot
meross_iot/utilities/limiter.py
RateLimitChecker.__init__
python
def __init__(self, global_burst_rate: int = 6, global_time_window: timedelta = timedelta(seconds=1), global_tokens_per_interval: int = 2, device_burst_rate: int = 1, device_time_window: timedelta = timedelta(seconds=1), ...
Constructor :param global_burst_rate: Global burst rate, max number of commands that can be executed within the global_time_window :param global_time_window: Time window in seconds that is used to aggregate the API counting :param global_tokens_per_interval: Number of calls allowed within the ti...
https://github.com/albertogeniola/merossiot/blob/4522d6822edbc7dfc454bd3b278e006565d842ff/meross_iot/utilities/limiter.py#L158-L190
from abc import ABC, abstractmethod from datetime import timedelta from enum import Enum from time import time import logging from typing import Dict, Tuple from meross_iot.model.enums import Namespace _LIMITER = logging.getLogger("meross_iot.manager.apilimiter") class BackoffLogic(ABC): @abstractmethod def res...
MIT License
ngageoint/sarpy
sarpy/io/phase_history/cphd1_elements/Dwell.py
DwellType.NumCODTimes
python
def NumCODTimes(self): if self.CODTimes is None: return 0 else: return len(self.CODTimes)
int: The number of cod time polynomial elements.
https://github.com/ngageoint/sarpy/blob/91405721a7e6ffe7c76dd7b143915fee4bee1e82/sarpy/io/phase_history/cphd1_elements/Dwell.py#L125-L133
__classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import List from sarpy.io.xml.base import Serializable from sarpy.io.xml.descriptors import StringDescriptor, SerializableDescriptor, SerializableListDescriptor from sarpy.io.complex.sicd_elements.blocks import Poly2DType from .base import...
MIT License
galarzaa90/tibia.py
tibiapy/abc.py
BaseNews.url
python
def url(self): return self.get_url(self.id)
:class:`str`: The URL to the Tibia.com page of the news entry.
https://github.com/galarzaa90/tibia.py/blob/babcb1648fb99bf5ac0fd0162b38244cbcd21b9d/tibiapy/abc.py#L449-L451
from __future__ import annotations import abc import datetime import enum import json from collections import OrderedDict from typing import Callable, TYPE_CHECKING from tibiapy.utils import get_tibia_url if TYPE_CHECKING: from tibiapy import PvpType, WorldLocation class Serializable: _serializable_properties =...
Apache License 2.0
demisto/demisto-sdk
demisto_sdk/commands/common/hook_validations/script.py
ScriptValidator._get_arg_to_required_dict
python
def _get_arg_to_required_dict(cls, script_json): arg_to_required = {} args = script_json.get('args', []) for arg in args: arg_to_required[arg.get('name')] = arg.get('required', False) return arg_to_required
Get a dictionary arg name to its required status. Args: script_json (dict): Dictionary of the examined script. Returns: dict. arg name to its required status.
https://github.com/demisto/demisto-sdk/blob/8d8767c2dfec77b67c35f4e1022e30ed2893e864/demisto_sdk/commands/common/hook_validations/script.py#L94-L107
import os import re from typing import Optional from demisto_sdk.commands.common.constants import (API_MODULES_PACK, DEPRECATED_REGEXES, PYTHON_SUBTYPES, TYPE_PWSH) from demisto_sdk.commands.common.errors import Errors...
MIT License
thesadru/animethemes-dl
animethemes_dl/parsers/dldata.py
get_formatter
python
def get_formatter(**kwargs) -> Dict[str,str]: formatter = {} for t,d in kwargs.items(): for k,v in d.items(): if (not isinstance(v,(list,dict,bool)) and not k.endswith('ated_at') ): formatter[t+'_'+k] = v formatter['video_filetype'] = 'webm' ...
Generates a formatter dict used for formatting filenames. Takes in kwargs of Dict[str,Any]. Does not keep lists, dicts and bools. Automatically filters out` .endswith('ated_at')` for animethemes-dl. Also adds `{video_filetype:webm,anime_filename:...}`.
https://github.com/thesadru/animethemes-dl/blob/059afa407d4e07e7420a2e08cc6019b51ced7770/animethemes_dl/parsers/dldata.py#L88-L107
import logging import re import string from os import PathLike from os.path import join, realpath, splitext from typing import Dict, List, Optional, Tuple from ..models import (AnimeListSite, AnimeThemeAnime, AnimeThemeEntry, AnimeThemeTheme, AnimeThemeVideo, DownloadData) from ..options import OP...
MIT License
magenta/ddsp
ddsp/core.py
safe_log
python
def safe_log(x, eps=1e-5): safe_x = tf.where(x <= eps, eps, x) return tf.math.log(safe_x)
Avoid taking the log of a non-positive number.
https://github.com/magenta/ddsp/blob/56266e9c255019df050a3c20255caa2beaa912ac/ddsp/core.py#L179-L182
import collections import copy from typing import Any, Dict, Optional, Sequence, Text, TypeVar import gin import numpy as np from scipy import fftpack import tensorflow.compat.v2 as tf Number = TypeVar('Number', int, float, np.ndarray, tf.Tensor) def tf_float32(x): if isinstance(x, tf.Tensor): return tf.cast(x, d...
Apache License 2.0
usi-systems/p4benchmark
p4gen/p4template.py
control
python
def control(fwd_tbl, applies): d = { 'fwd_tbl' : fwd_tbl, 'applies': applies } return read_template('template/controls/ingress.txt', d)
This method returns the apply statement and apply forward_table used in the control flow :param tbl_name: the name of the table :type tbl_name: str :param applies: the apply statement for other table :type applies: str :returns: str -- the code in plain text :raises: None
https://github.com/usi-systems/p4benchmark/blob/e1b22c106c3458f757a362f57027670cee286c47/p4gen/p4template.py#L170-L183
from string import Template from pkg_resources import resource_string def read_template(filename, binding={}): src = Template(resource_string(__name__, filename)) return src.substitute(binding) def p4_define(): p4_define = read_template('template/define.txt') return p4_define def ethernet_header(): ...
Apache License 2.0
huychau/drf-registration
drf_registration/api/register.py
ActivateView.get
python
def get(self, request, uidb64, token): user = get_user_from_uid(uidb64) if user and activation_token.check_token(user, token): set_user_verified(user) send_email_welcome(user) if drfr_settings.USER_ACTIVATE_SUCCESS_TEMPLATE: return render(request, drfr...
Override to get the activation uid and token Args: request (object): Request object uidb64 (string): The uid token (string): The user token
https://github.com/huychau/drf-registration/blob/5327a3373306280f4e114a181b02ecc177cf602f/drf_registration/api/register.py#L91-L117
from django.contrib.auth import password_validation from django.http import HttpResponse from django.shortcuts import render from django.utils.translation import gettext as _ from django.views import View from rest_framework import status from rest_framework.generics import CreateAPIView from rest_framework.response im...
MIT License
miyuchina/mistletoe
mistletoe/base_renderer.py
BaseRenderer.render_raw_text
python
def render_raw_text(self, token): return token.content
Default render method for RawText. Simply return token.content.
https://github.com/miyuchina/mistletoe/blob/c6cfd1a615cd4907ab37c2e653fade7613fe979a/mistletoe/base_renderer.py#L141-L145
import re import sys from mistletoe import block_token, span_token class BaseRenderer(object): _parse_name = re.compile(r"([A-Z][a-z]+|[A-Z]+(?![a-z]))") def __init__(self, *extras): self.render_map = { 'Strong': self.render_strong, 'Emphasis': self.render_emphasis,...
MIT License
surfriderfoundationeurope/mot
src/mot/object_detection/modeling/model_fpn.py
fpn_map_rois_to_levels
python
def fpn_map_rois_to_levels(boxes): sqrtarea = tf.sqrt(tf_area(boxes)) level = tf.cast(tf.floor( 4 + tf.log(sqrtarea * (1. / 224) + 1e-6) * (1.0 / np.log(2))), tf.int32) level_ids = [ tf.where(level <= 2), tf.where(tf.equal(level, 3)), tf.where(tf.equal(level, 4)), ...
Assign boxes to level 2~5. Args: boxes (nx4): Returns: [tf.Tensor]: 4 tensors for level 2-5. Each tensor is a vector of indices of boxes in its level. [tf.Tensor]: 4 tensors, the gathered boxes in each level. Be careful that the returned tensor could be empty.
https://github.com/surfriderfoundationeurope/mot/blob/3434955863767736486bdd45caf33656b594face/src/mot/object_detection/modeling/model_fpn.py#L72-L102
import itertools import numpy as np import tensorflow as tf from tensorpack.models import Conv2D, FixedUnPooling, MaxPooling, layer_register from tensorpack.tfutils.argscope import argscope from tensorpack.tfutils.scope_utils import under_name_scope from tensorpack.tfutils.summary import add_moving_summary from tensorp...
MIT License
rhyssiyan/der-classil.pytorch
inclearn/convnet/resnet.py
resnet50
python
def resnet50(pretrained=False, **kwargs): model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
Constructs a ResNet-50 model.
https://github.com/rhyssiyan/der-classil.pytorch/blob/d711034c550bcac40a6ec7dfa1c65a79589efe93/inclearn/convnet/resnet.py#L215-L222
import torch.nn as nn import torch.utils.model_zoo as model_zoo from torch.nn import functional as F __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.or...
MIT License
marcelm/xopen
src/xopen/__init__.py
PipedCompressionReader.__init__
python
def __init__( self, path, program_args: List[str], mode: str = "r", threads_flag: Optional[str] = None, threads: Optional[int] = None, ): if mode not in ('r', 'rt', 'rb'): raise ValueError("Mode is '{}', but it must be 'r', 'rt' or 'rb'".format(mod...
Raise an OSError when pigz could not be found.
https://github.com/marcelm/xopen/blob/793018655f41642a9037129338ce6ae8db289feb/src/xopen/__init__.py#L260-L300
__all__ = [ "xopen", "PipedGzipReader", "PipedGzipWriter", "PipedIGzipReader", "PipedIGzipWriter", "PipedPigzReader", "PipedPigzWriter", "PipedPBzip2Reader", "PipedPBzip2Writer", "PipedPythonIsalReader", "PipedPythonIsalWriter", "__version__", ] import gzip import sys imp...
MIT License
fichtefoll/filehistory
file_history.py
FileHistory.__init__
python
def __init__(self): self.__load_settings() self.__load_history() self.__clear_context() if self.DELETE_ALL_ON_STARTUP: sublime.set_timeout_async(lambda: self.delete_all_history(), 0) elif self.CLEANUP_ON_STARTUP: sublime.set_timeout_async(lambda: self.clea...
Class to manage the file-access history
https://github.com/fichtefoll/filehistory/blob/afb0fdeaeb21ee5dd87b384c2fafabd7d206319f/file_history.py#L33-L42
import os import hashlib import json import time import re import shutil import glob from textwrap import dedent import sublime import sublime_plugin class Singleton(type): _instance = None def __call__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__call...
MIT License
datastax/python-driver
tests/unit/test_types.py
DateRangeDeserializationTests._deserialize_date_range
python
def _deserialize_date_range(self, truncate_kwargs, precision, round_up_truncated_upper_value, increment_loop_variable): def truncate_date(number): dt = datetime.datetime.fromtimestamp(number / 1000.0, tz=utc_timezone) dt = dt.replace(**truncate_kwargs) ...
This functions iterates over several DateRange objects determined by lower_value upper_value which are given as a value that represents seconds since the epoch. We want to make sure the lower_value is correctly rounded down and the upper value is correctly rounded up. In the case of rounding dow...
https://github.com/datastax/python-driver/blob/12a8adce943fe37a05ad6580e8bd302b65c2d93a/tests/unit/test_types.py#L766-L816
try: import unittest2 as unittest except ImportError: import unittest import datetime import tempfile import time from binascii import unhexlify import six import cassandra from cassandra import util from cassandra.cqltypes import ( CassandraType, DateRangeType, DateType, DecimalType, EmptyValue, Long...
Apache License 2.0
tylerbutler/engineer
engineer/plugins/core.py
JinjaEnvironmentPlugin.get_globals
python
def get_globals(cls): return cls.globals
If required, subclasses can override this method to return a dict of functions to add to the Jinja environment globally. The default implementation simply returns :attr:`~engineer.plugins.JinjaEnvironmentPlugin.globals`.
https://github.com/tylerbutler/engineer/blob/1fdcae512a828ea681be8c469f6863b974260614/engineer/plugins/core.py#L307-L313
import logging __author__ = 'Tyler Butler <tyler@tylerbutler.com>' def find_plugins(entrypoint): try: import pkg_resources except ImportError: pkg_resources = None if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(entrypoint): yield entryp...
MIT License
openschc/openschc
src/stats/statsct.py
Statsct.initialize
python
def initialize(init_time=None): dprint('Init statsct module') if init_time is None: init_time = time.time() Statsct.results['init_time'] = init_time Statsct.results['packet_list'] = [] Statsct.sender_packets['packet_list'] = [] Statsct.receiver_packets['pack...
Class to initializa the static class creates the file to write and the instance of the class
https://github.com/openschc/openschc/blob/7b0c165a27936d8f2732a90844a00c5ade23eea5/src/stats/statsct.py#L75-L103
try: from ucollections import defaultdict except ImportError: from collections import defaultdict try: from ucollections import OrderedDict except ImportError: from collections import OrderedDict try: import utime as time except ImportError: import time import sys from .toa_calculator import get...
MIT License
morgan-stanley/treadmill
lib/python/treadmill/yamlwrapper.py
_repr_none
python
def _repr_none(dumper, _data): return dumper.represent_scalar(u'tag:yaml.org,2002:null', '~')
Fix yaml None representation (use ~).
https://github.com/morgan-stanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/yamlwrapper.py#L56-L59
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import six import yaml from yaml import YAMLError try: from yaml import CSafeLoader as Loader from yaml import CSafeDumper as Dumper except ImportError: from y...
Apache License 2.0
annoviko/pyclustering
pyclustering/cluster/cure.py
cure.__process_by_python
python
def __process_by_python(self): self.__create_queue() self.__create_kdtree() while len(self.__queue) > self.__number_cluster: cluster1 = self.__queue[0] cluster2 = cluster1.closest self.__queue.remove(cluster1) self.__queue.remove(cluster2) ...
! @brief Performs cluster analysis using python code.
https://github.com/annoviko/pyclustering/blob/bf4f51a472622292627ec8c294eb205585e50f52/pyclustering/cluster/cure.py#L165-L230
import numpy from pyclustering.cluster.encoder import type_encoding from pyclustering.utils import euclidean_distance_square from pyclustering.container.kdtree import kdtree from pyclustering.core.wrapper import ccore_library import pyclustering.core.cure_wrapper as wrapper class cure_cluster: def __init__(self, po...
BSD 3-Clause New or Revised License
ucy-linc-lab/fogify
connectors/materialized_connectors/DockerBasedConnectors.py
SwarmConnector.down
python
def down(self, timeout=60): try: subprocess.check_output(['docker', 'stack', 'rm', 'fogify']) except Exception as e: print(e) finished = False for i in range(int(timeout / 5)): sleep(5) if self.count_services() == 0: finishe...
Undeploys a running infrastructure :param timeout: The duration that the system will wait until it raises exception
https://github.com/ucy-linc-lab/fogify/blob/80dee9e2079ef45c49a6cd6629a3bf0b31461afb/connectors/materialized_connectors/DockerBasedConnectors.py#L347-L364
import copy import json import logging import os import socket import subprocess from time import sleep import docker from flask_api import exceptions from utils.host_info import HostInfo from FogifyModel.base import Node, FogifyModel from connectors.base import BasicConnector class CommonDockerSuperclass(BasicConnecto...
Apache License 2.0
samschott/maestral
src/maestral/utils/__init__.py
chunks
python
def chunks(lst: list, n: int, consume: bool = False) -> Iterator[list]: if consume: while lst: chunk = lst[0:n] del lst[0:n] yield chunk else: for i in range(0, len(lst), n): yield lst[i : i + n]
Partitions an iterable into chunks of length ``n``. :param lst: Iterable to partition. :param n: Chunk size. :param consume: If True, the list will be consumed (emptied) during the iteration. This can be used to free memory in case of large lists. :returns: Iterator over chunks.
https://github.com/samschott/maestral/blob/a0cd0ebbfecae65d71337fc35a54d1f3fab7ab5a/src/maestral/utils/__init__.py#L35-L53
import os from types import TracebackType from packaging.version import Version from typing import Iterator, TypeVar, Optional, Iterable, Tuple, Type _N = TypeVar("_N", float, int) ExecInfoType = Tuple[Type[BaseException], BaseException, Optional[TracebackType]] def natural_size(num: float, unit: str = "B", sep: bool =...
MIT License
hpe-container-platform-community/hpecp-python-library
hpecp/k8s_cluster.py
K8sClusterHostConfig.to_dict
python
def to_dict(self): return {"node": self.node, "role": self.role}
Returns a dict representation of the object. Returns ------- dict Example ------- >>> .to_dict() { 'node': '/api/v2/worker/k8shost/12', 'role': 'master' }
https://github.com/hpe-container-platform-community/hpecp-python-library/blob/625fb25c99698a2203b394ef39a253e2b4f0d7c9/hpecp/k8s_cluster.py#L241-L256
from __future__ import absolute_import import re from distutils.version import LooseVersion from enum import Enum from requests.structures import CaseInsensitiveDict from .base_resource import AbstractResource, AbstractWaitableResourceController try: basestring except NameError: basestring = str class K8sCluste...
MIT License
team-ocean/veros
veros/tools/setup.py
interpolate
python
def interpolate(coords, var, interp_coords, missing_value=None, fill=True, kind="linear"): if len(coords) != len(interp_coords) or len(coords) != var.ndim: raise ValueError("Dimensions of coordinates and values do not match") if missing_value is not None: invalid_mask = npx.isclose(var, missing_...
Interpolate globally defined data to a different (regular) grid. Arguments: coords: Tuple of coordinate arrays for each dimension. var (:obj:`ndarray` of dim (nx1, ..., nxd)): Variable data to interpolate. interp_coords: Tuple of coordinate arrays to interpolate to. missing_value (optio...
https://github.com/team-ocean/veros/blob/db4bbf20118d4608cf0dd1f571d5274a4b3f012a/veros/tools/setup.py#L8-L49
from veros.core.operators import numpy as npx import numpy as onp import scipy.interpolate import scipy.spatial
MIT License
jyveapp/django-pgclone
pgclone/database.py
get_url
python
def get_url(db_config): return ( f'postgresql://{db_config["USER"]}:{db_config["PASSWORD"]}' f'@{db_config["HOST"]}:{db_config["PORT"]}/{db_config["NAME"]}' )
Convert a database dictionary config to a url
https://github.com/jyveapp/django-pgclone/blob/89b26372201e50393cb6a0b0dbb2bbc707d01c22/pgclone/database.py#L30-L35
import copy from django.conf import settings def get_default_config(): return copy.deepcopy(settings.DATABASES['default']) def make_config(db_name): for db in settings.DATABASES.values(): if db.get('NAME') == db_name: raise RuntimeError( f'pgclone cannot use temporary datab...
BSD 3-Clause New or Revised License
azure/azure-devops-cli-extension
azure-devops/azext_devops/devops_sdk/v5_1/tfvc/tfvc_client.py
TfvcClient.get_labels
python
def get_labels(self, request_data, project=None, top=None, skip=None): route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') query_parameters = {} if request_data is not None: if request_data.label_scope...
GetLabels. Get a collection of shallow label references. :param :class:`<TfvcLabelRequestData> <azure.devops.v5_1.tfvc.models.TfvcLabelRequestData>` request_data: labelScope, name, owner, and itemLabelFilter :param str project: Project ID or project name :param int top: Max number of lab...
https://github.com/azure/azure-devops-cli-extension/blob/5f33f7d81a9c2d2990044fbd9ffa6b535cbda528/azure-devops/azext_devops/devops_sdk/v5_1/tfvc/tfvc_client.py#L628-L663
 from msrest import Serializer, Deserializer from ...client import Client from . import models class TfvcClient(Client): def __init__(self, base_url=None, creds=None): super(TfvcClient, self).__init__(base_url, creds) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}...
MIT License
deanmalmgren/flo
flo/tasks/graph.py
TaskGraph._run_helper
python
def _run_helper(self, starting_tasks, do_run_func, mock_run): self.logger.info(self.duration_message(starting_tasks)) for task in self.iter_tasks(starting_tasks): if do_run_func(task): if mock_run: task.mock_run() else: ...
This is a convenience method that is used to slightly modify the behavior of running a workflow depending on the circumstances.
https://github.com/deanmalmgren/flo/blob/40ba3ce29a03cecb74bf809e40061e5e5c9d6a6b/flo/tasks/graph.py#L368-L386
import sys import os import time import csv import collections import datetime import glob from distutils.util import strtobool import json import networkx as nx from ..exceptions import NonUniqueTask, ShellError, CommandLineException from .. import colors from .. import shell from .. import resources from .. import lo...
MIT License
2ndwatch/cloudendure-python
cloudendure/cloudendure_api/models/cloud_endure_subnet.py
CloudEndureSubnet.__init__
python
def __init__(self, subnet_id=None, network_id=None, name=None): self._subnet_id = None self._network_id = None self._name = None self.discriminator = None if subnet_id is not None: self.subnet_id = subnet_id if network_id is not None: self.networ...
CloudEndureSubnet - a model defined in Swagger
https://github.com/2ndwatch/cloudendure-python/blob/f81d1be1422b7c19adedb06c584803eaaa811919/cloudendure/cloudendure_api/models/cloud_endure_subnet.py#L36-L47
import pprint import re import six class CloudEndureSubnet: """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definiti...
MIT License
maximtrp/ranger-archives
compress.py
compress.tab
python
def tab(self, tabnum): extension = ['.7z', '.zip', '.tar.gz', '.tar.bz2', '.tar.xz'] return ['compress ' + os.path.basename(self.fm.thisdir.path) + ext for ext in extension]
Complete with current folder name
https://github.com/maximtrp/ranger-archives/blob/f19bdd4190997f29bad52a5584d6490a988fbfda/compress.py#L53-L57
import os.path from re import search from ranger.api.commands import Command from ranger.core.loader import CommandLoader from .archives_utils import parse_escape_args, get_compression_command class compress(Command): def execute(self): cwd = self.fm.thisdir marked_files = cwd.get_selection() ...
MIT License
docusign/docusign-python-client
docusign_esign/models/tab_account_settings.py
TabAccountSettings.note_tabs_enabled
python
def note_tabs_enabled(self, note_tabs_enabled): self._note_tabs_enabled = note_tabs_enabled
Sets the note_tabs_enabled of this TabAccountSettings. # noqa: E501 :param note_tabs_enabled: The note_tabs_enabled of this TabAccountSettings. # noqa: E501 :type: str
https://github.com/docusign/docusign-python-client/blob/c6aeafff0d046fa6c10a398be83ba9e24b05d4ea/docusign_esign/models/tab_account_settings.py#L626-L635
import pprint import re import six from docusign_esign.client.configuration import Configuration class TabAccountSettings(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute...
MIT License
cleverhans-lab/cleverhans
cleverhans_v3.1.0/cleverhans/attack_bundling.py
AttackGoal.print_progress
python
def print_progress(self, criteria, run_counts): print("Working on a " + self.__class__.__name__ + " goal.")
Prints a progress message about how much has been done toward the goal. :param criteria: dict, of the format returned by get_criteria :param run_counts: dict mapping each AttackConfig to a numpy array specifying how many times it has been run for each example
https://github.com/cleverhans-lab/cleverhans/blob/4aed4be702be5ce13d5017b8a3c6a2cdc4fc0009/cleverhans_v3.1.0/cleverhans/attack_bundling.py#L694-L701
import copy import logging import time import numpy as np import six from six.moves import range import tensorflow as tf from cleverhans.attacks import Noise from cleverhans.attacks import ProjectedGradientDescent from cleverhans.attacks import SPSA from cleverhans.evaluation import correctness_and_confidence from clev...
MIT License
plusmultiply/mprm
datasets/Scannet_subcloud.py
ScannetDataset.load_evaluation_points
python
def load_evaluation_points(self, file_path): mesh_path = file_path.split('/') mesh_path[-2] = mesh_path[-2][:-6] + 'meshes' mesh_path = '/'.join(mesh_path) vertex_data, faces = read_ply(mesh_path[:-4] + '_mesh.ply', triangular_mesh=True) return np.vstack((vertex_data['x'], vertex...
Load points (from test or validation split) on which the metrics should be evaluated
https://github.com/plusmultiply/mprm/blob/9783dc179f0bfca8ca7316b638269769f11027aa/datasets/Scannet_subcloud.py#L982-L992
import json import os import tensorflow as tf import numpy as np import time import pickle from sklearn.neighbors import KDTree from utils.ply import read_ply, write_ply from utils.mesh import rasterize_mesh from os import makedirs, listdir from os.path import exists, join, isfile, isdir from datasets.common import Dat...
MIT License
escorciav/deep-action-proposals
daps/model.py
forward_pass
python
def forward_pass(network, input_data): l_pred_var, y_pred_var = lasagne.layers.get_output(network, input_data, deterministic=True) loc = l_pred_var.eval().reshape((-1, 2)) return loc, y_pred_var.eval()
Forward pass input_data over network
https://github.com/escorciav/deep-action-proposals/blob/c14f512febc1abd0ec40bd3188a83e4ee3913535/daps/model.py#L77-L83
import lasagne import numpy as np import theano.tensor as T from daps.c3d_encoder import Feature from daps.utils.segment import format as segment_format EPSILON = 10e-8 def build_lstm(input_var=None, seq_length=256, depth=2, width=512, input_size=4096, grad_clip=100, forget_bias=5.0): network = lasag...
MIT License
tresamigossd/smv
src/main/python/smv/smvappinfo.py
SmvAppInfo._common_prefix
python
def _common_prefix(self, fqn_list): if not fqn_list: return '' parsed = [s.split(".") for s in fqn_list] s1 = min(parsed) s2 = max(parsed) for i, c in enumerate(s1): if c != s2[i]: return ".".join(s1[:i]) return ".".join(s1)
Given a list of fqns, return the longest common prefix
https://github.com/tresamigossd/smv/blob/e12257b5b07113d805e7fdd8de41cbcf72120ed7/src/main/python/smv/smvappinfo.py#L41-L54
from smv.utils import scala_seq_to_list import json from smv.modulesvisitor import ModulesVisitor class SmvAppInfo(object): def __init__(self, smvApp): self.smvApp = smvApp self.dsm = smvApp.dsm self.stages = smvApp.stages() def _graph(self): nodes = self.dsm.allDataSets() ...
Apache License 2.0
vforgione/logging2
logging2/loggers.py
Logger.warning
python
def warning(self, message: str, **context) -> None: self._log(message=message, level=LogLevel.warning, **context)
Calls each registered ``Handler``'s ``write`` method to produce a warning log entry. :param message: the user message to be written :param context: additional key-value pairs to override template context during interpolation
https://github.com/vforgione/logging2/blob/9d620c14d9b5f67e3dc285082330296cf1ecbfcd/logging2/loggers.py#L134-L140
import inspect import os import re import sys import traceback from datetime import datetime, tzinfo from datetime import timezone as _tz from typing import Callable, Dict, Iterable, List, Optional, Set, Union from logging2 import LogRegister from logging2.handlers.abc import Handler from logging2.handlers.streaming im...
MIT License
genialis/resolwe
resolwe/test_helpers/test_runner.py
_manager_setup
python
def _manager_setup(): if TESTING_CONTEXT.get("manager_reset", False): return TESTING_CONTEXT["manager_reset"] = True state.update_constants() manager.drain_messages()
Execute setup operations common to serial and parallel testing. This mostly means state cleanup, such as resetting database connections and clearing the shared state.
https://github.com/genialis/resolwe/blob/dc8a70979ae9722e6c60ae0e3935c6542c637f48/resolwe/test_helpers/test_runner.py#L67-L77
import asyncio import contextlib import errno import logging import os import re import shutil import subprocess import sys from pathlib import Path from unittest.mock import patch import yaml import zmq import zmq.asyncio from channels.db import database_sync_to_async from django.conf import settings from django.core....
Apache License 2.0
googleads/google-ads-python
google/ads/googleads/v8/services/services/domain_category_service/transports/grpc.py
DomainCategoryServiceGrpcTransport.get_domain_category
python
def get_domain_category( self, ) -> Callable[ [domain_category_service.GetDomainCategoryRequest], domain_category.DomainCategory, ]: if "get_domain_category" not in self._stubs: self._stubs["get_domain_category"] = self.grpc_channel.unary_unary( "/goog...
r"""Return a callable for the get domain category method over gRPC. Returns the requested domain category. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `HeaderError <>`__ `InternalError <>`__ `QuotaError <>`__ `RequestError <>`__ Returns: ...
https://github.com/googleads/google-ads-python/blob/6794993e146abcfe21292677144c66cb546446bc/google/ads/googleads/v8/services/services/domain_category_service/transports/grpc.py#L213-L243
import warnings from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers from google.api_core import gapic_v1 import google.auth from google.auth import credentials as ga_credentials from google.auth.transport.grpc import SslCredentials import grpc from google.ad...
Apache License 2.0
commvault/cvpysdk
cvpysdk/activitycontrol.py
ActivityControl.is_enabled
python
def is_enabled(self, activity_type): self._get_activity_control_status() for each_activity in self._activity_control_properties_list: if int(each_activity['activityType']) == self._activity_type_dict[activity_type]: self._reEnableTime = each_activity['reEna...
Returns True/False based on the enabled flag and also sets other relevant properties for a given activity type. Args: activity_type (str) -- Activity Type to be Enabled or Disabled Values: "ALL ACTIVITY", "DATA M...
https://github.com/commvault/cvpysdk/blob/66df30e6e31d619812b7756cb4f7e130b220a08f/cvpysdk/activitycontrol.py#L233-L261
from __future__ import absolute_import from __future__ import unicode_literals from .exception import SDKException class ActivityControl(object): def __init__(self, commcell_object): self._commcell_object = commcell_object self._activity_type_dict = { "ALL ACTIVITY": 128, "DA...
Apache License 2.0
leonjza/hogar
hogar/Plugins/Learn/main.py
commands
python
def commands (): return ['learn', 'forget', 'show']
Commands In the case of text plugins, returns the commands that this plugin should trigger for. For other message types, a empty list should be returned. -- @return list
https://github.com/leonjza/hogar/blob/a8cf4b6a6b508e5e86d26dd5cbd55add560d26a5/hogar/Plugins/Learn/main.py#L60-L72
from hogar.Models.LearnKey import LearnKey from hogar.Models.LearnValue import LearnValue from hogar.Utils.StringUtils import ignore_case_replace import peewee import logging logger = logging.getLogger(__name__) def enabled (): return True def applicable_types (): return ['text']
MIT License
openstack/cinder
cinder/api/api_utils.py
validate_integer
python
def validate_integer(value, name, min_value=None, max_value=None): try: value = strutils.validate_integer(value, name, min_value, max_value) return value except ValueError as e: raise webob.exc.HTTPBadRequest(explanation=str(e))
Make sure that value is a valid integer, potentially within range. :param value: the value of the integer :param name: the name of the integer :param min_length: the min_length of the integer :param max_length: the max_length of the integer :returns: integer
https://github.com/openstack/cinder/blob/4558e4b53a7e41dc1263417a4824f39bb6fd30e1/cinder/api/api_utils.py#L128-L141
from keystoneauth1 import exceptions as ks_exc from keystoneauth1 import identity from keystoneauth1 import loading as ka_loading from keystoneclient import client from oslo_config import cfg from oslo_log import log as logging from oslo_utils import strutils import webob from webob import exc from cinder import except...
Apache License 2.0
osmr/imgclsmob
pytorch/pytorchcv/models/sepreresnet_cifar.py
sepreresnet542bn_svhn
python
def sepreresnet542bn_svhn(num_classes=10, **kwargs): return get_sepreresnet_cifar(num_classes=num_classes, blocks=542, bottleneck=True, model_name="sepreresnet542bn_svhn", **kwargs)
SE-PreResNet-542(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- num_classes : int, default 10 Number of classification num_classes. pretrained : bool, default False Whether to load the pretrained weights for model. ...
https://github.com/osmr/imgclsmob/blob/ea5f784eea865ce830f3f97c5c1d1f6491d9cbb2/pytorch/pytorchcv/models/sepreresnet_cifar.py#L443-L457
__all__ = ['CIFARSEPreResNet', 'sepreresnet20_cifar10', 'sepreresnet20_cifar100', 'sepreresnet20_svhn', 'sepreresnet56_cifar10', 'sepreresnet56_cifar100', 'sepreresnet56_svhn', 'sepreresnet110_cifar10', 'sepreresnet110_cifar100', 'sepreresnet110_svhn', 'sepreresnet164bn_cifar10', 'sepre...
MIT License
fish-quant/big-fish
bigfish/classification/input_preparation.py
_get_centrosome_distance_map
python
def _get_centrosome_distance_map(centrosome_coord, cell_mask): if centrosome_coord.size == 3: centrosome_coord_2d = centrosome_coord[1:] else: centrosome_coord_2d = centrosome_coord.copy() mask_centrosome = np.zeros_like(cell_mask) mask_centrosome[centrosome_coord_2d[:, 0], ...
Build distance map from a centrosome localisation. Parameters ---------- centrosome_coord : np.ndarray, np.int64 Coordinates of the detected centrosome with shape (nb_elements, 3) or (nb_elements, 2). One coordinate per dimension (zyx or yx dimensions). cell_mask : np.ndarray, bool ...
https://github.com/fish-quant/big-fish/blob/5512b6e3274872793ef4365a6dc423c72add91f9/bigfish/classification/input_preparation.py#L288-L320
import numpy as np from scipy import ndimage as ndi import bigfish.stack as stack from skimage.measure import regionprops def prepare_extracted_data(cell_mask, nuc_mask=None, ndim=None, rna_coord=None, centrosome_coord=None): stack.check_parameter(ndim=(int, type(None))) if rna_coord ...
BSD 3-Clause New or Revised License
docusign/docusign-python-client
docusign_esign/models/bulk_sending_list_summary.py
BulkSendingListSummary.__eq__
python
def __eq__(self, other): if not isinstance(other, BulkSendingListSummary): return False return self.to_dict() == other.to_dict()
Returns true if both objects are equal
https://github.com/docusign/docusign-python-client/blob/c6aeafff0d046fa6c10a398be83ba9e24b05d4ea/docusign_esign/models/bulk_sending_list_summary.py#L193-L198
import pprint import re import six from docusign_esign.client.configuration import Configuration class BulkSendingListSummary(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attri...
MIT License
rlworkgroup/garage
src/garage/torch/modules/multi_headed_mlp_module.py
MultiHeadedMLPModule._check_parameter_for_output_layer
python
def _check_parameter_for_output_layer(cls, var_name, var, n_heads): if isinstance(var, (list, tuple)): if len(var) == 1: return list(var) * n_heads if len(var) == n_heads: return var msg = ('{} should be either an integer or a collection of len...
Check input parameters for output layer are valid. Args: var_name (str): variable name var (any): variable to be checked n_heads (int): number of head Returns: list: list of variables (length of n_heads) Raises: ValueError: if the va...
https://github.com/rlworkgroup/garage/blob/3a578852c392cecde5b7c9786aa182d74f6df1d4/src/garage/torch/modules/multi_headed_mlp_module.py#L109-L133
import copy import torch import torch.nn as nn from garage.torch import NonLinearity class MultiHeadedMLPModule(nn.Module): def __init__(self, n_heads, input_dim, output_dims, hidden_sizes, hidden_nonlinearity=torch.relu, ...
MIT License
docusign/docusign-python-client
docusign_esign/models/commission_county.py
CommissionCounty.anchor_tab_processor_version_metadata
python
def anchor_tab_processor_version_metadata(self, anchor_tab_processor_version_metadata): self._anchor_tab_processor_version_metadata = anchor_tab_processor_version_metadata
Sets the anchor_tab_processor_version_metadata of this CommissionCounty. :param anchor_tab_processor_version_metadata: The anchor_tab_processor_version_metadata of this CommissionCounty. # noqa: E501 :type: PropertyMetadata
https://github.com/docusign/docusign-python-client/blob/c6aeafff0d046fa6c10a398be83ba9e24b05d4ea/docusign_esign/models/commission_county.py#L748-L756
import pprint import re import six from docusign_esign.client.configuration import Configuration class CommissionCounty(object): """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute n...
MIT License
red-hat-storage/ocs-ci
ocs_ci/ocs/resources/bucketclass.py
bucket_class_factory
python
def bucket_class_factory( request, mcg_obj, backingstore_factory, namespace_store_factory ): interfaces = { "oc": mcg_obj.oc_create_bucketclass, "cli": mcg_obj.cli_create_bucketclass, } created_bucket_classes = [] def _create_bucket_class(bucket_class_dict): if "interface" in...
Create a bucket class factory. Calling this fixture creates a new custom bucket class. For a custom backingstore(s), provide the 'backingstore_dict' parameter. Args: request (object): Pytest built-in fixture mcg_obj (MCG): An MCG object containing the MCG S3 connection credentials backi...
https://github.com/red-hat-storage/ocs-ci/blob/81bc3dd3c2bccbf875ffa8fa5fa2eb0ac9d52b7e/ocs_ci/ocs/resources/bucketclass.py#L41-L199
import logging from ocs_ci.ocs import constants from ocs_ci.ocs.resources.backingstore import BackingStore from ocs_ci.ocs.exceptions import CommandFailed from ocs_ci.framework import config from ocs_ci.ocs.ocp import OCP from ocs_ci.helpers.helpers import create_unique_resource_name log = logging.getLogger(__name__) c...
MIT License
csyben/pyro-nn
pyronn/ct_reconstruction/geometry/geometry_fan_2d.py
GeometryFan2D.set_trajectory
python
def set_trajectory(self, central_ray_vectors): self.central_ray_vectors = np.array(central_ray_vectors, self.np_dtype)
Sets the member central_ray_vectors. Args: central_ray_vectors: np.array defining the trajectory central_ray_vectors.
https://github.com/csyben/pyro-nn/blob/726b62b57d7093ff0f3e675e66d976d989eebc0a/pyronn/ct_reconstruction/geometry/geometry_fan_2d.py#L38-L44
import numpy as np from .geometry_base import GeometryBase class GeometryFan2D(GeometryBase): def __init__(self, volume_shape, volume_spacing, detector_shape, detector_spacing, number_of_projections, angular_range, source_detector_distance, source_...
Apache License 2.0
anymesh/anymesh-python
example/urwid/graphics.py
PythonLogo.__init__
python
def __init__(self): blu = AttrSpec('light blue', 'default') yel = AttrSpec('yellow', 'default') width = 17 self._canvas = Text([ (blu, " ______\n"), (blu, " _|_o__ |"), (yel, "__\n"), (blu, " | _____|"), (yel, " |\n"), (blu, " |...
Create canvas containing an ASCII version of the Python Logo and store it.
https://github.com/anymesh/anymesh-python/blob/017b7808f2fbdc765604488d325678c28be438c0/example/urwid/graphics.py#L884-L897
from urwid.util import decompose_tagmarkup, get_encoding_mode from urwid.canvas import CompositeCanvas, CanvasJoin, TextCanvas, CanvasCombine, SolidCanvas from urwid.widget import WidgetMeta, Widget, BOX, FIXED, FLOW, nocache_widget_render, nocache_widget_render_instance, fixed_size, WidgetWrap, Divider, Solid...
MIT License
deepmind/acme
acme/utils/loggers/terminal.py
serialize
python
def serialize(values: base.LoggingData) -> str: return ' | '.join(f'{_format_key(k)} = {_format_value(v)}' for k, v in sorted(values.items()))
Converts `values` to a pretty-printed string. This takes a dictionary `values` whose keys are strings and returns a formatted string such that each [key, value] pair is separated by ' = ' and each entry is separated by ' | '. The keys are sorted alphabetically to ensure a consistent order, and snake case is sp...
https://github.com/deepmind/acme/blob/39232315e1761219bcc98e7a4ecdd308a42b00e4/acme/utils/loggers/terminal.py#L38-L59
import logging import time from typing import Any, Callable from acme.utils.loggers import base import numpy as np def _format_key(key: str) -> str: return key.replace('_', ' ').title() def _format_value(value: Any) -> str: value = base.to_numpy(value) if isinstance(value, (float, np.number)): return f'{value...
Apache License 2.0
dopefishh/pympi
pympi/Praat.py
TextGrid.get_tier
python
def get_tier(self, name_num): return self.tiers[name_num - 1] if isinstance(name_num, int) else [i for i in self.tiers if i.name == name_num][0]
Gives a tier, when multiple tiers exist with that name only the first is returned. :param name_num: Name or number of the tier to return. :type name_num: int or str :returns: The tier. :raises IndexError: If the tier doesn't exist.
https://github.com/dopefishh/pympi/blob/c17292c21dacb747a20fc1069450792b52c8a6f8/pympi/Praat.py#L175-L185
import codecs import re import struct VERSION = '1.70.2' class TextGrid: def __init__(self, file_path=None, xmin=0, xmax=None, codec='utf-8'): self.tiers = [] self.codec = codec if not file_path: if xmax is None: raise Exception('No xmax specified') se...
MIT License
krassowski/nbpipeline
nbpipeline/rules.py
NotebookRule.__init__
python
def __init__( self, *args, notebook, diff=True, deduce_io=True, deduce_io_from_data_vault=True, execute=True, **kwargs ): super().__init__(*args, **kwargs) self.todos = [] self.notebook = notebook self.absolute_notebook_path = Path(note...
Rule for Jupyter Notebooks Args: deduce_io: whether to automatically deduce inputs and outputs from the code cells tagged "inputs" and "outputs"; local variables defined in the cell will be evaluated and used as inputs or outputs. If you want to generate paths with a...
https://github.com/krassowski/nbpipeline/blob/c2337db2b19767b2cdfcc9bf019e2bf687bb4423/nbpipeline/rules.py#L247-L289
import json import pickle import re from copy import copy, deepcopy from functools import lru_cache from json import JSONDecodeError from os import system, walk, sep from abc import ABC, abstractmethod from pathlib import Path import time from subprocess import check_output from tempfile import NamedTemporaryFile from ...
MIT License
seldonio/alibi
alibi/utils/distributed.py
DistributedExplainer.actor_index
python
def actor_index(self) -> int: return self._actor_index
Returns the index of the actor for which state is returned.
https://github.com/seldonio/alibi/blob/ef757b9579f85ef2e3dfc7088211969616ee3fdb/alibi/utils/distributed.py#L550-L554
import copy import logging import numpy as np from functools import partial from scipy import sparse from typing import Any, Dict, Generator, List, Optional, Tuple, Union logger = logging.getLogger(__name__) def check_ray() -> bool: import importlib spec = importlib.util.find_spec('ray') if spec: ...
Apache License 2.0
mikidown/mikidown
mikidown/mikiwindow.py
MikiWindow.updateRecentViewedNotes
python
def updateRecentViewedNotes(self): self.viewedList.clear() self.viewedListActions = [] viewedNotes = self.settings.recentViewedNotes() existedNotes = [] i = 0 for f in viewedNotes: if self.notesTree.pageExists(f): existedNotes.append(f) ...
Switching notes will trigger this. When Alt pressed, show note number.
https://github.com/mikidown/mikidown/blob/70568eff44e4b8bc718dcdf35f81a31baebb9b74/mikidown/mikiwindow.py#L973-L1003
import os import shutil import re from threading import Thread from PyQt5.QtCore import Qt from PyQt5 import QtCore, QtGui, QtWidgets, QtWebKitWidgets, QtPrintSupport from whoosh.index import create_in, open_dir from whoosh.qparser import QueryParser, RegexPlugin from whoosh.writing import AsyncWriter import mikidown.m...
MIT License
jobovy/galpy
galpy/util/leung_dop853.py
dense_output
python
def dense_output(t_current, t_old, h_current, rcont): s = (t_current - t_old) / h_current s1 = 1.0 - s return rcont[0] + s * (rcont[1] + s1 * ( rcont[2] + s * (rcont[3] + s1 * (rcont[4] + s * (rcont[5] + s1 * (rcont[6] + s * rcont[7]))))))
Dense output function, basically extrapolatin
https://github.com/jobovy/galpy/blob/0470fa3e990f44319e9340497f669699d1bf1008/galpy/util/leung_dop853.py#L239-L248
import numpy c2 = 0.526001519587677318785587544488e-1 c3 = 0.789002279381515978178381316732e-1 c4 = 0.118350341907227396726757197510 c5 = 0.281649658092772603273242802490 c6 = 0.333333333333333333333333333333 c7 = 0.25 c8 = 0.307692307692307692307692307692 c9 = 0.651282051282051282051282051282 c10 = 0.6 c11 = 0.8571428...
BSD 3-Clause New or Revised License
tensorflow/fold
tensorflow_fold/loom/loom.py
Weaver.named_tensor
python
def named_tensor(self, name): return self._tensor_name_to_result[name]
Return a LoomResult which stands in for the named Tensor input.
https://github.com/tensorflow/fold/blob/0e7ca14832a14a5f2009d4e0424783a80e7d7a2c/tensorflow_fold/loom/loom.py#L929-L931
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import functools import numbers import re import numpy as np import six from six.moves import xrange import tensorflow as tf from tensorflow_fold.loom import deserializing_weaver_...
Apache License 2.0
mpi4jax/mpi4jax
mpi4jax/_src/collective_ops/sendrecv.py
sendrecv
python
def sendrecv( sendbuf, recvbuf, source, dest, *, sendtag=0, recvtag=_MPI.ANY_TAG, comm=None, status=None, token=None, ): if token is None: token = create_token(sendbuf) if comm is None: comm = get_default_comm() comm = wrap_as_hashable(comm) if sta...
Perform a sendrecv operation. .. warning:: Unlike mpi4py's sendrecv, this returns a *new* array with the received data. Arguments: sendbuf: Array or scalar input to send. recvbuf: Array or scalar input with the correct shape and dtype. This can contain arbitrary data and wi...
https://github.com/mpi4jax/mpi4jax/blob/e3ed6f00a5552099f260c6b1f68588917461403b/mpi4jax/_src/collective_ops/sendrecv.py#L40-L102
import numpy as _np from mpi4py import MPI as _MPI from jax import abstract_arrays, core from jax.core import Primitive from jax.interpreters import ad, xla, batching from jax.lax import create_token from jax.lib import xla_client from ..utils import ( HashableMPIType, default_primitive_impl, to_dtype_handl...
MIT License
netmanaiops/logclass
decorators.py
print_step
python
def print_step(func): @functools.wraps(func) def wrapper_print_name(*args, **kwargs): print(f"Calling {func.__qualname__}") value = func(*args, **kwargs) return value return wrapper_print_name
Print the function signature and return value
https://github.com/netmanaiops/logclass/blob/62c1c9c61294625bdb3d99dc01b6adc7b735c4ab/decorators.py#L19-L26
import functools def debug(func): @functools.wraps(func) def wrapper_debug(*args, **kwargs): args_repr = [repr(a) for a in args] kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] signature = ", ".join(args_repr + kwargs_repr) print(f"Calli...
MIT License
shunichi09/pythonlinearnonlinearcontrol
PythonLinearNonlinearControl/envs/cartpole.py
CartPoleEnv.step
python
def step(self, u): if self.config["input_lower_bound"] is not None: u = np.clip(u, self.config["input_lower_bound"], self.config["input_upper_bound"]) d_x0 = self.curr_x[1] d_x1 = (u[0] + self.config["mp"] * np.sin(self.curr_x[2]) ...
step environments Args: u (numpy.ndarray) : input, shape(input_size, ) Returns: next_x (numpy.ndarray): next state, shape(state_size, ) cost (float): costs done (bool): end the simulation or not info (dict): information
https://github.com/shunichi09/pythonlinearnonlinearcontrol/blob/eb0bf0c78251e372a9db9fa6a888583a11d0ee12/PythonLinearNonlinearControl/envs/cartpole.py#L60-L120
import numpy as np from matplotlib.axes import Axes from .env import Env from ..plotters.plot_objs import square class CartPoleEnv(Env): def __init__(self): self.config = {"state_size": 4, "input_size": 1, "dt": 0.02, "max_step": 500, ...
MIT License
readthedocs/readthedocs.org
readthedocs/doc_builder/base.py
BaseBuilder.run
python
def run(self, *args, **kwargs): return self.build_env.run(*args, **kwargs)
Proxy run to build environment.
https://github.com/readthedocs/readthedocs.org/blob/2cff8376f0ef8f25ae6d8763bdbec86f47e33ab9/readthedocs/doc_builder/base.py#L142-L144
import logging import os import shutil from functools import wraps from readthedocs.projects.models import Feature log = logging.getLogger(__name__) def restoring_chdir(fn): @wraps(fn) def decorator(*args, **kw): try: path = os.getcwd() return fn(*args, **kw) finally: ...
MIT License
ganeti/ganeti
lib/storage/container.py
_LvmBase._RunListCommand
python
def _RunListCommand(args): result = utils.RunCmd(args) if result.failed: raise errors.StorageError("Failed to run %r, command output: %s" % (args[0], result.output)) return result.stdout
Run LVM command.
https://github.com/ganeti/ganeti/blob/4d21019c72cba4d746f5d17ca22098f4c7682e9c/lib/storage/container.py#L314-L324
import logging from ganeti import errors from ganeti import constants from ganeti import utils def _ParseSize(value): return int(round(float(value), 0)) class _Base(object): def List(self, name, fields): raise NotImplementedError() def Modify(self, name, changes): if changes: raise errors.Programme...
BSD 2-Clause Simplified License
flapjax/flapjack-cogs
blizzard/blizzard.py
Blizzard.battletag
python
async def battletag(self, ctx): pass
Change your battletag settings.
https://github.com/flapjax/flapjack-cogs/blob/8a1a20f86fec36f60899dbbf91f2f77eee191786/blizzard/blizzard.py#L199-L201
import asyncio import re from copy import copy from numbers import Number import aiohttp import bleach import discord from bs4 import BeautifulSoup from redbot.core import Config, checks, commands from discord.ext.commands import formatter class Blizzard(commands.Cog): default_global_settings = { "notes_for...
MIT License
project-rig/nengo_spinnaker
nengo_spinnaker/operators/lif.py
EnsembleLIF.make_vertices
python
def make_vertices(self, model, n_steps): params = model.params[self.ensemble] self.regions = ens_regions = dict() incoming = model.get_signals_to_object(self) assert EnsembleInputPort.neurons not in incoming incoming_modulatory = {port: signal for (...
Construct the data which can be loaded into the memory of a SpiNNaker machine.
https://github.com/project-rig/nengo_spinnaker/blob/8afde11ee265c070e7003f25d3c06f5138ec3b05/nengo_spinnaker/operators/lif.py#L86-L450
import collections import enum import itertools import math from nengo.base import ObjView from nengo.connection import LearningRule from nengo.learning_rules import PES, Voja import numpy as np from rig.place_and_route import Cores, SDRAM from rig.place_and_route.constraints import SameChipConstraint from six import i...
MIT License
neuralensemble/python-neo
neo/io/klustakwikio.py
FilenameParser.read_filenames
python
def read_filenames(self, typestring='fet'): all_filenames = glob.glob(os.path.join(self.dirname, '*')) d = {} for v in all_filenames: split_fn = os.path.split(v)[1] m = glob.re.search((r'^(\w+)\.%s\.(\d+)$' % typestring), split_fn) if m is not None: ...
Returns filenames in the data directory matching the type. Generally, `typestring` is one of the following: 'fet', 'clu', 'spk', 'res' Returns a dict {group_number: filename}, e.g.: { 0: 'basename.fet.0', 1: 'basename.fet.1', 2: 'basename.fet.2...
https://github.com/neuralensemble/python-neo/blob/889060c022a56b9c3122afee68cbd5d83e4abe78/neo/io/klustakwikio.py#L426-L464
import glob import logging import os.path import shutil import numpy as np try: import matplotlib.mlab as mlab except ImportError as err: HAVE_MLAB = False MLAB_ERR = err else: HAVE_MLAB = True MLAB_ERR = None from neo.io.baseio import BaseIO from neo.core import Block, Segment, Group, SpikeTrain cl...
BSD 3-Clause New or Revised License
paddlepaddle/paddle
python/paddle/fluid/contrib/mixed_precision/fp16_utils.py
fp16_guard
python
def fp16_guard(): with framework.name_scope(prefix=_fp16_guard_pattern): yield
As for the pure fp16 training, if users set `use_fp16_guard` to True, only those ops created in the context manager `fp16_guard` will be transformed as float16 type. Examples: .. code-block:: python import numpy as np import paddle import paddle.nn.functional as...
https://github.com/paddlepaddle/paddle/blob/056b87414880e0520bb4560fc40d5b62db9c5175/python/paddle/fluid/contrib/mixed_precision/fp16_utils.py#L334-L357
from __future__ import print_function from ... import core from ... import framework from ... import layers from ... import global_scope from ...log_helper import get_logger from ...wrapped_decorator import signature_safe_contextmanager from .fp16_lists import AutoMixedPrecisionLists import collections import logging i...
Apache License 2.0
mklan/nx-rom-market
lib/python3.5/enum.py
EnumMeta.__call__
python
def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1): if names is None: return cls.__new__(cls, value) return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start)
Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum('Color', names='red green blue')). When used for the functional A...
https://github.com/mklan/nx-rom-market/blob/33613d2177b63df9e0568038ffdf1dd91ad334d8/lib/python3.5/enum.py#L215-L243
import sys from collections import OrderedDict from types import MappingProxyType, DynamicClassAttribute __all__ = ['Enum', 'IntEnum', 'unique'] def _is_descriptor(obj): return ( hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__')) def _is_dunder(name...
MIT License
michaelaquilina/python-tools
lib/jedi/api/classes.py
Completion.description
python
def description(self): if self._definition is None: return '' t = self.type if t == 'statement' or t == 'import': desc = self._definition.get_code() else: desc = '.'.join(unicode(p) for p in self._path()) line = '' if self.in_builtin_module els...
Provide a description of the completion object.
https://github.com/michaelaquilina/python-tools/blob/2fbee20f9ce286ba55050adafcea8bb43c0922b3/lib/jedi/api/classes.py#L421-L432
import warnings from itertools import chain import re from jedi._compatibility import unicode, use_metaclass from jedi import settings from jedi import common from jedi.parser import tree from jedi.evaluate.cache import memoize_default, CachedMetaClass from jedi.evaluate import representation as er from jedi.evaluate i...
MIT License
tensorflow/transform
tensorflow_transform/graph_context.py
TFGraphContext.get_module_to_export
python
def get_module_to_export(cls) -> Optional[tf.Module]: return cls._get_current_state().module_to_export
Retrieves the value of module_to_export. None if called outside a TFGraphContext scope. Returns: A tf.Module object
https://github.com/tensorflow/transform/blob/6349d7f6d847cb8979f31b9b315981d79ffba3e5/tensorflow_transform/graph_context.py#L121-L129
import os import threading from typing import Any, Dict, Optional import tensorflow as tf from tfx_bsl.types import tfx_namedtuple class TFGraphContext: class _State( tfx_namedtuple.namedtuple('_State', [ 'module_to_export', 'temp_dir', 'evaluated_replacements', ])): @cla...
Apache License 2.0
verashira/tspnet
fairseq/models/transformer_from_sign.py
TransformerEncoderSign.upgrade_state_dict_named
python
def upgrade_state_dict_named(self, state_dict, name): if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): weights_key = '{}.embed_positions.weights'.format(name) if weights_key in state_dict: logger.info('deleting {0}'.format(weights_key)) ...
Upgrade a (possibly old) state dict for new versions of fairseq.
https://github.com/verashira/tspnet/blob/ee454165dcc61cdbbff19565364e2221727ed2b8/fairseq/models/transformer_from_sign.py#L434-L452
from collections import namedtuple import logging import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq import options, utils from fairseq.models import ( FairseqEncoder, FairseqIncrementalDecoder, FairseqEncoderDecoderModel, register_model, register_model_archi...
MIT License
drexly/openhgsenti
lib/django/contrib/gis/gdal/prototypes/geom.py
pnt_func
python
def pnt_func(f): return double_output(f, [c_void_p, c_int])
For accessing point information.
https://github.com/drexly/openhgsenti/blob/d7806f58c81127d32091d9875a99ac13aef94a8a/lib/django/contrib/gis/gdal/prototypes/geom.py#L21-L23
from ctypes import POINTER, c_char_p, c_double, c_int, c_void_p from django.contrib.gis.gdal.envelope import OGREnvelope from django.contrib.gis.gdal.libgdal import lgdal from django.contrib.gis.gdal.prototypes.errcheck import check_envelope from django.contrib.gis.gdal.prototypes.generation import ( const_string_o...
Apache License 2.0
swd-bits-goa/swd_django
swd/main/models.py
VacationDatesFill.check_start_end_dates_in_range
python
def check_start_end_dates_in_range(self, dateTimeStart, dateTimeEnd): first_cond = self.check_date_in_range(dateTimeStart) and self.check_date_in_range(dateTimeEnd) return first_cond and dateTimeStart < dateTimeEnd
Checks whether both start and end date time objects are in range and start date less than end date params: dateTimeStart, dateTimeEnd: datetime object
https://github.com/swd-bits-goa/swd_django/blob/1fafb657f0a7cb7f7ac66bde789eeb336f8df065/swd/main/models.py#L580-L590
from django.db import models from django.contrib.auth.models import User import os import hashlib import re from django.utils import timezone from datetime import datetime from datetime import date try: from tools.dev_info import SALT_IMG as SALT except ModuleNotFoundError: SALT = '1234567890' MESS_CHOICES = ( ...
MIT License
yfauser/planespotter
app-server/app/lib/python2.7/site-packages/click/termui.py
echo_via_pager
python
def echo_via_pager(text, color=None): color = resolve_color_default(color) if not isinstance(text, string_types): text = text_type(text) from ._termui_impl import pager return pager(text + '\n', color)
This function takes a text and shows it via an environment specific pager on stdout. .. versionchanged:: 3.0 Added the `color` flag. :param text: the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection.
https://github.com/yfauser/planespotter/blob/d400216502b6b5592a4889eb9fa277b2ddb75f9b/app-server/app/lib/python2.7/site-packages/click/termui.py#L198-L213
import os import sys import struct from ._compat import raw_input, text_type, string_types, isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN from .utils import echo from .exceptions import Abort, UsageError from .types import convert_type from .globals import resolve_color_default visible_prompt_func = ra...
MIT License
tuturto/pyherc
src/pyherc/test/builders/item.py
ItemBuilder.with_required_ammunition_type
python
def with_required_ammunition_type(self, ammunition_type): if self.weapon_data is None: self.weapon_data = WeaponData() self.weapon_data.ammunition_type = ammunition_type return self
Configure type of ammunition this weapon requires :param ammunition_type: type of ammunition this weapon requires :type ammunition_type: string
https://github.com/tuturto/pyherc/blob/4e7c72a4d80d335f7d3c48cecac96cd7105acac4/src/pyherc/test/builders/item.py#L135-L145
from pyherc.data import Item from pyherc.data.effects import EffectsCollection from pyherc.data.item import (AmmunitionData, ArmourData, WeaponData, TrapData, BootsData) class ItemBuilder(): def __init__(self): super().__init__() self.name = 'prototype' self.app...
MIT License
oscaar/oscaar
oscaar/dataBank.py
dataBank.outOfTransit
python
def outOfTransit(self): return (self.getTimes() < self.ingress) + (self.getTimes() > self.egress)
Boolean array where `True` are the times in `getTimes()` that are before ingress or after egress. Returns ------- List of bools
https://github.com/oscaar/oscaar/blob/5c953570d870c8b855ee388436aa360bde70869a/oscaar/dataBank.py#L436-L446
import numpy as np import pyfits from matplotlib import pyplot as plt from scipy import optimize from glob import glob import os import re import oscaar import mathMethods import sys import systematics oscaarpath = os.path.dirname(os.path.abspath(oscaar.__file__)) oscaarpathplus = os.path.join(oscaarpath,'extras') clas...
MIT License
derfies/panda3d-editor
src/pandaEditor/game/nodes/manager.py
Manager.get_type_string
python
def get_type_string(self, comp): if hasattr(comp.__class__, 'cType'): return comp.cType type_str = type(comp).__name__ if type_str == 'NodePath': type_str = comp.node().get_tag(TAG_NODE_TYPE) if not type_str: type_str = type(comp.node()).__name...
Return the type of the component as a string. Components are identified in the following method (in order): - If the component has the class variable 'cType' then this string will be used as the type. - Use the component's type's name as the type. - If this is 'NodePath...
https://github.com/derfies/panda3d-editor/blob/a50939bd4bfa5c22d27a9ddee090717e8d95f404/src/pandaEditor/game/nodes/manager.py#L115-L135
from game.nodes.actor import Actor from game.nodes.base import Base from game.nodes.bullet import ( BulletBoxShape, BulletCapsuleShape, BulletDebugNode, BulletPlaneShape, BulletRigidBodyNode, BulletSphereShape, BulletWorld, ) from game.nodes.camera import Camera from game.nodes.collision imp...
MIT License
sony/nnabla
python/src/nnabla/backward_function/r_div_scalar.py
r_div_scalar_backward
python
def r_div_scalar_backward(inputs, val=1): dy = inputs[0] x0 = inputs[1] dx0 = - dy * val / x0 ** 2 return dx0
Args: inputs (list of nn.Variable): Incomming grads/inputs to/of the forward function. kwargs (dict of arguments): Dictionary of the corresponding function arguments. Return: list of Variable: Return the gradients wrt inputs of the corresponding function.
https://github.com/sony/nnabla/blob/fef9b6bca02a002de880a13f3196df14369445f4/python/src/nnabla/backward_function/r_div_scalar.py#L16-L28
Apache License 2.0
cihai/cihai
cihai/config.py
Configurator.write
python
def write(self, **updates): if updates: self._data.update(**updates) pass
If no delta is created from DEFAULT, it not write. If file doesn't exist, it will create.
https://github.com/cihai/cihai/blob/650e865655c0c0b15f39a44a8b24d69761acbb11/cihai/config.py#L112-L120
import os from appdirs import AppDirs from ._compat import string_types def expand_config(d, dirs): context = { 'user_cache_dir': dirs.user_cache_dir, 'user_config_dir': dirs.user_config_dir, 'user_data_dir': dirs.user_data_dir, 'user_log_dir': dirs.user_log_dir, 'site_config...
MIT License
jest-community/jest-pytest
src/__tests__/integration/home-assistant/homeassistant/components/lock/verisure.py
VerisureDoorlock.available
python
def available(self): return hub.get_first( "$.doorLockStatusList[?(@.deviceLabel=='%s')]", self._device_label) is not None
Return True if entity is available.
https://github.com/jest-community/jest-pytest/blob/b197b0b31e3ca5c411202d97583cbd2d2b0b92e9/src/__tests__/integration/home-assistant/homeassistant/components/lock/verisure.py#L56-L60
import logging from time import sleep from time import time from homeassistant.components.verisure import HUB as hub from homeassistant.components.verisure import (CONF_LOCKS, CONF_CODE_DIGITS) from homeassistant.components.lock import LockDevice from homeassistant.const import ( ATTR_CODE, STATE_LOCKED, STATE_UNKN...
MIT License
tyohei/chainerkfac
chainerkfac/communicators/pure_nccl_communicator.py
PureNcclCommunicator.all_gather_v_arrays
python
def all_gather_v_arrays(self, arrays, stream=None, debug=False): if stream is None: stream = chainer.cuda.Stream.null local_rank = self.rank self._init_comms() nccl_comm = self.nccl_comm nelems = _get_divideable_nelems(nccl_comm, _utility.get_nelems(arrays)) n...
Executes All-Gather-V. 0. memset: gbuf_A <- (zero) 1. pack: gbuf_A <- arrays 2. send: .... <- gbuf_A 3. recv: gbuf_B <- .... 4. unpack: arrays <- gbuf_B
https://github.com/tyohei/chainerkfac/blob/99e88396268e8b7d099fdb6bbf54e309e98293c8/chainerkfac/communicators/pure_nccl_communicator.py#L150-L218
import math import cupy import numpy as np import chainer from chainermn.communicators import _communication_utility from chainermn.communicators import _memory_utility from chainermn import nccl from chainerkfac.communicators import _utility from chainerkfac.communicators import base class PureNcclCommunicator(base.Kf...
MIT License
mabuchilab/qnet
src/qnet/algebra/core/circuit_algebra.py
SLH.space
python
def space(self): args_spaces = (self.S.space, self.L.space, self.H.space) return ProductSpace.create(*args_spaces)
Total Hilbert space
https://github.com/mabuchilab/qnet/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/circuit_algebra.py#L368-L371
import os import re from abc import ABCMeta, abstractmethod from collections import OrderedDict from functools import reduce import numpy as np import sympy from sympy import I from sympy import Matrix as SympyMatrix from sympy import symbols, sympify from .abstract_algebra import ( Expression, Operation, substitut...
MIT License
nrel/floris
floris/tools/optimization/scipy/power_density_1D.py
PowerDensityOptimization1D.optimize
python
def optimize(self): print("=====================================================") print("Optimizing turbine layout...") print("Number of parameters to optimize = ", len(self.x0)) print("=====================================================") opt_vars_norm = self._optimize() ...
This method finds the optimized layout of wind turbines for power production given the provided frequencies of occurance of wind conditions (wind speed, direction). Returns: opt_locs (iterable): A list of the optimized x, y locations of each turbine (m).
https://github.com/nrel/floris/blob/ef4934ec7feb7afd2615772d364a1eaa28db93e9/floris/tools/optimization/scipy/power_density_1D.py#L218-L247
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize from .optimization import Optimization class PowerDensityOptimization1D(Optimization): def __init__( self, fi, wd, ws, freq, AEP_initial, x0=None, bnds=None, ...
Apache License 2.0
dtuwindenergy/pywake
py_wake/examples/data/iea37/iea37_aepcalc.py
calcAEP
python
def calcAEP(turb_coords, wind_freq, wind_speed, wind_dir, turb_diam, turb_ci, turb_co, rated_ws, rated_pwr): num_bins = len(wind_freq) pwr_produced = np.zeros(num_bins) for i in range(num_bins): pwr_produced[i] = DirPower(turb_coords, wind_dir[i], wind_speed, ...
Calculate the wind farm AEP.
https://github.com/dtuwindenergy/pywake/blob/ab02a41b5b4ebe7d17877e265ae64d2902324298/py_wake/examples/data/iea37/iea37_aepcalc.py#L116-L135
from __future__ import print_function import numpy as np import yaml from math import radians as DegToRad coordinate = np.dtype([('x', 'f8'), ('y', 'f8')]) def WindFrame(turb_coords, wind_dir_deg): wind_dir_deg = 270. - wind_dir_deg wind_dir_rad = DegToRad(wind_dir_deg) c...
MIT License
lobocv/crashreporter
crashreporter/tools.py
analyze_traceback
python
def analyze_traceback(tb, inspection_level=None, limit=None): info = [] tb_level = tb extracted_tb = traceback.extract_tb(tb, limit=limit) for ii, (filepath, line, module, code) in enumerate(extracted_tb): func_source, func_lineno = inspect.getsourcelines(tb_level.tb_frame) d = {"File": ...
Extract trace back information into a list of dictionaries. :param tb: traceback :return: list of dicts containing filepath, line, module, code, traceback level and source code for tracebacks
https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/tools.py#L155-L183
__author__ = 'calvin' import inspect import logging import re import traceback from types import FunctionType, MethodType, ModuleType, BuiltinMethodType, BuiltinFunctionType try: import numpy as np _NUMPY_INSTALLED = True except ImportError: _NUMPY_INSTALLED = False obj_ref_regex = re.compile("[A-z]+[0-9]*\...
MIT License
online-ml/river
river/base/classifier.py
Classifier.predict_one
python
def predict_one(self, x: dict) -> base.typing.ClfTarget: y_pred = self.predict_proba_one(x) if y_pred: return max(y_pred, key=y_pred.get) return None
Predict the label of a set of features `x`. Parameters ---------- x A dictionary of features. Returns ------- The predicted label.
https://github.com/online-ml/river/blob/842f7c5be5574e62a3aab0b46d996eb5f1d73beb/river/base/classifier.py#L53-L72
import abc import typing import pandas as pd from river import base from . import estimator class Classifier(estimator.Estimator): @abc.abstractmethod def learn_one(self, x: dict, y: base.typing.ClfTarget, **kwargs) -> "Classifier": def predict_proba_one(self, x: dict) -> typing.Dict[base.typing.ClfTarget, ...
BSD 3-Clause New or Revised License
catalyst-team/catalyst
catalyst/contrib/nn/criterion/wing.py
WingLoss.forward
python
def forward(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: loss = self.loss_fn(outputs, targets) return loss
Args: @TODO: Docs. Contribution is welcome.
https://github.com/catalyst-team/catalyst/blob/a6fc305eaddc499c17584824794fa8d006072842/catalyst/contrib/nn/criterion/wing.py#L71-L77
from functools import partial import math import torch from torch import nn def wing_loss( outputs: torch.Tensor, targets: torch.Tensor, width: int = 5, curvature: float = 0.5, reduction: str = "mean", ) -> torch.Tensor: diff_abs = (targets - outputs).abs() loss = diff_abs.clone() idx_sm...
Apache License 2.0
brain-research/data-linter
linters.py
DuplicateExampleDetector._lint
python
def _lint(self, examples): feature_names = sorted(f.name for f in self._stats.features) tuplize = utils.example_tuplizer(feature_names, denan=True) duplicates = ( examples | 'Tuplize' >> beam.Map(lambda x: (tuplize(x), x)) | 'CollectDuplicates' >> beam.GroupByKey() | 'Example...
Returns the `PTransform` for the DuplicateExampleDetector linter. Args: examples: A `PTransform` that yields a `PCollection` of `tf.Example`s. Returns: A `PTransform` that yields a `LintResult` of the format warnings: [num_duplicates] lint_sample: [ features: [sample duplicates...]...
https://github.com/brain-research/data-linter/blob/ef62043ae1a2022d48b3c1e83171cfd500a11524/linters.py#L713-L756
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import datetime import itertools import re import apache_beam as beam import dateutil.parser import numpy as np import scipy.stats import six import lint_result_pb2 import data_linter_utils as...
Apache License 2.0
diofant/diofant
diofant/core/mul.py
_unevaluated_Mul
python
def _unevaluated_Mul(*args): args = list(args) newargs = [] ncargs = [] co = S.One while args: a = args.pop() if a.is_Mul: c, nc = a.args_cnc() args.extend(c) if nc: ncargs.append(Mul._from_args(nc)) elif a.is_Number: ...
Return a well-formed unevaluated Mul: Numbers are collected and put in slot 0, any arguments that are Muls will be flattened, and args are sorted. Use this when args have changed but you still want to return an unevaluated Mul. Examples ======== >>> a = _unevaluated_Mul(*[Float(3.0), x, Intege...
https://github.com/diofant/diofant/blob/05c50552b0e0533f1dbf2ec05e65b6c45b7e2c11/diofant/core/mul.py#L27-L75
from collections import defaultdict from ..utilities import default_sort_key from .basic import Basic from .cache import cacheit from .logic import _fuzzy_group, fuzzy_and from .operations import AssocOp from .singleton import S from .sympify import sympify class NC_Marker: is_Order = False is_Mul = False i...
BSD 3-Clause New or Revised License
google-research/federated
reconstruction/movielens/movielens_dataset.py
create_user_split_np_arrays
python
def create_user_split_np_arrays( ratings_df: pd.DataFrame, max_examples_per_user: Optional[int] = None, train_fraction: float = 0.8, val_fraction: float = 0.1, ) -> Tuple[ServerDataArray, ServerDataArray, ServerDataArray]: num_users = len(set(ratings_df.UserID)) all_user_examples = [] for user_id ...
Creates arrays for train/val/test user data for server-side evaluation. Loads a server-side version of the MovieLens dataset that contains ratings from users partitioned into train/val/test populations. Note that unlike `create_tf_datasets` and `create_tf_dataset_for_user`, the output data does not generate ba...
https://github.com/google-research/federated/blob/909953fa8945cfac01328e0a6d878e1dc0376c3c/reconstruction/movielens/movielens_dataset.py#L467-L569
import collections import io import os from typing import Any, List, Optional, Tuple import zipfile import numpy as np import pandas as pd import requests import tensorflow as tf MOVIELENS_1M_URL = "http://files.grouplens.org/datasets/movielens/ml-1m.zip" DEFAULT_DATA_DIRECTORY = "/tmp" NP_RANDOM_SEED = 42 ServerDataAr...
Apache License 2.0
adafruit/adafruit_circuitpython_esp32spi
adafruit_esp32spi/PWMOut.py
PWMOut._is_deinited
python
def _is_deinited(self): if self._pwm_pin is None: raise ValueError( "PWMOut Object has been deinitialized and can no longer " "be used. Create a new PWMOut object." )
Checks if PWMOut object has been previously de-initalized
https://github.com/adafruit/adafruit_circuitpython_esp32spi/blob/7b048134c49c6fb45b33fab4534114b8a89e4d29/adafruit_esp32spi/PWMOut.py#L53-L59
class PWMOut: ESP32_PWM_PINS = set( [0, 1, 2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33] ) def __init__( self, esp, pwm_pin, *, frequency=500, duty_cycle=0, variable_frequency=False ): if pwm_pin in self.ESP32_PWM_PINS: self._pwm_pin = pwm_p...
MIT License
wrr/wwwhisper
wwwhisper_auth/models.py
User.login_successful
python
def login_successful(self): return
Must be called after successful login.
https://github.com/wrr/wwwhisper/blob/38a55dd9c828fbb1b5a8234ea3ddf2242e684983/wwwhisper_auth/models.py#L239-L243
from django.contrib.auth.models import AbstractBaseUser from django.db import connection from django.db import models from django.db import IntegrityError from django.forms import ValidationError from django.utils import timezone from functools import wraps from wwwhisper_auth import url_utils from wwwhisper_auth impo...
MIT License
pmatigakis/huginn
huginn/rest.py
FlightControlsResource.get
python
def get(self): flight_controls_data = { "aileron": self.controls.aileron, "elevator": self.controls.elevator, "rudder": self.controls.rudder, "throttle": self.controls.throttle, } return flight_controls_data
returns the flight controls values
https://github.com/pmatigakis/huginn/blob/a35fec1df844eec05c7ab97a7c70c750e43a9f08/huginn/rest.py#L273-L282
from logging import getLogger from flask import request from flask_restful import Resource, reqparse, marshal_with, abort from tinydb import Query from huginn.schemas import (AccelerationsSchema, VelocitiesSchema, OrientationSchema, AtmosphereShema, ForcesSchema, ...
BSD 3-Clause New or Revised License
antoineco/kovhernetes
kovh/userdata.py
UserData.gen_kubelet_unit
python
def gen_kubelet_unit(self, roles): labels = ("node-role.kubernetes.io/{}=''".format(r) for r in roles) self.add_sunits([ { 'name': 'kubelet.service', 'enable': True, 'contents': ( files['kubelet'].decode() ...
Generate kubelet service unit
https://github.com/antoineco/kovhernetes/blob/bb8a7fefede33e24c9946633ce6e17a6bdcaff77/kovh/userdata.py#L141-L155
from gzip import compress from urllib.parse import quote from pkg_resources import resource_string from json import loads, dumps from collections import OrderedDict def res_plain(resource): return resource_string(__name__, resource) def res_gzip(resource): return compress(res_plain(resource...
Apache License 2.0
crm416/semantic
semantic/dates.py
DateService.extractDates
python
def extractDates(self, inp): def merge(param): day, time = param if not (day or time): return None if not day: return time if not time: return day return datetime.datetime( day.year, day.m...
Extract semantic date information from an input string. In effect, runs both parseDay and parseTime on the input string and merges the results to produce a comprehensive datetime object. Args: inp (str): Input string to be parsed. Returns: A list of date...
https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L349-L378
import re import datetime try: from itertools import zip_longest except: from itertools import izip_longest as zip_longest from .numbers import NumberService class DateService(object): def __init__(self, tz=None, now=None): self.tz = tz if now: self.now = now else: ...
MIT License
rjt1990/pyflux
pyflux/ssm/ndynlin.py
NDynReg._ss_matrices
python
def _ss_matrices(self,beta): T = np.identity(self.state_no) Z = self.X R = np.identity(self.state_no) Q = np.identity(self.state_no) for i in range(0,self.state_no): Q[i][i] = self.latent_variables.z_list[i].prior.transform(beta[i]) return T, Z, R, Q
Creates the state space matrices required Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- T, Z, R, Q : np.array State space matrices used in KFS algorithm
https://github.com/rjt1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/ndynlin.py#L345-L368
import sys if sys.version_info < (3,): range = xrange import numpy as np import pandas as pd import scipy.stats as ss from scipy import optimize from .. import inference as ifr from .. import families as fam from .. import output as op from .. import tsm as tsm from .. import data_check as dc from .. import covaria...
BSD 3-Clause New or Revised License
iristyle/chocolateypackages
EthanBrown.SublimeText2.EditorPackages/tools/PackageCache/SmartMarkdown/headline_move.py
HeadlineMoveCommand.run
python
def run(self, edit, forward=True, same_level=True): new_sel = [] if same_level: level_type = headline.MATCH_PARENT else: level_type = headline.MATCH_ANY for region in self.view.sel(): if same_level: _, level = headline.headline_and_leve...
Move between headlines, forward or backward. If same_level is true, only move to headline with the same level or higher level.
https://github.com/iristyle/chocolateypackages/blob/8c9833710577de6db6e8b1db5d9196e19e19d117/EthanBrown.SublimeText2.EditorPackages/tools/PackageCache/SmartMarkdown/headline_move.py#L20-L55
import sublime import sublime_plugin try: from . import headline from .utilities import is_region_void except ValueError: import headline from utilities import is_region_void class HeadlineMoveCommand(sublime_plugin.TextCommand):
MIT License
scikit-hep/uproot4
src/uproot/behaviors/TAxis.py
AxisTraits.discrete
python
def discrete(self): fNbins = self._axis.member("fNbins") fLabels = self._axis.member("fLabels", none_if_missing=True) return fLabels is not None and len(fLabels) == fNbins
True if bins are discrete: if they have string-valued labels.
https://github.com/scikit-hep/uproot4/blob/e0db77a2a10d701cb48f72e9f0d7867e1589572d/src/uproot/behaviors/TAxis.py#L39-L45
from __future__ import absolute_import try: from collections.abc import Sequence except ImportError: from collections import Sequence import numpy class AxisTraits(object): def __init__(self, axis): self._axis = axis def __repr__(self): return "AxisTraits({0})".format(repr(self._axis)) ...
BSD 3-Clause New or Revised License
michaelhush/m-loop
mloop/utilities.py
_generate_legend_labels
python
def _generate_legend_labels(param_indices, all_param_names): labels = [] for index in param_indices: label = str(index) name = all_param_names[index] if name: label = label + ': {name}'.format(name=name) labels.append(label) return labels
Generate a list of labels for the legend of a plot. This is a helper function for visualization methods, used to generate the labels in legends for plots that show the values for optimization parameters. The label has the parameter's index and, if available, a colon followed by the parameter's name...
https://github.com/michaelhush/m-loop/blob/24e0e67d993b81dcc319d7cc6390c3345036fc67/mloop/utilities.py#L417-L449
from __future__ import absolute_import, division, print_function __metaclass__ = type import scipy.io as si import pickle import logging import datetime import sys import os import numpy as np import numpy.random as nr import base64 import mloop python_version = sys.version_info[0] if python_version < 3: import Que...
MIT License
nccgroup/libptmalloc
libptmalloc/frontend/commands/gdb/pthelp.py
pthelp.invoke
python
def invoke(self, arg, from_tty): pu.print_header("{:<20}".format("pthelp"), end="") print("List all libptmalloc commands") for cmd in self.cmds: if cmd.parser != None: description = cmd.parser.description.split("\n")[0] elif cmd.description != None: ...
Inherited from gdb.Command See https://sourceware.org/gdb/current/onlinedocs/gdb/Commands-In-Python.html Print the usage of all the commands
https://github.com/nccgroup/libptmalloc/blob/e9011393db1ea79b769dcf5f52bd1170a367b304/libptmalloc/frontend/commands/gdb/pthelp.py#L32-L51
from __future__ import print_function import sys import logging from libptmalloc.frontend import printutils as pu from libptmalloc.ptmalloc import malloc_state as ms from libptmalloc.ptmalloc import ptmalloc as pt from libptmalloc.frontend import helpers as h from libptmalloc.frontend.commands.gdb import ptcmd log = lo...
MIT License
universitadellacalabria/uniticket
uni_ticket/views/management.py
manage_closed_ticket_url
python
def manage_closed_ticket_url(request, structure_slug): structure = get_object_or_404(OrganizationalStructure, slug=structure_slug) user_type = get_user_type(request.user, structure) return redirect('uni_ticket:{}_closed_ticket'.format(user_type), struct...
Makes URL redirect to closed ticket page depending of user role :type structure_slug: String :param structure_slug: slug of structure to manage :return: redirect
https://github.com/universitadellacalabria/uniticket/blob/b7c6e9b793eda273038a6339f6dfdfc3e3b5a344/uni_ticket/views/management.py#L69-L83
import json import logging import os import zipfile from django.conf import settings from django.contrib import messages from django.contrib.admin.models import LogEntry, ADDITION, CHANGE from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import login_required fr...
Apache License 2.0
bigmlcom/bigmler
bigmler/checkpoint.py
is_evaluation_created
python
def is_evaluation_created(path): evaluation_id = None try: with open("%s%sevaluation" % (path, os.sep)) as evaluation_file: evaluation_id = evaluation_file.readline().strip() try: evaluation_id = bigml.api.get_evaluation_id(evaluation_id) return Tr...
Checks existence and reads the evaluation id from the evaluation file in the path directory
https://github.com/bigmlcom/bigmler/blob/91973ca1e752954302bf26bb22aa6874dc34ce69/bigmler/checkpoint.py#L119-L134
import os import bigml.api from bigml.util import console_log from bigmler.utils import log_message def is_source_created(path, suffix=""): source_id = None try: with open("%s%ssource%s" % (path, os.sep, suffix)) as source_file: source_id = source_file.readline().strip() try: ...
Apache License 2.0