repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
pybel/pybel
src/pybel/struct/graph.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L733-L738
def get_equivalent_nodes(self, node: BaseEntity) -> Set[BaseEntity]: """Get a set of equivalent nodes to this node, excluding the given node.""" if isinstance(node, BaseEntity): return set(self.iter_equivalent_nodes(node)) return set(self.iter_equivalent_nodes(node))
[ "def", "get_equivalent_nodes", "(", "self", ",", "node", ":", "BaseEntity", ")", "->", "Set", "[", "BaseEntity", "]", ":", "if", "isinstance", "(", "node", ",", "BaseEntity", ")", ":", "return", "set", "(", "self", ".", "iter_equivalent_nodes", "(", "node"...
Get a set of equivalent nodes to this node, excluding the given node.
[ "Get", "a", "set", "of", "equivalent", "nodes", "to", "this", "node", "excluding", "the", "given", "node", "." ]
python
train
49.833333
kajala/django-jutil
jutil/dates.py
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/dates.py#L105-L119
def next_month(today: datetime=None, tz=None): """ Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: toda...
[ "def", "next_month", "(", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utcnow", "(", ")", "begin", "=", "datetime", "(", "day", "=", "1", ",", "month", ...
Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
[ "Returns", "next", "month", "begin", "(", "inclusive", ")", "and", "end", "(", "exclusive", ")", ".", ":", "param", "today", ":", "Some", "date", "in", "the", "month", "(", "defaults", "current", "datetime", ")", ":", "param", "tz", ":", "Timezone", "(...
python
train
44.6
timothydmorton/isochrones
isochrones/observation.py
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L1075-L1089
def trim(self): """ Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is """ # Only allow leaves to stay on list (highest-resolution) level return for l in self._levels[-2::-1]: for n in l: ...
[ "def", "trim", "(", "self", ")", ":", "# Only allow leaves to stay on list (highest-resolution) level", "return", "for", "l", "in", "self", ".", "_levels", "[", "-", "2", ":", ":", "-", "1", "]", ":", "for", "n", "in", "l", ":", "if", "n", ".", "is_leaf"...
Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is
[ "Trims", "leaves", "from", "tree", "that", "are", "not", "observed", "at", "highest", "-", "resolution", "level" ]
python
train
27.866667
acutesoftware/AIKIF
scripts/examples/gui_view_world.py
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/scripts/examples/gui_view_world.py#L98-L105
def show_grid_from_file(self, fname): """ reads a saved grid file and paints it on the canvas """ with open(fname, "r") as f: for y, row in enumerate(f): for x, val in enumerate(row): self.draw_cell(y, x, val)
[ "def", "show_grid_from_file", "(", "self", ",", "fname", ")", ":", "with", "open", "(", "fname", ",", "\"r\"", ")", "as", "f", ":", "for", "y", ",", "row", "in", "enumerate", "(", "f", ")", ":", "for", "x", ",", "val", "in", "enumerate", "(", "ro...
reads a saved grid file and paints it on the canvas
[ "reads", "a", "saved", "grid", "file", "and", "paints", "it", "on", "the", "canvas" ]
python
train
35.25
apache/incubator-mxnet
example/ctc/multiproc_data.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/multiproc_data.py#L90-L99
def _init_proc(self): """Start processes if not already started""" if not self.proc: self.proc = [ mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn)) for i in range(self.num_proc) ] self.alive.value = True ...
[ "def", "_init_proc", "(", "self", ")", ":", "if", "not", "self", ".", "proc", ":", "self", ".", "proc", "=", "[", "mp", ".", "Process", "(", "target", "=", "self", ".", "_proc_loop", ",", "args", "=", "(", "i", ",", "self", ".", "alive", ",", "...
Start processes if not already started
[ "Start", "processes", "if", "not", "already", "started" ]
python
train
36.5
cuihantao/andes
andes/main.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/main.py#L106-L126
def preamble(): """ Log the Andes command-line preamble at the `logging.INFO` level Returns ------- None """ from . import __version__ as version logger.info('ANDES {ver} (Build {b}, Python {p} on {os})' .format(ver=version[:5], b=version[-8:], p=...
[ "def", "preamble", "(", ")", ":", "from", ".", "import", "__version__", "as", "version", "logger", ".", "info", "(", "'ANDES {ver} (Build {b}, Python {p} on {os})'", ".", "format", "(", "ver", "=", "version", "[", ":", "5", "]", ",", "b", "=", "version", "...
Log the Andes command-line preamble at the `logging.INFO` level Returns ------- None
[ "Log", "the", "Andes", "command", "-", "line", "preamble", "at", "the", "logging", ".", "INFO", "level" ]
python
train
27.857143
rackerlabs/simpl
simpl/db/mongodb.py
https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/db/mongodb.py#L507-L511
def delete(self, key): """Delete a document by id.""" assert key, "A key must be supplied for delete operations" self._collection.remove(spec_or_id={'_id': key}) LOG.debug("DB REMOVE: %s.%s", self.collection_name, key)
[ "def", "delete", "(", "self", ",", "key", ")", ":", "assert", "key", ",", "\"A key must be supplied for delete operations\"", "self", ".", "_collection", ".", "remove", "(", "spec_or_id", "=", "{", "'_id'", ":", "key", "}", ")", "LOG", ".", "debug", "(", "...
Delete a document by id.
[ "Delete", "a", "document", "by", "id", "." ]
python
train
49.2
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L320-L326
def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to UTC (with UTC timezone). """ dt = coerce_to_pendulum(dt) tz = get_tz_utc() return dt.in_tz(tz)
[ "def", "convert_datetime_to_utc", "(", "dt", ":", "PotentialDatetimeType", ")", "->", "DateTime", ":", "dt", "=", "coerce_to_pendulum", "(", "dt", ")", "tz", "=", "get_tz_utc", "(", ")", "return", "dt", ".", "in_tz", "(", "tz", ")" ]
Convert date/time with timezone to UTC (with UTC timezone).
[ "Convert", "date", "/", "time", "with", "timezone", "to", "UTC", "(", "with", "UTC", "timezone", ")", "." ]
python
train
31.285714
tehmaze-labs/wright
wright/util.py
https://github.com/tehmaze-labs/wright/blob/79b2d816f541e69d5fb7f36a3c39fa0d432157a6/wright/util.py#L123-L126
def normal_case(name): """Converts "CamelCaseHere" to "camel case here".""" s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name) return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower()
[ "def", "normal_case", "(", "name", ")", ":", "s1", "=", "re", ".", "sub", "(", "r'(.)([A-Z][a-z]+)'", ",", "r'\\1 \\2'", ",", "name", ")", "return", "re", ".", "sub", "(", "r'([a-z0-9])([A-Z])'", ",", "r'\\1 \\2'", ",", "s1", ")", ".", "lower", "(", ")...
Converts "CamelCaseHere" to "camel case here".
[ "Converts", "CamelCaseHere", "to", "camel", "case", "here", "." ]
python
train
47.75
Azure/azure-cosmos-python
azure/cosmos/endpoint_discovery_retry_policy.py
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/endpoint_discovery_retry_policy.py#L61-L101
def ShouldRetry(self, exception): """Returns true if should retry based on the passed-in exception. :param (errors.HTTPFailure instance) exception: :rtype: boolean """ if not self.connection_policy.EnableEndpointDiscovery: return False if self...
[ "def", "ShouldRetry", "(", "self", ",", "exception", ")", ":", "if", "not", "self", ".", "connection_policy", ".", "EnableEndpointDiscovery", ":", "return", "False", "if", "self", ".", "failover_retry_count", ">=", "self", ".", "Max_retry_attempt_count", ":", "r...
Returns true if should retry based on the passed-in exception. :param (errors.HTTPFailure instance) exception: :rtype: boolean
[ "Returns", "true", "if", "should", "retry", "based", "on", "the", "passed", "-", "in", "exception", "." ]
python
train
42.97561
Jajcus/pyxmpp2
pyxmpp2/transport.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L595-L608
def wait_for_writability(self): """ Stop current thread until the channel is writable. :Return: `False` if it won't be readable (e.g. is closed) """ with self.lock: while True: if self._state in ("closing", "closed", "aborted"): re...
[ "def", "wait_for_writability", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "while", "True", ":", "if", "self", ".", "_state", "in", "(", "\"closing\"", ",", "\"closed\"", ",", "\"aborted\"", ")", ":", "return", "False", "if", "self", ".", ...
Stop current thread until the channel is writable. :Return: `False` if it won't be readable (e.g. is closed)
[ "Stop", "current", "thread", "until", "the", "channel", "is", "writable", "." ]
python
valid
34.071429
chemlab/chemlab
chemlab/qc/one.py
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/one.py#L15-L38
def S(a,b): """ Simple interface to the overlap function. >>> from pyquante2 import pgbf,cgbf >>> s = pgbf(1) >>> isclose(S(s,s),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,sc),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,s),1.0) True ...
[ "def", "S", "(", "a", ",", "b", ")", ":", "if", "b", ".", "contracted", ":", "return", "sum", "(", "cb", "*", "S", "(", "pb", ",", "a", ")", "for", "(", "cb", ",", "pb", ")", "in", "b", ")", "elif", "a", ".", "contracted", ":", "return", ...
Simple interface to the overlap function. >>> from pyquante2 import pgbf,cgbf >>> s = pgbf(1) >>> isclose(S(s,s),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,sc),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,s),1.0) True >>> isclose(S(s,sc),1.0...
[ "Simple", "interface", "to", "the", "overlap", "function", ".", ">>>", "from", "pyquante2", "import", "pgbf", "cgbf", ">>>", "s", "=", "pgbf", "(", "1", ")", ">>>", "isclose", "(", "S", "(", "s", "s", ")", "1", ".", "0", ")", "True", ">>>", "sc", ...
python
train
25.25
RudolfCardinal/pythonlib
cardinal_pythonlib/sphinxtools.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L329-L412
def rst_content(self, prefix: str = "", suffix: str = "", heading_underline_char: str = "=", method: AutodocMethod = None) -> str: """ Returns the text contents of an RST file that will automatically document our sou...
[ "def", "rst_content", "(", "self", ",", "prefix", ":", "str", "=", "\"\"", ",", "suffix", ":", "str", "=", "\"\"", ",", "heading_underline_char", ":", "str", "=", "\"=\"", ",", "method", ":", "AutodocMethod", "=", "None", ")", "->", "str", ":", "spacer...
Returns the text contents of an RST file that will automatically document our source file. Args: prefix: prefix, e.g. RST copyright comment suffix: suffix, after the part we're creating heading_underline_char: RST character to use to underline the hea...
[ "Returns", "the", "text", "contents", "of", "an", "RST", "file", "that", "will", "automatically", "document", "our", "source", "file", "." ]
python
train
33.380952
devassistant/devassistant
devassistant/dapi/__init__.py
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L511-L513
def _strip_leading_dirname(self, path): '''Strip leading directory name from the given path''' return os.path.sep.join(path.split(os.path.sep)[1:])
[ "def", "_strip_leading_dirname", "(", "self", ",", "path", ")", ":", "return", "os", ".", "path", ".", "sep", ".", "join", "(", "path", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "[", "1", ":", "]", ")" ]
Strip leading directory name from the given path
[ "Strip", "leading", "directory", "name", "from", "the", "given", "path" ]
python
train
53.666667
radjkarl/imgProcessor
imgProcessor/equations/gaussian.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/equations/gaussian.py#L6-L13
def gaussian(x, a, b, c, d=0): ''' a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset ''' return a * np.exp( -(((x-b)**2 )/ (2*(c**2))) ) + d
[ "def", "gaussian", "(", "x", ",", "a", ",", "b", ",", "c", ",", "d", "=", "0", ")", ":", "return", "a", "*", "np", ".", "exp", "(", "-", "(", "(", "(", "x", "-", "b", ")", "**", "2", ")", "/", "(", "2", "*", "(", "c", "**", "2", ")"...
a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset
[ "a", "-", ">", "height", "of", "the", "curve", "s", "peak", "b", "-", ">", "position", "of", "the", "center", "of", "the", "peak", "c", "-", ">", "standard", "deviation", "or", "Gaussian", "RMS", "width", "d", "-", ">", "offset" ]
python
train
31.5
saltstack/salt
salt/cli/daemons.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L233-L311
def prepare(self): ''' Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Minion, self).prepare() try: if self.config['verify_env']: ...
[ "def", "prepare", "(", "self", ")", ":", "super", "(", "Minion", ",", "self", ")", ".", "prepare", "(", ")", "try", ":", "if", "self", ".", "config", "[", "'verify_env'", "]", ":", "confd", "=", "self", ".", "config", ".", "get", "(", "'default_inc...
Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare()
[ "Run", "the", "preparation", "sequence", "required", "to", "start", "a", "salt", "minion", "." ]
python
train
40.379747
mitsei/dlkit
dlkit/json_/learning/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/managers.py#L2192-L2209
def get_proficiency_admin_session(self, proxy): """Gets the ``OsidSession`` associated with the proficiency administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ProficiencyAdminSession) - a ``ProficiencyAdminSession`` raise: NullArgum...
[ "def", "get_proficiency_admin_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_proficiency_admin", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "Profic...
Gets the ``OsidSession`` associated with the proficiency administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ProficiencyAdminSession) - a ``ProficiencyAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed...
[ "Gets", "the", "OsidSession", "associated", "with", "the", "proficiency", "administration", "service", "." ]
python
train
46.222222
mfcloud/python-zvm-sdk
zvmsdk/configdrive.py
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/configdrive.py#L113-L153
def create_config_drive(network_interface_info, os_version): """Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address...
[ "def", "create_config_drive", "(", "network_interface_info", ",", "os_version", ")", ":", "temp_path", "=", "CONF", ".", "guest", ".", "temp_path", "if", "not", "os", ".", "path", ".", "exists", "(", "temp_path", ")", ":", "os", ".", "mkdir", "(", "temp_pa...
Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address netmask_v4 - IPV4 netmask :param str os_version: operat...
[ "Generate", "config", "driver", "for", "zVM", "guest", "vm", "." ]
python
train
37.02439
pypa/pipenv
pipenv/vendor/click/core.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/core.py#L557-L573
def forward(*args, **kwargs): """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. """ self, cmd = args[:2] # It's also possible to invok...
[ "def", "forward", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ",", "cmd", "=", "args", "[", ":", "2", "]", "# It's also possible to invoke another command which might or", "# might not have a callback.", "if", "not", "isinstance", "(", "cmd", ",...
Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands.
[ "Similar", "to", ":", "meth", ":", "invoke", "but", "fills", "in", "default", "keyword", "arguments", "from", "the", "current", "context", "if", "the", "other", "command", "expects", "it", ".", "This", "cannot", "invoke", "callbacks", "directly", "only", "ot...
python
train
37.470588
tensorflow/tensor2tensor
tensor2tensor/models/image_transformer.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L1054-L1062
def imagetransformer_cifar_tpu_range(rhp): """Range of hyperparameters for vizier.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE) rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16]) rhp.set_discrete("hidden_size", [256, ...
[ "def", "imagetransformer_cifar_tpu_range", "(", "rhp", ")", ":", "# After starting from base, set intervals for some parameters.", "rhp", ".", "set_float", "(", "\"learning_rate\"", ",", "0.01", ",", "1.0", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", ...
Range of hyperparameters for vizier.
[ "Range", "of", "hyperparameters", "for", "vizier", "." ]
python
train
54.777778
ansible/tacacs_plus
tacacs_plus/client.py
https://github.com/ansible/tacacs_plus/blob/de0d01372169c8849fa284d75097e57367c8930f/tacacs_plus/client.py#L226-L266
def authorize(self, username, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authorize with a TACACS+ server. :param username: :param arguments...
[ "def", "authorize", "(", "self", ",", "username", ",", "arguments", "=", "[", "]", ",", "authen_type", "=", "TAC_PLUS_AUTHEN_TYPE_ASCII", ",", "priv_lvl", "=", "TAC_PLUS_PRIV_LVL_MIN", ",", "rem_addr", "=", "TAC_PLUS_VIRTUAL_REM_ADDR", ",", "port", "=", "TAC_PLUS_...
Authorize with a TACACS+ server. :param username: :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: ...
[ "Authorize", "with", "a", "TACACS", "+", "server", "." ]
python
train
46.097561
edx/opaque-keys
opaque_keys/edx/locator.py
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1116-L1120
def for_branch(self, branch): """ Return a UsageLocator for the same block in a different branch of the library. """ return self.replace(library_key=self.library_key.for_branch(branch))
[ "def", "for_branch", "(", "self", ",", "branch", ")", ":", "return", "self", ".", "replace", "(", "library_key", "=", "self", ".", "library_key", ".", "for_branch", "(", "branch", ")", ")" ]
Return a UsageLocator for the same block in a different branch of the library.
[ "Return", "a", "UsageLocator", "for", "the", "same", "block", "in", "a", "different", "branch", "of", "the", "library", "." ]
python
train
42.6
solvebio/solvebio-python
solvebio/utils/tabulate.py
https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/utils/tabulate.py#L160-L170
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, string_types)) and \ _isconvertible(int, string)
[ "def", "_isint", "(", "string", ")", ":", "return", "type", "(", "string", ")", "is", "int", "or", "(", "isinstance", "(", "string", ",", "_binary_type", ")", "or", "isinstance", "(", "string", ",", "string_types", ")", ")", "and", "_isconvertible", "(",...
>>> _isint("123") True >>> _isint("123.45") False
[ ">>>", "_isint", "(", "123", ")", "True", ">>>", "_isint", "(", "123", ".", "45", ")", "False" ]
python
test
23.363636
albu/albumentations
albumentations/augmentations/functional.py
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L1023-L1039
def bbox_transpose(bbox, axis, rows, cols): """Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols. """ x_min, y_min, x_max, y_...
[ "def", "bbox_transpose", "(", "bbox", ",", "axis", ",", "rows", ",", "cols", ")", ":", "x_min", ",", "y_min", ",", "x_max", ",", "y_max", "=", "bbox", "if", "axis", "!=", "0", "and", "axis", "!=", "1", ":", "raise", "ValueError", "(", "'Axis must be ...
Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols.
[ "Transposes", "a", "bounding", "box", "along", "given", "axis", "." ]
python
train
32.823529
StackStorm/pybind
pybind/slxos/v17s_1_02/routing_system/interface/ve/intf_isis/interface_isis/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/interface/ve/intf_isis/interface_isis/__init__.py#L215-L236
def _set_interface_auth_key(self, v, load=False): """ Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_interface_auth_key is con...
[ "def", "_set_interface_auth_key", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ","...
Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_interface_auth_key is considered as a private method. Backends looking to populate ...
[ "Setter", "method", "for", "interface_auth_key", "mapped", "from", "YANG", "variable", "/", "routing_system", "/", "interface", "/", "ve", "/", "intf_isis", "/", "interface_isis", "/", "interface_auth_key", "(", "list", ")", "If", "this", "variable", "is", "read...
python
train
143.454545
DataDog/integrations-core
ceph/datadog_checks/ceph/ceph.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/ceph/datadog_checks/ceph/ceph.py#L249-L258
def _osd_pct_used(self, health): """Take a single health check string, return (OSD name, percentage used)""" # Full string looks like: osd.2 is full at 95% # Near full string: osd.1 is near full at 94% pct = re.compile(r'\d+%').findall(health) osd = re.compile(r'osd.\d+').findall...
[ "def", "_osd_pct_used", "(", "self", ",", "health", ")", ":", "# Full string looks like: osd.2 is full at 95%", "# Near full string: osd.1 is near full at 94%", "pct", "=", "re", ".", "compile", "(", "r'\\d+%'", ")", ".", "findall", "(", "health", ")", "osd", "=", "...
Take a single health check string, return (OSD name, percentage used)
[ "Take", "a", "single", "health", "check", "string", "return", "(", "OSD", "name", "percentage", "used", ")" ]
python
train
44.9
Fantomas42/django-blog-zinnia
zinnia/markups.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/markups.py#L30-L44
def markdown(value, extensions=MARKDOWN_EXTENSIONS): """ Markdown processing with optionally using various extensions that python-markdown supports. `extensions` is an iterable of either markdown.Extension instances or extension paths. """ try: import markdown except ImportError:...
[ "def", "markdown", "(", "value", ",", "extensions", "=", "MARKDOWN_EXTENSIONS", ")", ":", "try", ":", "import", "markdown", "except", "ImportError", ":", "warnings", ".", "warn", "(", "\"The Python markdown library isn't installed.\"", ",", "RuntimeWarning", ")", "r...
Markdown processing with optionally using various extensions that python-markdown supports. `extensions` is an iterable of either markdown.Extension instances or extension paths.
[ "Markdown", "processing", "with", "optionally", "using", "various", "extensions", "that", "python", "-", "markdown", "supports", ".", "extensions", "is", "an", "iterable", "of", "either", "markdown", ".", "Extension", "instances", "or", "extension", "paths", "." ]
python
train
33.8
mardix/Juice
juice/decorators.py
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/decorators.py#L23-L56
def plugin(module, *args, **kwargs): """ Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): ...
[ "def", "plugin", "(", "module", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "wrap", "(", "f", ")", ":", "m", "=", "module", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "inspect", ".", "isclass", "(", "m", ...
Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): return {} return MyEx...
[ "Decorator", "to", "extend", "a", "package", "to", "a", "view", ".", "The", "module", "can", "be", "a", "class", "or", "function", ".", "It", "will", "copy", "all", "the", "methods", "to", "the", "class" ]
python
train
24.676471
wummel/linkchecker
linkcheck/bookmarks/firefox.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/bookmarks/firefox.py#L34-L42
def get_profile_dir (): """Return path where all profiles of current user are stored.""" if os.name == 'nt': basedir = unicode(os.environ["APPDATA"], nt_filename_encoding) dirpath = os.path.join(basedir, u"Mozilla", u"Firefox", u"Profiles") elif os.name == 'posix': basedir = unicode(...
[ "def", "get_profile_dir", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "basedir", "=", "unicode", "(", "os", ".", "environ", "[", "\"APPDATA\"", "]", ",", "nt_filename_encoding", ")", "dirpath", "=", "os", ".", "path", ".", "join", "(", ...
Return path where all profiles of current user are stored.
[ "Return", "path", "where", "all", "profiles", "of", "current", "user", "are", "stored", "." ]
python
train
46.111111
bitesofcode/projexui
projexui/widgets/xratingslider.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xratingslider.py#L78-L84
def mousePressEvent( self, event ): """ Sets the value for the slider at the event position. :param event | <QMouseEvent> """ self.setValue(self.valueAt(event.pos().x()))
[ "def", "mousePressEvent", "(", "self", ",", "event", ")", ":", "self", ".", "setValue", "(", "self", ".", "valueAt", "(", "event", ".", "pos", "(", ")", ".", "x", "(", ")", ")", ")" ]
Sets the value for the slider at the event position. :param event | <QMouseEvent>
[ "Sets", "the", "value", "for", "the", "slider", "at", "the", "event", "position", ".", ":", "param", "event", "|", "<QMouseEvent", ">" ]
python
train
32
wavycloud/pyboto3
pyboto3/dynamodb.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/dynamodb.py#L3217-L3660
def scan(TableName=None, IndexName=None, AttributesToGet=None, Limit=None, Select=None, ScanFilter=None, ConditionalOperator=None, ExclusiveStartKey=None, ReturnConsumedCapacity=None, TotalSegments=None, Segment=None, ProjectionExpression=None, FilterExpression=None, ExpressionAttributeNames=None, ExpressionAttributeVa...
[ "def", "scan", "(", "TableName", "=", "None", ",", "IndexName", "=", "None", ",", "AttributesToGet", "=", "None", ",", "Limit", "=", "None", ",", "Select", "=", "None", ",", "ScanFilter", "=", "None", ",", "ConditionalOperator", "=", "None", ",", "Exclus...
The Scan operation returns one or more items and item attributes by accessing every item in a table or a secondary index. To have DynamoDB return fewer items, you can provide a FilterExpression operation. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and result...
[ "The", "Scan", "operation", "returns", "one", "or", "more", "items", "and", "item", "attributes", "by", "accessing", "every", "item", "in", "a", "table", "or", "a", "secondary", "index", ".", "To", "have", "DynamoDB", "return", "fewer", "items", "you", "ca...
python
train
74.254505
TUT-ARG/sed_eval
sed_eval/sound_event.py
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/sound_event.py#L1577-L1601
def reset(self): """Reset internal state """ self.overall = { 'Nref': 0.0, 'Nsys': 0.0, 'Nsubs': 0.0, 'Ntp': 0.0, 'Nfp': 0.0, 'Nfn': 0.0, } self.class_wise = {} for class_label in self.event_label_l...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "overall", "=", "{", "'Nref'", ":", "0.0", ",", "'Nsys'", ":", "0.0", ",", "'Nsubs'", ":", "0.0", ",", "'Ntp'", ":", "0.0", ",", "'Nfp'", ":", "0.0", ",", "'Nfn'", ":", "0.0", ",", "}", "self"...
Reset internal state
[ "Reset", "internal", "state" ]
python
train
22
Holzhaus/python-cmuclmtk
cmuclmtk/__init__.py
https://github.com/Holzhaus/python-cmuclmtk/blob/67a5c6713c497ca644ea1c697a70e8d930c9d4b4/cmuclmtk/__init__.py#L275-L327
def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10): """ Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurr...
[ "def", "wngram2idngram", "(", "input_file", ",", "vocab_file", ",", "output_file", ",", "buffersize", "=", "100", ",", "hashtablesize", "=", "2000000", ",", "files", "=", "20", ",", "compress", "=", "False", ",", "verbosity", "=", "2", ",", "n", "=", "3"...
Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format. Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this...
[ "Takes", "a", "word", "N", "-", "gram", "file", "and", "a", "vocabulary", "file", "and", "lists", "every", "id", "n", "-", "gram", "which", "occurred", "in", "the", "text", "along", "with", "its", "number", "of", "occurrences", "in", "either", "ASCII", ...
python
train
39.075472
tcalmant/ipopo
pelix/framework.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L326-L344
def get_registered_services(self): # type: () -> List[ServiceReference] """ Returns this bundle's ServiceReference list for all services it has registered or an empty list The list is valid at the time of the call to this method, however, as the Framework is a very dynam...
[ "def", "get_registered_services", "(", "self", ")", ":", "# type: () -> List[ServiceReference]", "if", "self", ".", "_state", "==", "Bundle", ".", "UNINSTALLED", ":", "raise", "BundleException", "(", "\"Can't call 'get_registered_services' on an \"", "\"uninstalled bundle\"",...
Returns this bundle's ServiceReference list for all services it has registered or an empty list The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :return: An a...
[ "Returns", "this", "bundle", "s", "ServiceReference", "list", "for", "all", "services", "it", "has", "registered", "or", "an", "empty", "list" ]
python
train
41.368421
CalebBell/ht
ht/conv_free_immersed.py
https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/conv_free_immersed.py#L148-L204
def Nu_vertical_cylinder_Griffiths_Davis_Morgan(Pr, Gr, turbulent=None): r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to the results of [1]_ correlated by [2]_, as presented in [3]_ and [4]_. .. math:: Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < R...
[ "def", "Nu_vertical_cylinder_Griffiths_Davis_Morgan", "(", "Pr", ",", "Gr", ",", "turbulent", "=", "None", ")", ":", "Ra", "=", "Pr", "*", "Gr", "if", "turbulent", "or", "(", "Ra", ">", "1E9", "and", "turbulent", "is", "None", ")", ":", "Nu", "=", "0.0...
r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to the results of [1]_ correlated by [2]_, as presented in [3]_ and [4]_. .. math:: Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < Ra < 10^{9} Nu_H = 0.0782 Ra_H^{0.357}, \; 10^{9} < Ra < 10^{11} ...
[ "r", "Calculates", "Nusselt", "number", "for", "natural", "convection", "around", "a", "vertical", "isothermal", "cylinder", "according", "to", "the", "results", "of", "[", "1", "]", "_", "correlated", "by", "[", "2", "]", "_", "as", "presented", "in", "["...
python
train
34.368421
pypa/pipenv
pipenv/vendor/distlib/_backport/shutil.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L510-L518
def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
[ "def", "get_archive_formats", "(", ")", ":", "formats", "=", "[", "(", "name", ",", "registry", "[", "2", "]", ")", "for", "name", ",", "registry", "in", "_ARCHIVE_FORMATS", ".", "items", "(", ")", "]", "formats", ".", "sort", "(", ")", "return", "fo...
Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description)
[ "Returns", "a", "list", "of", "supported", "formats", "for", "archiving", "and", "unarchiving", "." ]
python
train
34.444444
mbodenhamer/syn
syn/tree/b/node.py
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/tree/b/node.py#L170-L179
def collect_by_type(self, typ): '''A more efficient way to collect nodes of a specified type than collect_nodes. ''' nodes = [] if isinstance(self, typ): nodes.append(self) for c in self: nodes.extend(c.collect_by_type(typ)) return nodes
[ "def", "collect_by_type", "(", "self", ",", "typ", ")", ":", "nodes", "=", "[", "]", "if", "isinstance", "(", "self", ",", "typ", ")", ":", "nodes", ".", "append", "(", "self", ")", "for", "c", "in", "self", ":", "nodes", ".", "extend", "(", "c",...
A more efficient way to collect nodes of a specified type than collect_nodes.
[ "A", "more", "efficient", "way", "to", "collect", "nodes", "of", "a", "specified", "type", "than", "collect_nodes", "." ]
python
train
30.8
OriHoch/python-hebrew-numbers
hebrew_numbers/__init__.py
https://github.com/OriHoch/python-hebrew-numbers/blob/0bfa3d83b7bc03c2fc27e3db4a0630f6770cdbf0/hebrew_numbers/__init__.py#L56-L78
def int_to_gematria(num, gershayim=True): """convert integers between 1 an 999 to Hebrew numerals. - set gershayim flag to False to ommit gershayim """ # 1. Lookup in specials if num in specialnumbers['specials']: retval = specialnumbers['specials'][num] return _add_gershayim...
[ "def", "int_to_gematria", "(", "num", ",", "gershayim", "=", "True", ")", ":", "# 1. Lookup in specials", "if", "num", "in", "specialnumbers", "[", "'specials'", "]", ":", "retval", "=", "specialnumbers", "[", "'specials'", "]", "[", "num", "]", "return", "_...
convert integers between 1 an 999 to Hebrew numerals. - set gershayim flag to False to ommit gershayim
[ "convert", "integers", "between", "1", "an", "999", "to", "Hebrew", "numerals", "." ]
python
train
31.347826
alphagov/estools
estools/command/rotate.py
https://github.com/alphagov/estools/blob/ee016ceb14cd83ee61e338fe0e226998914df97c/estools/command/rotate.py#L156-L166
def rotate(prefixes, hosts, **kwargs): """ Rotates a set of daily indices by updating a "-current" alias to point to a (newly-created) index for today. This should probably be called from a daily cronjob just after midnight. """ rotator = Rotator(pyes.ES(hosts), **kwargs) for prefix in pre...
[ "def", "rotate", "(", "prefixes", ",", "hosts", ",", "*", "*", "kwargs", ")", ":", "rotator", "=", "Rotator", "(", "pyes", ".", "ES", "(", "hosts", ")", ",", "*", "*", "kwargs", ")", "for", "prefix", "in", "prefixes", ":", "rotator", ".", "rotate",...
Rotates a set of daily indices by updating a "-current" alias to point to a (newly-created) index for today. This should probably be called from a daily cronjob just after midnight.
[ "Rotates", "a", "set", "of", "daily", "indices", "by", "updating", "a", "-", "current", "alias", "to", "point", "to", "a", "(", "newly", "-", "created", ")", "index", "for", "today", ".", "This", "should", "probably", "be", "called", "from", "a", "dail...
python
train
31.545455
DLR-RM/RAFCON
source/rafcon/gui/views/graphical_editor.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L778-L792
def find_selection(): """Finds the selected ids After the scene has been rendered again in selection mode, this method gathers and returns the ids of the selected object and restores the matrices. :return: The selection stack """ hits = glRenderMode(GL_RENDER) ...
[ "def", "find_selection", "(", ")", ":", "hits", "=", "glRenderMode", "(", "GL_RENDER", ")", "glMatrixMode", "(", "GL_PROJECTION", ")", "glPopMatrix", "(", ")", "glMatrixMode", "(", "GL_MODELVIEW", ")", "return", "hits" ]
Finds the selected ids After the scene has been rendered again in selection mode, this method gathers and returns the ids of the selected object and restores the matrices. :return: The selection stack
[ "Finds", "the", "selected", "ids" ]
python
train
27.4
iskandr/fancyimpute
fancyimpute/iterative_imputer.py
https://github.com/iskandr/fancyimpute/blob/9f0837d387c7303d5c8c925a9989ca77a1a96e3e/fancyimpute/iterative_imputer.py#L99-L113
def _get_mask(X, value_to_mask): """Compute the boolean mask X == missing_values.""" if is_scalar_nan(value_to_mask): if X.dtype.kind == "f": return np.isnan(X) elif X.dtype.kind in ("i", "u"): # can't have NaNs in integer array. return np.zeros(X.shape, dtype...
[ "def", "_get_mask", "(", "X", ",", "value_to_mask", ")", ":", "if", "is_scalar_nan", "(", "value_to_mask", ")", ":", "if", "X", ".", "dtype", ".", "kind", "==", "\"f\"", ":", "return", "np", ".", "isnan", "(", "X", ")", "elif", "X", ".", "dtype", "...
Compute the boolean mask X == missing_values.
[ "Compute", "the", "boolean", "mask", "X", "==", "missing_values", "." ]
python
train
39.733333
thomasdelaet/python-velbus
velbus/messages/channel_name_request.py
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/channel_name_request.py#L20-L29
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 1) self.set_attributes(priority, address, rtr) self.channels = sel...
[ "def", "populate", "(", "self", ",", "priority", ",", "address", ",", "rtr", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", "self", ".", "needs_low_priority", "(", "priority", ")", "self", ".", "needs_no_rtr", "(", "rtr", ...
:return: None
[ ":", "return", ":", "None" ]
python
train
33.8
seleniumbase/SeleniumBase
seleniumbase/fixtures/base_case.py
https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/base_case.py#L2319-L2330
def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT): """ Similar to wait_for_link_text_visible(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. """ if self.timeout_mul...
[ "def", "assert_link_text", "(", "self", ",", "link_text", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", ":", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings", ".", "SMALL_TIMEOUT", ":", "timeout", "=", "self", ".", "_...
Similar to wait_for_link_text_visible(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT.
[ "Similar", "to", "wait_for_link_text_visible", "()", "but", "returns", "nothing", ".", "As", "above", "will", "raise", "an", "exception", "if", "nothing", "can", "be", "found", ".", "Returns", "True", "if", "successful", ".", "Default", "timeout", "=", "SMALL_...
python
train
58.5
scanny/python-pptx
pptx/text/layout.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/text/layout.py#L103-L113
def _wrap_lines(self, line_source, point_size): """ Return a sequence of str values representing the text in *line_source* wrapped within this fitter when rendered at *point_size*. """ text, remainder = self._break_line(line_source, point_size) lines = [text] ...
[ "def", "_wrap_lines", "(", "self", ",", "line_source", ",", "point_size", ")", ":", "text", ",", "remainder", "=", "self", ".", "_break_line", "(", "line_source", ",", "point_size", ")", "lines", "=", "[", "text", "]", "if", "remainder", ":", "lines", "....
Return a sequence of str values representing the text in *line_source* wrapped within this fitter when rendered at *point_size*.
[ "Return", "a", "sequence", "of", "str", "values", "representing", "the", "text", "in", "*", "line_source", "*", "wrapped", "within", "this", "fitter", "when", "rendered", "at", "*", "point_size", "*", "." ]
python
train
37.636364
mlperf/training
compliance/mlperf_compliance/mlperf_log.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/compliance/mlperf_compliance/mlperf_log.py#L80-L138
def _mlperf_print(key, value=None, benchmark=None, stack_offset=0, tag_set=None, deferred=False, root_dir=None, extra_print=False, prefix=""): ''' Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: ...
[ "def", "_mlperf_print", "(", "key", ",", "value", "=", "None", ",", "benchmark", "=", "None", ",", "stack_offset", "=", "0", ",", "tag_set", "=", "None", ",", "deferred", "=", "False", ",", "root_dir", "=", "None", ",", "extra_print", "=", "False", ","...
Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: The value which contains no newlines. benchmark: The short code for the benchmark being run, see the MLPerf log spec. stack_offset: Increase the value to go deeper into the stack to...
[ "Prints", "out", "an", "MLPerf", "Log", "Line", "." ]
python
train
38.79661
ValvePython/steam
steam/guard.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/guard.py#L446-L467
def generate_confirmation_key(identity_secret, tag, timestamp): """Generate confirmation key for trades. Can only be used once. :param identity_secret: authenticator identity secret :type identity_secret: bytes :param tag: tag identifies what the request, see list below :type tag: str :param ti...
[ "def", "generate_confirmation_key", "(", "identity_secret", ",", "tag", ",", "timestamp", ")", ":", "data", "=", "struct", ".", "pack", "(", "'>Q'", ",", "int", "(", "timestamp", ")", ")", "+", "tag", ".", "encode", "(", "'ascii'", ")", "# this will NOT st...
Generate confirmation key for trades. Can only be used once. :param identity_secret: authenticator identity secret :type identity_secret: bytes :param tag: tag identifies what the request, see list below :type tag: str :param timestamp: timestamp to use for generating key :type timestamp: int ...
[ "Generate", "confirmation", "key", "for", "trades", ".", "Can", "only", "be", "used", "once", "." ]
python
train
35.409091
CitrineInformatics/pif-dft
dfttopif/parsers/vasp.py
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/vasp.py#L382-L390
def get_band_gap(self): """Get the bandgap, either from the EIGENVAL or DOSCAR files""" if self.outcar is not None and self.eignval is not None: bandgap = VaspParser._get_bandgap_eigenval(self.eignval, self.outcar) elif self.doscar is not None: bandgap = VaspParser._get_b...
[ "def", "get_band_gap", "(", "self", ")", ":", "if", "self", ".", "outcar", "is", "not", "None", "and", "self", ".", "eignval", "is", "not", "None", ":", "bandgap", "=", "VaspParser", ".", "_get_bandgap_eigenval", "(", "self", ".", "eignval", ",", "self",...
Get the bandgap, either from the EIGENVAL or DOSCAR files
[ "Get", "the", "bandgap", "either", "from", "the", "EIGENVAL", "or", "DOSCAR", "files" ]
python
train
50.555556
gwastro/pycbc
pycbc/inference/io/base_hdf.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_hdf.py#L113-L139
def parse_parameters(self, parameters, array_class=None): """Parses a parameters arg to figure out what fields need to be loaded. Parameters ---------- parameters : (list of) strings The parameter(s) to retrieve. A parameter can be the name of any field in ``samp...
[ "def", "parse_parameters", "(", "self", ",", "parameters", ",", "array_class", "=", "None", ")", ":", "# get the type of array class to use", "if", "array_class", "is", "None", ":", "array_class", "=", "FieldArray", "# get the names of fields needed for the given parameters...
Parses a parameters arg to figure out what fields need to be loaded. Parameters ---------- parameters : (list of) strings The parameter(s) to retrieve. A parameter can be the name of any field in ``samples_group``, a virtual field or method of ``FieldArray`` ...
[ "Parses", "a", "parameters", "arg", "to", "figure", "out", "what", "fields", "need", "to", "be", "loaded", "." ]
python
train
43.111111
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1233-L1242
def MakeOdds(self): """Transforms from probabilities to odds. Values with prob=0 are removed. """ for hypo, prob in self.Items(): if prob: self.Set(hypo, Odds(prob)) else: self.Remove(hypo)
[ "def", "MakeOdds", "(", "self", ")", ":", "for", "hypo", ",", "prob", "in", "self", ".", "Items", "(", ")", ":", "if", "prob", ":", "self", ".", "Set", "(", "hypo", ",", "Odds", "(", "prob", ")", ")", "else", ":", "self", ".", "Remove", "(", ...
Transforms from probabilities to odds. Values with prob=0 are removed.
[ "Transforms", "from", "probabilities", "to", "odds", "." ]
python
train
26.9
spyder-ide/conda-manager
conda_manager/api/download_api.py
https://github.com/spyder-ide/conda-manager/blob/89a2126cbecefc92185cf979347ccac1c5ee5d9d/conda_manager/api/download_api.py#L444-L458
def _create_worker(self, method, *args, **kwargs): """Create a new worker instance.""" thread = QThread() worker = RequestsDownloadWorker(method, args, kwargs) worker.moveToThread(thread) worker.sig_finished.connect(self._start) self._sig_download_finished.connect(worker....
[ "def", "_create_worker", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thread", "=", "QThread", "(", ")", "worker", "=", "RequestsDownloadWorker", "(", "method", ",", "args", ",", "kwargs", ")", "worker", ".", "moveT...
Create a new worker instance.
[ "Create", "a", "new", "worker", "instance", "." ]
python
train
43.266667
DataBiosphere/toil
src/toil/lib/docker.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/lib/docker.py#L57-L67
def dockerCall(*args, **kwargs): """ Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'. Provided for backwards compatibility with a previous implementation that used 'subprocess.check_call()'. This has since been supplanted and apiDockerCall() is recommended. """ l...
[ "def", "dockerCall", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "warn", "(", "\"WARNING: dockerCall() using subprocess.check_output() \"", "\"is deprecated, please switch to apiDockerCall().\"", ")", "return", "subprocessDockerCall", "(", "*", "ar...
Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'. Provided for backwards compatibility with a previous implementation that used 'subprocess.check_call()'. This has since been supplanted and apiDockerCall() is recommended.
[ "Deprecated", ".", "Runs", "subprocessDockerCall", "()", "using", "subprocess", ".", "check_output", "()", "." ]
python
train
46.636364
spdx/tools-python
spdx/parsers/tagvaluebuilders.py
https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/tagvaluebuilders.py#L383-L399
def add_review_comment(self, doc, comment): """Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if comment is not free form text. """ if len(doc.reviews) != 0: if not self.review_comment_s...
[ "def", "add_review_comment", "(", "self", ",", "doc", ",", "comment", ")", ":", "if", "len", "(", "doc", ".", "reviews", ")", "!=", "0", ":", "if", "not", "self", ".", "review_comment_set", ":", "self", ".", "review_comment_set", "=", "True", "if", "va...
Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if comment is not free form text.
[ "Sets", "the", "review", "comment", ".", "Raises", "CardinalityError", "if", "already", "set", ".", "OrderError", "if", "no", "reviewer", "defined", "before", ".", "Raises", "SPDXValueError", "if", "comment", "is", "not", "free", "form", "text", "." ]
python
valid
43.705882
PinLin/KCOJ_api
KCOJ_api/api.py
https://github.com/PinLin/KCOJ_api/blob/64f6ef0f9e64dc1efd692cbe6d5738ee7cfb78ec/KCOJ_api/api.py#L190-L208
def update_password(self, password: str) -> bool: """ 修改登入密碼 """ try: # 操作所需資訊 payload = { 'pass': password, 'submit': 'sumit' } # 修改密碼 response = self.__session.post( self.__url +...
[ "def", "update_password", "(", "self", ",", "password", ":", "str", ")", "->", "bool", ":", "try", ":", "# 操作所需資訊", "payload", "=", "{", "'pass'", ":", "password", ",", "'submit'", ":", "'sumit'", "}", "# 修改密碼", "response", "=", "self", ".", "__session",...
修改登入密碼
[ "修改登入密碼" ]
python
train
30.842105
TUNE-Archive/freight_forwarder
freight_forwarder/config.py
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/config.py#L1026-L1112
def _load_yml_config(self, config_file): """ loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then assigns the config data to self._data. :param config_file: A :string: loaded from a yaml file. """ if not isinstance(config_file, s...
[ "def", "_load_yml_config", "(", "self", ",", "config_file", ")", ":", "if", "not", "isinstance", "(", "config_file", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'config_file must be a str.'", ")", "try", ":", "def", "construct_yaml_int...
loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then assigns the config data to self._data. :param config_file: A :string: loaded from a yaml file.
[ "loads", "a", "yaml", "str", "creates", "a", "few", "constructs", "for", "pyaml", "serializes", "and", "normalized", "the", "config", "data", ".", "Then", "assigns", "the", "config", "data", "to", "self", ".", "_data", "." ]
python
train
37.609195
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/layers.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L547-L578
def to_real_keras_layer(layer): ''' real keras layer. ''' from keras import layers if is_layer(layer, "Dense"): return layers.Dense(layer.units, input_shape=(layer.input_units,)) if is_layer(layer, "Conv"): return layers.Conv2D( layer.filters, layer.kernel_si...
[ "def", "to_real_keras_layer", "(", "layer", ")", ":", "from", "keras", "import", "layers", "if", "is_layer", "(", "layer", ",", "\"Dense\"", ")", ":", "return", "layers", ".", "Dense", "(", "layer", ".", "units", ",", "input_shape", "=", "(", "layer", "....
real keras layer.
[ "real", "keras", "layer", "." ]
python
train
34.46875
samirelanduk/quickplots
quickplots/charts.py
https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L359-L390
def x_lower_limit(self, limit=None): """Returns or sets (if a value is provided) the value at which the x-axis should start. By default this is zero (unless there are negative values). :param limit: If given, the chart's x_lower_limit will be set to this. :raises ValueError: if ...
[ "def", "x_lower_limit", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "limit", "is", "None", ":", "if", "self", ".", "_x_lower_limit", "is", "None", ":", "if", "self", ".", "smallest_x", "(", ")", "<", "0", ":", "if", "self", ".", "smalle...
Returns or sets (if a value is provided) the value at which the x-axis should start. By default this is zero (unless there are negative values). :param limit: If given, the chart's x_lower_limit will be set to this. :raises ValueError: if you try to make the lower limit larger than the\...
[ "Returns", "or", "sets", "(", "if", "a", "value", "is", "provided", ")", "the", "value", "at", "which", "the", "x", "-", "axis", "should", "start", ".", "By", "default", "this", "is", "zero", "(", "unless", "there", "are", "negative", "values", ")", ...
python
train
38.78125
IdentityPython/SATOSA
src/satosa/backends/saml2.py
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L321-L343
def register_endpoints(self): """ See super class method satosa.backends.base.BackendModule#register_endpoints :rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))] """ url_map = [] sp_endpoints = self.sp.config.getattr("endpoints", "sp") for endp, bindi...
[ "def", "register_endpoints", "(", "self", ")", ":", "url_map", "=", "[", "]", "sp_endpoints", "=", "self", ".", "sp", ".", "config", ".", "getattr", "(", "\"endpoints\"", ",", "\"sp\"", ")", "for", "endp", ",", "binding", "in", "sp_endpoints", "[", "\"as...
See super class method satosa.backends.base.BackendModule#register_endpoints :rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))]
[ "See", "super", "class", "method", "satosa", ".", "backends", ".", "base", ".", "BackendModule#register_endpoints", ":", "rtype", "list", "[", "(", "str", "((", "satosa", ".", "context", ".", "Context", "Any", ")", "-", ">", "Any", "Any", "))", "]" ]
python
train
43.913043
bigchaindb/bigchaindb-driver
bigchaindb_driver/driver.py
https://github.com/bigchaindb/bigchaindb-driver/blob/c294a535f0696bd19483ae11a4882b74e6fc061e/bigchaindb_driver/driver.py#L120-L136
def api_info(self, headers=None): """Retrieves information provided by the API root endpoint ``'/api/v1'``. Args: headers (dict): Optional headers to pass to the request. Returns: dict: Details of the HTTP API provided by the BigchainDB server. ...
[ "def", "api_info", "(", "self", ",", "headers", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "forward_request", "(", "method", "=", "'GET'", ",", "path", "=", "self", ".", "api_prefix", ",", "headers", "=", "headers", ",", ")" ]
Retrieves information provided by the API root endpoint ``'/api/v1'``. Args: headers (dict): Optional headers to pass to the request. Returns: dict: Details of the HTTP API provided by the BigchainDB server.
[ "Retrieves", "information", "provided", "by", "the", "API", "root", "endpoint", "/", "api", "/", "v1", "." ]
python
train
26.882353
tdryer/hangups
examples/common.py
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/common.py#L40-L57
def _get_parser(extra_args): """Return ArgumentParser with any extra arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) dirs = appdirs.AppDirs('hangups', 'hangups') default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.tx...
[ "def", "_get_parser", "(", "extra_args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ",", ")", "dirs", "=", "appdirs", ".", "AppDirs", "(", "'hangups'", ",", "'hangups...
Return ArgumentParser with any extra arguments.
[ "Return", "ArgumentParser", "with", "any", "extra", "arguments", "." ]
python
valid
37.333333
kubernetes-client/python
kubernetes/client/apis/core_v1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/core_v1_api.py#L1265-L1286
def connect_get_namespaced_service_proxy(self, name, namespace, **kwargs): """ connect GET requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_get_namespace...
[ "def", "connect_get_namespaced_service_proxy", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "se...
connect GET requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_get_namespaced_service_proxy(name, namespace, async_req=True) >>> result = thread.get() :pa...
[ "connect", "GET", "requests", "to", "proxy", "of", "Service", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "t...
python
train
62.318182
blockstack/blockstack-core
blockstack/lib/operations/register.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/register.py#L108-L123
def get_num_names_owned( state_engine, checked_ops, sender ): """ Find out how many preorders a given sender (i.e. a script) actually owns, as of this transaction. """ count = 0 registers = find_by_opcode( checked_ops, "NAME_REGISTRATION" ) for reg in registers: if reg['sender'...
[ "def", "get_num_names_owned", "(", "state_engine", ",", "checked_ops", ",", "sender", ")", ":", "count", "=", "0", "registers", "=", "find_by_opcode", "(", "checked_ops", ",", "\"NAME_REGISTRATION\"", ")", "for", "reg", "in", "registers", ":", "if", "reg", "["...
Find out how many preorders a given sender (i.e. a script) actually owns, as of this transaction.
[ "Find", "out", "how", "many", "preorders", "a", "given", "sender", "(", "i", ".", "e", ".", "a", "script", ")", "actually", "owns", "as", "of", "this", "transaction", "." ]
python
train
30.5
geronimp/graftM
graftm/create.py
https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/create.py#L335-L352
def _generate_tree_log_file(self, tree, alignment, output_tree_file_path, output_log_file_path, residue_type, fasttree): '''Generate the FastTree log file given a tree and the alignment that made that tree Returns ------- Nothing. The log file as p...
[ "def", "_generate_tree_log_file", "(", "self", ",", "tree", ",", "alignment", ",", "output_tree_file_path", ",", "output_log_file_path", ",", "residue_type", ",", "fasttree", ")", ":", "if", "residue_type", "==", "Create", ".", "_NUCLEOTIDE_PACKAGE_TYPE", ":", "cmd"...
Generate the FastTree log file given a tree and the alignment that made that tree Returns ------- Nothing. The log file as parameter is written as the log file.
[ "Generate", "the", "FastTree", "log", "file", "given", "a", "tree", "and", "the", "alignment", "that", "made", "that", "tree" ]
python
train
53.277778
odrling/peony-twitter
peony/utils.py
https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/utils.py#L174-L199
def log_error(msg=None, exc_info=None, logger=None, **kwargs): """ log an exception and its traceback on the logger defined Parameters ---------- msg : str, optional A message to add to the error exc_info : tuple Information about the current exception logger : logging.L...
[ "def", "log_error", "(", "msg", "=", "None", ",", "exc_info", "=", "None", ",", "logger", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "logger", "is", "None", ":", "logger", "=", "_logger", "if", "not", "exc_info", ":", "exc_info", "=", "s...
log an exception and its traceback on the logger defined Parameters ---------- msg : str, optional A message to add to the error exc_info : tuple Information about the current exception logger : logging.Logger logger to use
[ "log", "an", "exception", "and", "its", "traceback", "on", "the", "logger", "defined" ]
python
valid
23.346154
EntilZha/PyFunctional
functional/pipeline.py
https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L366-L379
def drop(self, n): """ Drop the first n elements of the sequence. >>> seq([1, 2, 3, 4, 5]).drop(2) [3, 4, 5] :param n: number of elements to drop :return: sequence without first n elements """ if n <= 0: return self._transform(transformations...
[ "def", "drop", "(", "self", ",", "n", ")", ":", "if", "n", "<=", "0", ":", "return", "self", ".", "_transform", "(", "transformations", ".", "drop_t", "(", "0", ")", ")", "else", ":", "return", "self", ".", "_transform", "(", "transformations", ".", ...
Drop the first n elements of the sequence. >>> seq([1, 2, 3, 4, 5]).drop(2) [3, 4, 5] :param n: number of elements to drop :return: sequence without first n elements
[ "Drop", "the", "first", "n", "elements", "of", "the", "sequence", "." ]
python
train
28.142857
edx/completion
completion/handlers.py
https://github.com/edx/completion/blob/5c23806f6db69ce6be3fd068fc5b5fdf4d66bd60/completion/handlers.py#L15-L39
def scorable_block_completion(sender, **kwargs): # pylint: disable=unused-argument """ When a problem is scored, submit a new BlockCompletion for that block. """ if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING): return course_key = CourseKey.from_string(kwargs['course_id...
[ "def", "scorable_block_completion", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "if", "not", "waffle", ".", "waffle", "(", ")", ".", "is_enabled", "(", "waffle", ".", "ENABLE_COMPLETION_TRACKING", ")", ":", "return", "c...
When a problem is scored, submit a new BlockCompletion for that block.
[ "When", "a", "problem", "is", "scored", "submit", "a", "new", "BlockCompletion", "for", "that", "block", "." ]
python
train
38.44
tensorflow/tensor2tensor
tensor2tensor/utils/t2t_model.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/t2t_model.py#L710-L718
def optimize(self, loss, num_async_replicas=1, use_tpu=False): """Return a training op minimizing loss.""" lr = learning_rate.learning_rate_schedule(self.hparams) if num_async_replicas > 1: log_info("Dividing learning rate by num_async_replicas: %d", num_async_replicas) lr /= math.s...
[ "def", "optimize", "(", "self", ",", "loss", ",", "num_async_replicas", "=", "1", ",", "use_tpu", "=", "False", ")", ":", "lr", "=", "learning_rate", ".", "learning_rate_schedule", "(", "self", ".", "hparams", ")", "if", "num_async_replicas", ">", "1", ":"...
Return a training op minimizing loss.
[ "Return", "a", "training", "op", "minimizing", "loss", "." ]
python
train
48.444444
Clinical-Genomics/scout
scout/commands/delete/delete_command.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/commands/delete/delete_command.py#L93-L98
def exons(context, build): """Delete all exons in the database""" LOG.info("Running scout delete exons") adapter = context.obj['adapter'] adapter.drop_exons(build)
[ "def", "exons", "(", "context", ",", "build", ")", ":", "LOG", ".", "info", "(", "\"Running scout delete exons\"", ")", "adapter", "=", "context", ".", "obj", "[", "'adapter'", "]", "adapter", ".", "drop_exons", "(", "build", ")" ]
Delete all exons in the database
[ "Delete", "all", "exons", "in", "the", "database" ]
python
test
29.166667
rsalmaso/django-fluo
fluo/middleware/locale.py
https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/middleware/locale.py#L68-L93
def get_default_language(language_code=None): """ Returns default language depending on settings.LANGUAGE_CODE merged with best match from settings.LANGUAGES Returns: language_code Raises ImproperlyConfigured if no match found """ if not language_code: language_code = settings.LAN...
[ "def", "get_default_language", "(", "language_code", "=", "None", ")", ":", "if", "not", "language_code", ":", "language_code", "=", "settings", ".", "LANGUAGE_CODE", "languages", "=", "dict", "(", "settings", ".", "LANGUAGES", ")", ".", "keys", "(", ")", "#...
Returns default language depending on settings.LANGUAGE_CODE merged with best match from settings.LANGUAGES Returns: language_code Raises ImproperlyConfigured if no match found
[ "Returns", "default", "language", "depending", "on", "settings", ".", "LANGUAGE_CODE", "merged", "with", "best", "match", "from", "settings", ".", "LANGUAGES" ]
python
train
28.730769
iamaziz/PyDataset
pydataset/utils/html2text.py
https://github.com/iamaziz/PyDataset/blob/789c0ca7587b86343f636b132dcf1f475ee6b90b/pydataset/utils/html2text.py#L314-L375
def handle_emphasis(self, start, tag_style, parent_style): """handles various text emphases""" tag_emphasis = google_text_emphasis(tag_style) parent_emphasis = google_text_emphasis(parent_style) # handle Google's text emphasis strikethrough = 'line-through' in tag_emphasis and ...
[ "def", "handle_emphasis", "(", "self", ",", "start", ",", "tag_style", ",", "parent_style", ")", ":", "tag_emphasis", "=", "google_text_emphasis", "(", "tag_style", ")", "parent_emphasis", "=", "google_text_emphasis", "(", "parent_style", ")", "# handle Google's text ...
handles various text emphases
[ "handles", "various", "text", "emphases" ]
python
train
39.725806
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/field_path.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/field_path.py#L280-L294
def from_api_repr(cls, api_repr): """Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath...
[ "def", "from_api_repr", "(", "cls", ",", "api_repr", ")", ":", "api_repr", "=", "api_repr", ".", "strip", "(", ")", "if", "not", "api_repr", ":", "raise", "ValueError", "(", "\"Field path API representation cannot be empty.\"", ")", "return", "cls", "(", "*", ...
Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath`) An instance parsed from ``api_repr``. ...
[ "Factory", ":", "create", "a", "FieldPath", "from", "the", "string", "formatted", "per", "the", "API", "." ]
python
train
40.4
aws/chalice
chalice/awsclient.py
https://github.com/aws/chalice/blob/10d7fb52e68bd1c52aae251c97e3939fc0190412/chalice/awsclient.py#L566-L579
def get_sdk_download_stream(self, rest_api_id, api_gateway_stage=DEFAULT_STAGE_NAME, sdk_type='javascript'): # type: (str, str, str) -> file """Generate an SDK for a given SDK. Returns a file like object that streams a zip contents...
[ "def", "get_sdk_download_stream", "(", "self", ",", "rest_api_id", ",", "api_gateway_stage", "=", "DEFAULT_STAGE_NAME", ",", "sdk_type", "=", "'javascript'", ")", ":", "# type: (str, str, str) -> file", "response", "=", "self", ".", "_client", "(", "'apigateway'", ")"...
Generate an SDK for a given SDK. Returns a file like object that streams a zip contents for the generated SDK.
[ "Generate", "an", "SDK", "for", "a", "given", "SDK", "." ]
python
train
38
roamanalytics/mittens
mittens/mittens_base.py
https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/mittens_base.py#L188-L193
def _format_param_value(key, value): """Wraps string values in quotes, and returns as 'key=value'. """ if isinstance(value, str): value = "'{}'".format(value) return "{}={}".format(key, value)
[ "def", "_format_param_value", "(", "key", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "\"'{}'\"", ".", "format", "(", "value", ")", "return", "\"{}={}\"", ".", "format", "(", "key", ",", "value", ")" ]
Wraps string values in quotes, and returns as 'key=value'.
[ "Wraps", "string", "values", "in", "quotes", "and", "returns", "as", "key", "=", "value", "." ]
python
train
35.166667
spyder-ide/spyder
spyder/plugins/editor/extensions/docstring.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L268-L349
def _generate_numpy_doc(self, func_info): """Generate a docstring of numpy type.""" numpy_doc = '' arg_names = func_info.arg_name_list arg_types = func_info.arg_type_list arg_values = func_info.arg_value_list if len(arg_names) > 0 and arg_names[0] == 'self': ...
[ "def", "_generate_numpy_doc", "(", "self", ",", "func_info", ")", ":", "numpy_doc", "=", "''", "arg_names", "=", "func_info", ".", "arg_name_list", "arg_types", "=", "func_info", ".", "arg_type_list", "arg_values", "=", "func_info", ".", "arg_value_list", "if", ...
Generate a docstring of numpy type.
[ "Generate", "a", "docstring", "of", "numpy", "type", "." ]
python
train
37.646341
gabstopper/smc-python
smc/core/engine.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine.py#L64-L157
def _create(cls, name, node_type, physical_interfaces, nodes=1, loopback_ndi=None, log_server_ref=None, domain_server_address=None, enable_antivirus=False, enable_gti=False, sidewinder_proxy_enabled=False, de...
[ "def", "_create", "(", "cls", ",", "name", ",", "node_type", ",", "physical_interfaces", ",", "nodes", "=", "1", ",", "loopback_ndi", "=", "None", ",", "log_server_ref", "=", "None", ",", "domain_server_address", "=", "None", ",", "enable_antivirus", "=", "F...
Create will return the engine configuration as a dict that is a representation of the engine. The creating class will also add engine specific requirements before constructing the request and sending to SMC (which will serialize the dict to json). :param name: name of engine :pa...
[ "Create", "will", "return", "the", "engine", "configuration", "as", "a", "dict", "that", "is", "a", "representation", "of", "the", "engine", ".", "The", "creating", "class", "will", "also", "add", "engine", "specific", "requirements", "before", "constructing", ...
python
train
38.095745
SheffieldML/GPy
GPy/util/datasets.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/datasets.py#L176-L205
def authorize_download(dataset_name=None): """Check with the user that the are happy with terms and conditions for the data set.""" print(('Acquiring resource: ' + dataset_name)) # TODO, check resource is in dictionary! print('') dr = data_resources[dataset_name] print('Details of data: ') p...
[ "def", "authorize_download", "(", "dataset_name", "=", "None", ")", ":", "print", "(", "(", "'Acquiring resource: '", "+", "dataset_name", ")", ")", "# TODO, check resource is in dictionary!", "print", "(", "''", ")", "dr", "=", "data_resources", "[", "dataset_name"...
Check with the user that the are happy with terms and conditions for the data set.
[ "Check", "with", "the", "user", "that", "the", "are", "happy", "with", "terms", "and", "conditions", "for", "the", "data", "set", "." ]
python
train
36.8
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit_file.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L101-L129
def verify_path(self, courseid, taskid, path, new_path=False): """ Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed """ task_fs = self.task_factory.get_task_fs(courseid, taskid) # verify that the dir exists if not task_fs.exists(): ...
[ "def", "verify_path", "(", "self", ",", "courseid", ",", "taskid", ",", "path", ",", "new_path", "=", "False", ")", ":", "task_fs", "=", "self", ".", "task_factory", ".", "get_task_fs", "(", "courseid", ",", "taskid", ")", "# verify that the dir exists", "if...
Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed
[ "Return", "the", "real", "wanted", "path", "(", "relative", "to", "the", "INGInious", "root", ")", "or", "None", "if", "the", "path", "is", "not", "valid", "/", "allowed" ]
python
train
36.37931
adamrothman/ftl
ftl/connection.py
https://github.com/adamrothman/ftl/blob/a88f3df1ecbdfba45035b65f833b8ffffc49b399/ftl/connection.py#L260-L264
async def _window_open(self, stream_id: int): """Wait until the identified stream's flow control window is open. """ stream = self._get_stream(stream_id) return await stream.window_open.wait()
[ "async", "def", "_window_open", "(", "self", ",", "stream_id", ":", "int", ")", ":", "stream", "=", "self", ".", "_get_stream", "(", "stream_id", ")", "return", "await", "stream", ".", "window_open", ".", "wait", "(", ")" ]
Wait until the identified stream's flow control window is open.
[ "Wait", "until", "the", "identified", "stream", "s", "flow", "control", "window", "is", "open", "." ]
python
train
44
ContextLab/quail
quail/helpers.py
https://github.com/ContextLab/quail/blob/71dd53c792dd915dc84879d8237e3582dd68b7a4/quail/helpers.py#L210-L233
def df2list(df): """ Convert a MultiIndex df to list Parameters ---------- df : pandas.DataFrame A MultiIndex DataFrame where the first level is subjects and the second level is lists (e.g. egg.pres) Returns ---------- lst : a list of lists of lists of values ...
[ "def", "df2list", "(", "df", ")", ":", "subjects", "=", "df", ".", "index", ".", "levels", "[", "0", "]", ".", "values", ".", "tolist", "(", ")", "lists", "=", "df", ".", "index", ".", "levels", "[", "1", "]", ".", "values", ".", "tolist", "(",...
Convert a MultiIndex df to list Parameters ---------- df : pandas.DataFrame A MultiIndex DataFrame where the first level is subjects and the second level is lists (e.g. egg.pres) Returns ---------- lst : a list of lists of lists of values The input df reformatted as a...
[ "Convert", "a", "MultiIndex", "df", "to", "list" ]
python
train
24.416667
marcinmiklitz/pywindow
pywindow/utilities.py
https://github.com/marcinmiklitz/pywindow/blob/e5264812157224f22a691741ca2e0aefdc9bd2eb/pywindow/utilities.py#L469-L486
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs): """Return optimised pore diameter and it's COM.""" args = elements, coordinates if com is not None: pass else: com = center_of_mass(elements, coordinates) if bounds is None: pore_r = pore_diameter(...
[ "def", "opt_pore_diameter", "(", "elements", ",", "coordinates", ",", "bounds", "=", "None", ",", "com", "=", "None", ",", "*", "*", "kwargs", ")", ":", "args", "=", "elements", ",", "coordinates", "if", "com", "is", "not", "None", ":", "pass", "else",...
Return optimised pore diameter and it's COM.
[ "Return", "optimised", "pore", "diameter", "and", "it", "s", "COM", "." ]
python
train
39.555556
CalebBell/thermo
thermo/joback.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/joback.py#L898-L926
def mul(self, T): r'''Computes liquid viscosity at a specified temperature of an organic compound using the Joback method as a function of chemical structure only. .. math:: \mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i \mu_a - 597.82}{T} + \sum_i \m...
[ "def", "mul", "(", "self", ",", "T", ")", ":", "if", "self", ".", "calculated_mul_coeffs", "is", "None", ":", "self", ".", "calculated_mul_coeffs", "=", "Joback", ".", "mul_coeffs", "(", "self", ".", "counts", ")", "a", ",", "b", "=", "self", ".", "c...
r'''Computes liquid viscosity at a specified temperature of an organic compound using the Joback method as a function of chemical structure only. .. math:: \mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i \mu_a - 597.82}{T} + \sum_i \mu_b - 11.202 \right) ...
[ "r", "Computes", "liquid", "viscosity", "at", "a", "specified", "temperature", "of", "an", "organic", "compound", "using", "the", "Joback", "method", "as", "a", "function", "of", "chemical", "structure", "only", ".", "..", "math", "::", "\\", "mu_", "{", "...
python
valid
29.068966
markuskiller/textblob-de
textblob_de/ext/_pattern/text/__init__.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L745-L753
def find_chunks(self, tokens, **kwargs): """ Annotates the given list of tokens with chunk tags. Several tags can be added, for example chunk + preposition tags. """ # [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] => # [["The", "DT", "B-NP"], ["cat", "NN", "I-NP"], ["purs", ...
[ "def", "find_chunks", "(", "self", ",", "tokens", ",", "*", "*", "kwargs", ")", ":", "# [[\"The\", \"DT\"], [\"cat\", \"NN\"], [\"purs\", \"VB\"]] =>", "# [[\"The\", \"DT\", \"B-NP\"], [\"cat\", \"NN\", \"I-NP\"], [\"purs\", \"VB\", \"B-VP\"]]", "return", "find_prepositions", "(", ...
Annotates the given list of tokens with chunk tags. Several tags can be added, for example chunk + preposition tags.
[ "Annotates", "the", "given", "list", "of", "tokens", "with", "chunk", "tags", ".", "Several", "tags", "can", "be", "added", "for", "example", "chunk", "+", "preposition", "tags", "." ]
python
train
51.666667
saltstack/salt
salt/daemons/masterapi.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/daemons/masterapi.py#L794-L815
def _minion_event(self, load): ''' Receive an event from the minion and fire it on the master event interface ''' if 'id' not in load: return False if 'events' not in load and ('tag' not in load or 'data' not in load): return False if 'even...
[ "def", "_minion_event", "(", "self", ",", "load", ")", ":", "if", "'id'", "not", "in", "load", ":", "return", "False", "if", "'events'", "not", "in", "load", "and", "(", "'tag'", "not", "in", "load", "or", "'data'", "not", "in", "load", ")", ":", "...
Receive an event from the minion and fire it on the master event interface
[ "Receive", "an", "event", "from", "the", "minion", "and", "fire", "it", "on", "the", "master", "event", "interface" ]
python
train
38.681818
jmgilman/Neolib
neolib/pyamf/amf3.py
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf3.py#L1046-L1063
def readXML(self): """ Reads an xml object from the stream. @return: An etree interface compatible object @see: L{xml.set_default_interface} """ ref = self.readInteger(False) if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) ...
[ "def", "readXML", "(", "self", ")", ":", "ref", "=", "self", ".", "readInteger", "(", "False", ")", "if", "ref", "&", "REFERENCE_BIT", "==", "0", ":", "return", "self", ".", "context", ".", "getObject", "(", "ref", ">>", "1", ")", "xmlstring", "=", ...
Reads an xml object from the stream. @return: An etree interface compatible object @see: L{xml.set_default_interface}
[ "Reads", "an", "xml", "object", "from", "the", "stream", "." ]
python
train
24.166667
ybrs/pydisque
pydisque/client.py
https://github.com/ybrs/pydisque/blob/ea5ce1576b66398c1cce32cad0f15709b1ea8df8/pydisque/client.py#L417-L451
def pause(self, queue_name, kw_in=None, kw_out=None, kw_all=None, kw_none=None, kw_state=None, kw_bcast=None): """ Pause a queue. Unfortunately, the PAUSE keywords are mostly reserved words in Python, so I've been a little creative in the function variable names. Open ...
[ "def", "pause", "(", "self", ",", "queue_name", ",", "kw_in", "=", "None", ",", "kw_out", "=", "None", ",", "kw_all", "=", "None", ",", "kw_none", "=", "None", ",", "kw_state", "=", "None", ",", "kw_bcast", "=", "None", ")", ":", "command", "=", "[...
Pause a queue. Unfortunately, the PAUSE keywords are mostly reserved words in Python, so I've been a little creative in the function variable names. Open to suggestions to change it (canardleteer) :param queue_name: The job queue we are modifying. :param kw_in: pause the queue ...
[ "Pause", "a", "queue", "." ]
python
train
38.771429
GNS3/gns3-server
gns3server/controller/project.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L119-L133
def update(self, **kwargs): """ Update the project :param kwargs: Project properties """ old_json = self.__json__() for prop in kwargs: setattr(self, prop, kwargs[prop]) # We send notif only if object has changed if old_json != self.__json__...
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "old_json", "=", "self", ".", "__json__", "(", ")", "for", "prop", "in", "kwargs", ":", "setattr", "(", "self", ",", "prop", ",", "kwargs", "[", "prop", "]", ")", "# We send notif only ...
Update the project :param kwargs: Project properties
[ "Update", "the", "project", ":", "param", "kwargs", ":", "Project", "properties" ]
python
train
27.666667
h2oai/h2o-3
scripts/logscrapedaily.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/scripts/logscrapedaily.py#L337-L370
def find_build_id(each_line,temp_func_list): """ Find the build id of a jenkins job. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters --------...
[ "def", "find_build_id", "(", "each_line", ",", "temp_func_list", ")", ":", "global", "g_before_java_file", "global", "g_java_filenames", "global", "g_build_id_text", "global", "g_jenkins_url", "global", "g_output_filename", "global", "g_output_pickle_filename", "if", "g_bui...
Find the build id of a jenkins job. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters ---------- each_line : str contains a line read in ...
[ "Find", "the", "build", "id", "of", "a", "jenkins", "job", ".", "It", "will", "save", "this", "information", "in", "g_failed_test_info_dict", ".", "In", "addition", "it", "will", "delete", "this", "particular", "function", "handle", "off", "the", "temp_func_li...
python
test
36
Gscorreia89/pyChemometrics
pyChemometrics/ChemometricsScaler.py
https://github.com/Gscorreia89/pyChemometrics/blob/539f5cd719795685271faa7fb1c6d53d7dd4de19/pyChemometrics/ChemometricsScaler.py#L171-L205
def inverse_transform(self, X, copy=None): """ Scale back the data to the original representation. :param X: Scaled data matrix. :type X: numpy.ndarray, shape [n_samples, n_features] :param bool copy: Copy the X data matrix. :return: X data matrix with the scaling operat...
[ "def", "inverse_transform", "(", "self", ",", "X", ",", "copy", "=", "None", ")", ":", "check_is_fitted", "(", "self", ",", "'scale_'", ")", "copy", "=", "copy", "if", "copy", "is", "not", "None", "else", "self", ".", "copy", "if", "sparse", ".", "is...
Scale back the data to the original representation. :param X: Scaled data matrix. :type X: numpy.ndarray, shape [n_samples, n_features] :param bool copy: Copy the X data matrix. :return: X data matrix with the scaling operation reverted. :rtype: numpy.ndarray, shape [n_samples, ...
[ "Scale", "back", "the", "data", "to", "the", "original", "representation", "." ]
python
train
34.542857
BD2KGenomics/protect
src/protect/addons/assess_car_t_validity.py
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/addons/assess_car_t_validity.py#L39-L152
def assess_car_t_validity(job, gene_expression, univ_options, reports_options): """ This function creates a report on the available clinical trials and scientific literature available for the overexpressed genes in the specified tumor type. It also gives a list of clinical trials available for other typ...
[ "def", "assess_car_t_validity", "(", "job", ",", "gene_expression", ",", "univ_options", ",", "reports_options", ")", ":", "work_dir", "=", "os", ".", "getcwd", "(", ")", "tumor_type", "=", "univ_options", "[", "'tumor_type'", "]", "input_files", "=", "{", "'r...
This function creates a report on the available clinical trials and scientific literature available for the overexpressed genes in the specified tumor type. It also gives a list of clinical trials available for other types of cancer with the same overexpressed gene. :param toil.fileStore.FileID gene_ex...
[ "This", "function", "creates", "a", "report", "on", "the", "available", "clinical", "trials", "and", "scientific", "literature", "available", "for", "the", "overexpressed", "genes", "in", "the", "specified", "tumor", "type", ".", "It", "also", "gives", "a", "l...
python
train
57.657895
pantsbuild/pants
src/python/pants/base/workunit.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/workunit.py#L289-L291
def _self_time(self): """Returns the time spent in this workunit outside of any children.""" return self.duration() - sum([child.duration() for child in self.children])
[ "def", "_self_time", "(", "self", ")", ":", "return", "self", ".", "duration", "(", ")", "-", "sum", "(", "[", "child", ".", "duration", "(", ")", "for", "child", "in", "self", ".", "children", "]", ")" ]
Returns the time spent in this workunit outside of any children.
[ "Returns", "the", "time", "spent", "in", "this", "workunit", "outside", "of", "any", "children", "." ]
python
train
58
draperjames/qtpandas
qtpandas/models/DataFrameModel.py
https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModel.py#L296-L324
def headerData(self, section, orientation, role=Qt.DisplayRole): """ Return the header depending on section, orientation and Qt::ItemDataRole Args: section (int): For horizontal headers, the section number corresponds to the column number. Similarly, for vertical hea...
[ "def", "headerData", "(", "self", ",", "section", ",", "orientation", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "role", "!=", "Qt", ".", "DisplayRole", ":", "return", "None", "if", "orientation", "==", "Qt", ".", "Horizontal", ":", "t...
Return the header depending on section, orientation and Qt::ItemDataRole Args: section (int): For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number. orientation (Qt::...
[ "Return", "the", "header", "depending", "on", "section", "orientation", "and", "Qt", "::", "ItemDataRole" ]
python
train
38.551724
splunk/splunk-sdk-python
examples/analytics/bottle.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1042-L1056
def wsgiheader(self): ''' Returns a wsgi conform list of header/value pairs. ''' for c in self.COOKIES.values(): if c.OutputString() not in self.headers.getall('Set-Cookie'): self.headers.append('Set-Cookie', c.OutputString()) # rfc2616 section 10.2.3, 10.3.5 ...
[ "def", "wsgiheader", "(", "self", ")", ":", "for", "c", "in", "self", ".", "COOKIES", ".", "values", "(", ")", ":", "if", "c", ".", "OutputString", "(", ")", "not", "in", "self", ".", "headers", ".", "getall", "(", "'Set-Cookie'", ")", ":", "self",...
Returns a wsgi conform list of header/value pairs.
[ "Returns", "a", "wsgi", "conform", "list", "of", "header", "/", "value", "pairs", "." ]
python
train
53.2
MartinThoma/hwrt
hwrt/filter_dataset.py
https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/filter_dataset.py#L179-L197
def read_csv(filepath): """ Read a CSV into a list of dictionarys. The first line of the CSV determines the keys of the dictionary. Parameters ---------- filepath : string Returns ------- list of dictionaries """ symbols = [] with open(filepath, 'rb') as csvfile: ...
[ "def", "read_csv", "(", "filepath", ")", ":", "symbols", "=", "[", "]", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "csvfile", ":", "spamreader", "=", "csv", ".", "DictReader", "(", "csvfile", ",", "delimiter", "=", "','", ",", "quotechar"...
Read a CSV into a list of dictionarys. The first line of the CSV determines the keys of the dictionary. Parameters ---------- filepath : string Returns ------- list of dictionaries
[ "Read", "a", "CSV", "into", "a", "list", "of", "dictionarys", ".", "The", "first", "line", "of", "the", "CSV", "determines", "the", "keys", "of", "the", "dictionary", "." ]
python
train
23.789474
boriel/zxbasic
asmparse.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asmparse.py#L601-L605
def p_program(p): """ program : line """ if p[1] is not None: [MEMORY.add_instruction(x) for x in p[1] if isinstance(x, Asm)]
[ "def", "p_program", "(", "p", ")", ":", "if", "p", "[", "1", "]", "is", "not", "None", ":", "[", "MEMORY", ".", "add_instruction", "(", "x", ")", "for", "x", "in", "p", "[", "1", "]", "if", "isinstance", "(", "x", ",", "Asm", ")", "]" ]
program : line
[ "program", ":", "line" ]
python
train
28.2
RJT1990/pyflux
pyflux/ssm/ndynlin.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/ndynlin.py#L551-L635
def plot_predict(self, h=5, past_values=20, intervals=True, oos_data=None, **kwargs): """ Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) ...
[ "def", "plot_predict", "(", "self", ",", "h", "=", "5", ",", "past_values", "=", "20", ",", "intervals", "=", "True", ",", "oos_data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "seab...
Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations to show on the forecast graph? intervals : Boolean ...
[ "Makes", "forecast", "with", "the", "estimated", "model" ]
python
train
40.917647
pypa/setuptools
setuptools/config.py
https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/config.py#L312-L354
def _parse_attr(cls, value, package_dir=None): """Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str """ attr_directive = 'attr:' if not value.startswith(attr_direc...
[ "def", "_parse_attr", "(", "cls", ",", "value", ",", "package_dir", "=", "None", ")", ":", "attr_directive", "=", "'attr:'", "if", "not", "value", ".", "startswith", "(", "attr_directive", ")", ":", "return", "value", "attrs_path", "=", "value", ".", "repl...
Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str
[ "Represents", "value", "as", "a", "module", "attribute", "." ]
python
train
33.302326
pyroscope/auvyon
src/auvyon/imaging/waveforms.py
https://github.com/pyroscope/auvyon/blob/5115c26f966df03df92a9934580b66c72e23d4e8/src/auvyon/imaging/waveforms.py#L45-L71
def waveform_stack(mediafiles, xy_size, output=None, label_style=None, center_color=None, outer_color=None, bg_color=None): """ Create a stack of waveform images from audio data. Return path to created image file. """ img_files = [] output = output or os.path.abspath(os.path.dirname(os....
[ "def", "waveform_stack", "(", "mediafiles", ",", "xy_size", ",", "output", "=", "None", ",", "label_style", "=", "None", ",", "center_color", "=", "None", ",", "outer_color", "=", "None", ",", "bg_color", "=", "None", ")", ":", "img_files", "=", "[", "]"...
Create a stack of waveform images from audio data. Return path to created image file.
[ "Create", "a", "stack", "of", "waveform", "images", "from", "audio", "data", ".", "Return", "path", "to", "created", "image", "file", "." ]
python
train
40.703704
wglass/lighthouse
lighthouse/zookeeper.py
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/zookeeper.py#L128-L189
def start_watching(self, cluster, callback): """ Initiates the "watching" of a cluster's associated znode. This is done via kazoo's ChildrenWatch object. When a cluster's znode's child nodes are updated, a callback is fired and we update the cluster's `nodes` attribute based on...
[ "def", "start_watching", "(", "self", ",", "cluster", ",", "callback", ")", ":", "logger", ".", "debug", "(", "\"starting to watch cluster %s\"", ",", "cluster", ".", "name", ")", "wait_on_any", "(", "self", ".", "connected", ",", "self", ".", "shutdown", ")...
Initiates the "watching" of a cluster's associated znode. This is done via kazoo's ChildrenWatch object. When a cluster's znode's child nodes are updated, a callback is fired and we update the cluster's `nodes` attribute based on the existing child znodes and fire a passed-in callback ...
[ "Initiates", "the", "watching", "of", "a", "cluster", "s", "associated", "znode", "." ]
python
train
35.548387
chemlab/chemlab
chemlab/io/datafile.py
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/datafile.py#L85-L99
def get_handler_class(ext): """Get the IOHandler that can handle the extension *ext*.""" if ext in _extensions_map: format = _extensions_map[ext] else: raise ValueError("Unknown format for %s extension." % ext) if format in _handler_map: hc = _handler_map[format] return...
[ "def", "get_handler_class", "(", "ext", ")", ":", "if", "ext", "in", "_extensions_map", ":", "format", "=", "_extensions_map", "[", "ext", "]", "else", ":", "raise", "ValueError", "(", "\"Unknown format for %s extension.\"", "%", "ext", ")", "if", "format", "i...
Get the IOHandler that can handle the extension *ext*.
[ "Get", "the", "IOHandler", "that", "can", "handle", "the", "extension", "*", "ext", "*", "." ]
python
train
34.6
happyleavesaoc/python-limitlessled
limitlessled/group/rgbw.py
https://github.com/happyleavesaoc/python-limitlessled/blob/70307c2bf8c91430a99579d2ad18b228ec7a8488/limitlessled/group/rgbw.py#L53-L57
def white(self): """ Set color to white. """ self._color = RGB_WHITE cmd = self.command_set.white() self.send(cmd)
[ "def", "white", "(", "self", ")", ":", "self", ".", "_color", "=", "RGB_WHITE", "cmd", "=", "self", ".", "command_set", ".", "white", "(", ")", "self", ".", "send", "(", "cmd", ")" ]
Set color to white.
[ "Set", "color", "to", "white", "." ]
python
train
28.4
OSSOS/MOP
src/ossos/core/ossos/gui/models/workload.py
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/workload.py#L579-L625
def get_workunit(self, ignore_list=None): """ Gets a new unit of work. Args: ignore_list: list(str) A list of filenames which should be ignored. Defaults to None. Returns: new_workunit: WorkUnit A new unit of work that has not yet been proce...
[ "def", "get_workunit", "(", "self", ",", "ignore_list", "=", "None", ")", ":", "if", "ignore_list", "is", "None", ":", "ignore_list", "=", "[", "]", "potential_files", "=", "self", ".", "get_potential_files", "(", "ignore_list", ")", "while", "len", "(", "...
Gets a new unit of work. Args: ignore_list: list(str) A list of filenames which should be ignored. Defaults to None. Returns: new_workunit: WorkUnit A new unit of work that has not yet been processed. A lock on it has been acquired. Ra...
[ "Gets", "a", "new", "unit", "of", "work", "." ]
python
train
32.021277