repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
wandb/client | wandb/wandb_torch.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/wandb_torch.py#L78-L108 | def add_log_hooks_to_pytorch_module(self, module, name=None, prefix='', log_parameters=True, log_gradients=True, log_freq=0):
""" This instuments hooks into the pytorch module
log_parameters - log parameters after a forward pass
log_gradients - log gradients after a backward pass
log_fre... | [
"def",
"add_log_hooks_to_pytorch_module",
"(",
"self",
",",
"module",
",",
"name",
"=",
"None",
",",
"prefix",
"=",
"''",
",",
"log_parameters",
"=",
"True",
",",
"log_gradients",
"=",
"True",
",",
"log_freq",
"=",
"0",
")",
":",
"if",
"name",
"is",
"not... | This instuments hooks into the pytorch module
log_parameters - log parameters after a forward pass
log_gradients - log gradients after a backward pass
log_freq - log gradients/parameters every N batches | [
"This",
"instuments",
"hooks",
"into",
"the",
"pytorch",
"module",
"log_parameters",
"-",
"log",
"parameters",
"after",
"a",
"forward",
"pass",
"log_gradients",
"-",
"log",
"gradients",
"after",
"a",
"backward",
"pass",
"log_freq",
"-",
"log",
"gradients",
"/",
... | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L12130-L12150 | def spkopn(filename, ifname, ncomch):
"""
Create a new SPK file, returning the handle of the opened file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkopn_c.html
:param filename: The name of the new SPK file to be created.
:type filename: str
:param ifname: The internal filename ... | [
"def",
"spkopn",
"(",
"filename",
",",
"ifname",
",",
"ncomch",
")",
":",
"filename",
"=",
"stypes",
".",
"stringToCharP",
"(",
"filename",
")",
"ifname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ifname",
")",
"ncomch",
"=",
"ctypes",
".",
"c_int",
"("... | Create a new SPK file, returning the handle of the opened file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkopn_c.html
:param filename: The name of the new SPK file to be created.
:type filename: str
:param ifname: The internal filename for the SPK file.
:type ifname: str
:param... | [
"Create",
"a",
"new",
"SPK",
"file",
"returning",
"the",
"handle",
"of",
"the",
"opened",
"file",
"."
] | python | train |
eddiejessup/spatious | spatious/vector.py | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L185-L216 | def sphere_pick_polar(d, n=1, rng=None):
"""Return vectors uniformly picked on the unit sphere.
Vectors are in a polar representation.
Parameters
----------
d: float
The number of dimensions of the space in which the sphere lives.
n: integer
Number of samples to pick.
Retur... | [
"def",
"sphere_pick_polar",
"(",
"d",
",",
"n",
"=",
"1",
",",
"rng",
"=",
"None",
")",
":",
"if",
"rng",
"is",
"None",
":",
"rng",
"=",
"np",
".",
"random",
"a",
"=",
"np",
".",
"empty",
"(",
"[",
"n",
",",
"d",
"]",
")",
"if",
"d",
"==",
... | Return vectors uniformly picked on the unit sphere.
Vectors are in a polar representation.
Parameters
----------
d: float
The number of dimensions of the space in which the sphere lives.
n: integer
Number of samples to pick.
Returns
-------
r: array, shape (n, d)
... | [
"Return",
"vectors",
"uniformly",
"picked",
"on",
"the",
"unit",
"sphere",
".",
"Vectors",
"are",
"in",
"a",
"polar",
"representation",
"."
] | python | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/tasklets.py | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/tasklets.py#L214-L227 | def _init_flow_exceptions():
"""Internal helper to initialize _flow_exceptions.
This automatically adds webob.exc.HTTPException, if it can be imported.
"""
global _flow_exceptions
_flow_exceptions = ()
add_flow_exception(datastore_errors.Rollback)
try:
from webob import exc
except ImportError:
... | [
"def",
"_init_flow_exceptions",
"(",
")",
":",
"global",
"_flow_exceptions",
"_flow_exceptions",
"=",
"(",
")",
"add_flow_exception",
"(",
"datastore_errors",
".",
"Rollback",
")",
"try",
":",
"from",
"webob",
"import",
"exc",
"except",
"ImportError",
":",
"pass",... | Internal helper to initialize _flow_exceptions.
This automatically adds webob.exc.HTTPException, if it can be imported. | [
"Internal",
"helper",
"to",
"initialize",
"_flow_exceptions",
"."
] | python | train |
klahnakoski/pyLibrary | jx_elasticsearch/es52/setop.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_elasticsearch/es52/setop.py#L409-L453 | def es_query_proto(path, selects, wheres, schema):
"""
RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE
:param path: THE NESTED PATH (NOT INCLUDING TABLE NAME)
:param wheres: MAP FROM path TO LIST OF WHERE CONDITIONS
:return: (es_query, filters_map) TUPLE
"""
output = None
last_where = MA... | [
"def",
"es_query_proto",
"(",
"path",
",",
"selects",
",",
"wheres",
",",
"schema",
")",
":",
"output",
"=",
"None",
"last_where",
"=",
"MATCH_ALL",
"for",
"p",
"in",
"reversed",
"(",
"sorted",
"(",
"wheres",
".",
"keys",
"(",
")",
"|",
"set",
"(",
"... | RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE
:param path: THE NESTED PATH (NOT INCLUDING TABLE NAME)
:param wheres: MAP FROM path TO LIST OF WHERE CONDITIONS
:return: (es_query, filters_map) TUPLE | [
"RETURN",
"TEMPLATE",
"AND",
"PATH",
"-",
"TO",
"-",
"FILTER",
"AS",
"A",
"2",
"-",
"TUPLE",
":",
"param",
"path",
":",
"THE",
"NESTED",
"PATH",
"(",
"NOT",
"INCLUDING",
"TABLE",
"NAME",
")",
":",
"param",
"wheres",
":",
"MAP",
"FROM",
"path",
"TO",
... | python | train |
eventbrite/eventbrite-sdk-python | eventbrite/access_methods.py | https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/access_methods.py#L792-L800 | def get_user_owned_event_attendees(self, id, **data):
"""
GET /users/:id/owned_event_attendees/
Returns a :ref:`paginated <pagination>` response of :format:`attendees <attendee>`,
under the key ``attendees``, of attendees visiting any of the events the user owns
(events that woul... | [
"def",
"get_user_owned_event_attendees",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"/users/{0}/owned_event_attendees/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | GET /users/:id/owned_event_attendees/
Returns a :ref:`paginated <pagination>` response of :format:`attendees <attendee>`,
under the key ``attendees``, of attendees visiting any of the events the user owns
(events that would be returned from ``/users/:id/owned_events/``) | [
"GET",
"/",
"users",
"/",
":",
"id",
"/",
"owned_event_attendees",
"/",
"Returns",
"a",
":",
"ref",
":",
"paginated",
"<pagination",
">",
"response",
"of",
":",
"format",
":",
"attendees",
"<attendee",
">",
"under",
"the",
"key",
"attendees",
"of",
"attend... | python | train |
chaosim/dao | dao/builtins/terminal.py | https://github.com/chaosim/dao/blob/d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa/dao/builtins/terminal.py#L59-L78 | def char_on_predicate(compiler, cont, test):
'''return current char and step if @test succeed, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
test = test.interlang()
text = compiler.new_var(il.C... | [
"def",
"char_on_predicate",
"(",
"compiler",
",",
"cont",
",",
"test",
")",
":",
"test",
"=",
"test",
".",
"interlang",
"(",
")",
"text",
"=",
"compiler",
".",
"new_var",
"(",
"il",
".",
"ConstLocalVar",
"(",
"'text'",
")",
")",
"pos",
"=",
"compiler",... | return current char and step if @test succeed, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function | [
"return",
"current",
"char",
"and",
"step",
"if"
] | python | train |
josiah-wolf-oberholtzer/uqbar | uqbar/sphinx/book.py | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/book.py#L116-L128 | def on_build_finished(app, exception):
"""
Hooks into Sphinx's ``build-finished`` event.
"""
if not app.config["uqbar_book_use_cache"]:
return
logger.info("")
for row in app.connection.execute("SELECT path, hits FROM cache ORDER BY path"):
path, hits = row
if not hits:
... | [
"def",
"on_build_finished",
"(",
"app",
",",
"exception",
")",
":",
"if",
"not",
"app",
".",
"config",
"[",
"\"uqbar_book_use_cache\"",
"]",
":",
"return",
"logger",
".",
"info",
"(",
"\"\"",
")",
"for",
"row",
"in",
"app",
".",
"connection",
".",
"execu... | Hooks into Sphinx's ``build-finished`` event. | [
"Hooks",
"into",
"Sphinx",
"s",
"build",
"-",
"finished",
"event",
"."
] | python | train |
manahl/arctic | arctic/arctic.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/arctic.py#L328-L361 | def get_library(self, library):
"""
Return the library instance. Can generally use slicing to return the library:
arctic_store[library]
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library'
"""
if... | [
"def",
"get_library",
"(",
"self",
",",
"library",
")",
":",
"if",
"library",
"in",
"self",
".",
"_library_cache",
":",
"return",
"self",
".",
"_library_cache",
"[",
"library",
"]",
"try",
":",
"error",
"=",
"None",
"lib",
"=",
"ArcticLibraryBinding",
"(",... | Return the library instance. Can generally use slicing to return the library:
arctic_store[library]
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library' | [
"Return",
"the",
"library",
"instance",
".",
"Can",
"generally",
"use",
"slicing",
"to",
"return",
"the",
"library",
":",
"arctic_store",
"[",
"library",
"]"
] | python | train |
shoebot/shoebot | shoebot/data/bezier.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/bezier.py#L340-L370 | def _locate(self, t, segments=None):
""" Locates t on a specific segment in the path.
Returns (index, t, PathElement)
A path is a combination of lines and curves (segments).
The returned index indicates the start of the segment that contains point t.
The returned ... | [
"def",
"_locate",
"(",
"self",
",",
"t",
",",
"segments",
"=",
"None",
")",
":",
"# Originally from nodebox-gl",
"if",
"segments",
"is",
"None",
":",
"segments",
"=",
"self",
".",
"_segment_lengths",
"(",
"relative",
"=",
"True",
")",
"if",
"len",
"(",
"... | Locates t on a specific segment in the path.
Returns (index, t, PathElement)
A path is a combination of lines and curves (segments).
The returned index indicates the start of the segment that contains point t.
The returned t is the absolute time on that segment,
... | [
"Locates",
"t",
"on",
"a",
"specific",
"segment",
"in",
"the",
"path",
".",
"Returns",
"(",
"index",
"t",
"PathElement",
")",
"A",
"path",
"is",
"a",
"combination",
"of",
"lines",
"and",
"curves",
"(",
"segments",
")",
".",
"The",
"returned",
"index",
... | python | valid |
ardexa/ardexaplugin | ardexaplugin.py | https://github.com/ardexa/ardexaplugin/blob/5068532f601ae3042bd87af1063057e8f274f670/ardexaplugin.py#L88-L108 | def check_pidfile(pidfile, debug):
"""Check that a process is not running more than once, using PIDFILE"""
# Check PID exists and see if the PID is running
if os.path.isfile(pidfile):
pidfile_handle = open(pidfile, 'r')
# try and read the PID file. If no luck, remove it
try:
... | [
"def",
"check_pidfile",
"(",
"pidfile",
",",
"debug",
")",
":",
"# Check PID exists and see if the PID is running",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"pidfile",
")",
":",
"pidfile_handle",
"=",
"open",
"(",
"pidfile",
",",
"'r'",
")",
"# try and read ... | Check that a process is not running more than once, using PIDFILE | [
"Check",
"that",
"a",
"process",
"is",
"not",
"running",
"more",
"than",
"once",
"using",
"PIDFILE"
] | python | valid |
Jammy2211/PyAutoLens | autolens/data/array/grids.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L123-L138 | def grid_stack_from_mask_sub_grid_size_and_psf_shape(cls, mask, sub_grid_size, psf_shape):
"""Setup a grid-stack of grid_stack from a mask, sub-grid size and psf-shape.
Parameters
-----------
mask : Mask
The mask whose unmasked pixels (*False*) are used to generate the grid-... | [
"def",
"grid_stack_from_mask_sub_grid_size_and_psf_shape",
"(",
"cls",
",",
"mask",
",",
"sub_grid_size",
",",
"psf_shape",
")",
":",
"regular_grid",
"=",
"RegularGrid",
".",
"from_mask",
"(",
"mask",
")",
"sub_grid",
"=",
"SubGrid",
".",
"from_mask_and_sub_grid_size"... | Setup a grid-stack of grid_stack from a mask, sub-grid size and psf-shape.
Parameters
-----------
mask : Mask
The mask whose unmasked pixels (*False*) are used to generate the grid-stack's grid_stack.
sub_grid_size : int
The size of a sub-pixel's sub-grid (sub_gr... | [
"Setup",
"a",
"grid",
"-",
"stack",
"of",
"grid_stack",
"from",
"a",
"mask",
"sub",
"-",
"grid",
"size",
"and",
"psf",
"-",
"shape",
"."
] | python | valid |
great-expectations/great_expectations | great_expectations/dataset/dataset.py | https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L658-L719 | def expect_column_values_to_be_between(self,
column,
min_value=None,
max_value=None,
allow_cross_type_comparisons=None,
... | [
"def",
"expect_column_values_to_be_between",
"(",
"self",
",",
"column",
",",
"min_value",
"=",
"None",
",",
"max_value",
"=",
"None",
",",
"allow_cross_type_comparisons",
"=",
"None",
",",
"parse_strings_as_datetimes",
"=",
"None",
",",
"output_strftime_format",
"=",... | Expect column entries to be between a minimum value and a maximum value (inclusive).
expect_column_values_to_be_between is a :func:`column_map_expectation <great_expectations.data_asset.dataset.Dataset.column_map_expectation>`.
Args:
column (str): \
The column name.
... | [
"Expect",
"column",
"entries",
"to",
"be",
"between",
"a",
"minimum",
"value",
"and",
"a",
"maximum",
"value",
"(",
"inclusive",
")",
"."
] | python | train |
IdentityPython/pysaml2 | src/saml2/server.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/server.py#L221-L231 | def parse_authn_request(self, enc_request, binding=BINDING_HTTP_REDIRECT):
"""Parse a Authentication Request
:param enc_request: The request in its transport format
:param binding: Which binding that was used to transport the message
to this entity.
:return: A request instan... | [
"def",
"parse_authn_request",
"(",
"self",
",",
"enc_request",
",",
"binding",
"=",
"BINDING_HTTP_REDIRECT",
")",
":",
"return",
"self",
".",
"_parse_request",
"(",
"enc_request",
",",
"AuthnRequest",
",",
"\"single_sign_on_service\"",
",",
"binding",
")"
] | Parse a Authentication Request
:param enc_request: The request in its transport format
:param binding: Which binding that was used to transport the message
to this entity.
:return: A request instance | [
"Parse",
"a",
"Authentication",
"Request"
] | python | train |
pmelchior/proxmin | examples/unmixing.py | https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/unmixing.py#L28-L30 | def add_noise(Y, sigma):
"""Adds noise to Y"""
return Y + np.random.normal(0, sigma, Y.shape) | [
"def",
"add_noise",
"(",
"Y",
",",
"sigma",
")",
":",
"return",
"Y",
"+",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"sigma",
",",
"Y",
".",
"shape",
")"
] | Adds noise to Y | [
"Adds",
"noise",
"to",
"Y"
] | python | train |
saltstack/salt | salt/modules/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L2355-L2422 | def event(tagmatch='*',
count=-1,
quiet=False,
sock_dir=None,
pretty=False,
node='minion'):
r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2016.3.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be eith... | [
"def",
"event",
"(",
"tagmatch",
"=",
"'*'",
",",
"count",
"=",
"-",
"1",
",",
"quiet",
"=",
"False",
",",
"sock_dir",
"=",
"None",
",",
"pretty",
"=",
"False",
",",
"node",
"=",
"'minion'",
")",
":",
"sevent",
"=",
"salt",
".",
"utils",
".",
"ev... | r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2016.3.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is useful for utilizing Salt's event bus from shell scripts or for
taking simple actions directly f... | [
"r",
"Watch",
"Salt",
"s",
"event",
"bus",
"and",
"block",
"until",
"the",
"given",
"tag",
"is",
"matched"
] | python | train |
etingof/pysnmp | pysnmp/hlapi/v3arch/asyncore/ntforg.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/asyncore/ntforg.py#L21-L174 | def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyType, *varBinds, **options):
"""Send SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM
notification (:RFC:`1905#section-4.2.6`) and schedules its
transmission by I/O framework a... | [
"def",
"sendNotification",
"(",
"snmpEngine",
",",
"authData",
",",
"transportTarget",
",",
"contextData",
",",
"notifyType",
",",
"*",
"varBinds",
",",
"*",
"*",
"options",
")",
":",
"# noinspection PyShadowingNames",
"def",
"__cbFun",
"(",
"snmpEngine",
",",
"... | Send SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM
notification (:RFC:`1905#section-4.2.6`) and schedules its
transmission by I/O framework at a later point of time.
Parameters
----------
snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance rep... | [
"Send",
"SNMP",
"notification",
"."
] | python | train |
librosa/librosa | librosa/feature/utils.py | https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/utils.py#L119-L252 | def stack_memory(data, n_steps=2, delay=1, **kwargs):
"""Short-term history embedding: vertically concatenate a data
vector or matrix with delayed copies of itself.
Each column `data[:, i]` is mapped to::
data[:, i] -> [data[:, i],
data[:, i - delay],
... | [
"def",
"stack_memory",
"(",
"data",
",",
"n_steps",
"=",
"2",
",",
"delay",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"n_steps",
"<",
"1",
":",
"raise",
"ParameterError",
"(",
"'n_steps must be a positive integer'",
")",
"if",
"delay",
"==",
"0"... | Short-term history embedding: vertically concatenate a data
vector or matrix with delayed copies of itself.
Each column `data[:, i]` is mapped to::
data[:, i] -> [data[:, i],
data[:, i - delay],
...
data[:, i - (n_steps-1)*delay]... | [
"Short",
"-",
"term",
"history",
"embedding",
":",
"vertically",
"concatenate",
"a",
"data",
"vector",
"or",
"matrix",
"with",
"delayed",
"copies",
"of",
"itself",
"."
] | python | test |
jtwhite79/pyemu | pyemu/pst/pst_handler.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/pst/pst_handler.py#L448-L462 | def adj_par_names(self):
""" get the adjustable (not fixed or tied) parameter names
Returns
-------
adj_par_names : list
list of adjustable (not fixed or tied) parameter names
"""
adj_names = []
for t,n in zip(self.parameter_data.partrans,
... | [
"def",
"adj_par_names",
"(",
"self",
")",
":",
"adj_names",
"=",
"[",
"]",
"for",
"t",
",",
"n",
"in",
"zip",
"(",
"self",
".",
"parameter_data",
".",
"partrans",
",",
"self",
".",
"parameter_data",
".",
"parnme",
")",
":",
"if",
"t",
".",
"lower",
... | get the adjustable (not fixed or tied) parameter names
Returns
-------
adj_par_names : list
list of adjustable (not fixed or tied) parameter names | [
"get",
"the",
"adjustable",
"(",
"not",
"fixed",
"or",
"tied",
")",
"parameter",
"names"
] | python | train |
juju/python-libjuju | juju/client/_client5.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client5.py#L3012-L3035 | async def CreateModel(self, cloud_tag, config, credential, name, owner_tag, region):
'''
cloud_tag : str
config : typing.Mapping[str, typing.Any]
credential : str
name : str
owner_tag : str
region : str
Returns -> typing.Union[_ForwardRef('Number'), str, t... | [
"async",
"def",
"CreateModel",
"(",
"self",
",",
"cloud_tag",
",",
"config",
",",
"credential",
",",
"name",
",",
"owner_tag",
",",
"region",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
... | cloud_tag : str
config : typing.Mapping[str, typing.Any]
credential : str
name : str
owner_tag : str
region : str
Returns -> typing.Union[_ForwardRef('Number'), str, typing.Sequence[~ModelMachineInfo], _ForwardRef('ModelMigrationStatus'), _ForwardRef('ModelSLAInfo'), _For... | [
"cloud_tag",
":",
"str",
"config",
":",
"typing",
".",
"Mapping",
"[",
"str",
"typing",
".",
"Any",
"]",
"credential",
":",
"str",
"name",
":",
"str",
"owner_tag",
":",
"str",
"region",
":",
"str",
"Returns",
"-",
">",
"typing",
".",
"Union",
"[",
"_... | python | train |
buildbot/buildbot_travis | buildbot_travis/steps/create_steps.py | https://github.com/buildbot/buildbot_travis/blob/350c657b7aabaf5bc6a9fdb55febdd9d8eabd60c/buildbot_travis/steps/create_steps.py#L84-L92 | def setupEnvironment(self, cmd):
""" Turn all build properties into environment variables """
shell.ShellCommand.setupEnvironment(self, cmd)
env = {}
for k, v in self.build.getProperties().properties.items():
env[str(k)] = str(v[0])
if cmd.args['env'] is None:
... | [
"def",
"setupEnvironment",
"(",
"self",
",",
"cmd",
")",
":",
"shell",
".",
"ShellCommand",
".",
"setupEnvironment",
"(",
"self",
",",
"cmd",
")",
"env",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"build",
".",
"getProperties",
"(",
")",... | Turn all build properties into environment variables | [
"Turn",
"all",
"build",
"properties",
"into",
"environment",
"variables"
] | python | train |
linkhub-sdk/popbill.py | popbill/taxinvoiceService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/taxinvoiceService.py#L514-L533 | def sendToNTS(self, CorpNum, MgtKeyType, MgtKey, UserID=None):
""" 국세청 즉시전송
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
UserID : 팝빌 회원아이디
return
처리결과. consi... | [
"def",
"sendToNTS",
"(",
"self",
",",
"CorpNum",
",",
"MgtKeyType",
",",
"MgtKey",
",",
"UserID",
"=",
"None",
")",
":",
"if",
"MgtKeyType",
"not",
"in",
"self",
".",
"__MgtKeyTypes",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"관리번호 형태가... | 국세청 즉시전송
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
UserID : 팝빌 회원아이디
return
처리결과. consist of code and message
raise
PopbillException | [
"국세청",
"즉시전송",
"args",
"CorpNum",
":",
"회원",
"사업자",
"번호",
"MgtKeyType",
":",
"관리번호",
"유형",
"one",
"of",
"[",
"SELL",
"BUY",
"TRUSTEE",
"]",
"MgtKey",
":",
"파트너",
"관리번호",
"UserID",
":",
"팝빌",
"회원아이디",
"return",
"처리결과",
".",
"consist",
"of",
"code",
"a... | python | train |
vatlab/SoS | src/sos/utils.py | https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L598-L608 | def dehtml(text):
'''Remove HTML tag in input text and format the texts
accordingly. '''
try:
parser = _DeHTMLParser()
parser.feed(text)
parser.close()
return parser.text()
except Exception as e:
env.logger.warning(f'Failed to dehtml text: {e}')
return tex... | [
"def",
"dehtml",
"(",
"text",
")",
":",
"try",
":",
"parser",
"=",
"_DeHTMLParser",
"(",
")",
"parser",
".",
"feed",
"(",
"text",
")",
"parser",
".",
"close",
"(",
")",
"return",
"parser",
".",
"text",
"(",
")",
"except",
"Exception",
"as",
"e",
":... | Remove HTML tag in input text and format the texts
accordingly. | [
"Remove",
"HTML",
"tag",
"in",
"input",
"text",
"and",
"format",
"the",
"texts",
"accordingly",
"."
] | python | train |
tgalal/yowsup | yowsup/config/base/serialize.py | https://github.com/tgalal/yowsup/blob/b0739461ba962bf221fc76047d9d60d8ce61bc3e/yowsup/config/base/serialize.py#L6-L15 | def serialize(self, config):
"""
:param config:
:type config: yowsup.config.base.config.Config
:return:
:rtype: bytes
"""
for transform in self._transforms:
config = transform.transform(config)
return config | [
"def",
"serialize",
"(",
"self",
",",
"config",
")",
":",
"for",
"transform",
"in",
"self",
".",
"_transforms",
":",
"config",
"=",
"transform",
".",
"transform",
"(",
"config",
")",
"return",
"config"
] | :param config:
:type config: yowsup.config.base.config.Config
:return:
:rtype: bytes | [
":",
"param",
"config",
":",
":",
"type",
"config",
":",
"yowsup",
".",
"config",
".",
"base",
".",
"config",
".",
"Config",
":",
"return",
":",
":",
"rtype",
":",
"bytes"
] | python | train |
Esri/ArcREST | src/arcrest/common/general.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/general.py#L609-L636 | def fromJSON(jsonValue):
"""returns a featureset from a JSON string"""
jd = json.loads(jsonValue)
features = []
if 'fields' in jd:
fields = jd['fields']
else:
fields = {'fields':[]}
if 'features' in jd:
for feat in jd['features']:
... | [
"def",
"fromJSON",
"(",
"jsonValue",
")",
":",
"jd",
"=",
"json",
".",
"loads",
"(",
"jsonValue",
")",
"features",
"=",
"[",
"]",
"if",
"'fields'",
"in",
"jd",
":",
"fields",
"=",
"jd",
"[",
"'fields'",
"]",
"else",
":",
"fields",
"=",
"{",
"'field... | returns a featureset from a JSON string | [
"returns",
"a",
"featureset",
"from",
"a",
"JSON",
"string"
] | python | train |
mitsei/dlkit | dlkit/handcar/relationship/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/relationship/managers.py#L535-L567 | def get_relationship_admin_session_for_family(self, family_id=None):
"""Gets the ``OsidSession`` associated with the relationship administration service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family``
return: (osid.relationship.RelationshipAdminSession) - a
... | [
"def",
"get_relationship_admin_session_for_family",
"(",
"self",
",",
"family_id",
"=",
"None",
")",
":",
"if",
"not",
"family_id",
":",
"raise",
"NullArgument",
"if",
"not",
"self",
".",
"supports_relationship_admin",
"(",
")",
":",
"raise",
"Unimplemented",
"(",... | Gets the ``OsidSession`` associated with the relationship administration service for the given family.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family``
return: (osid.relationship.RelationshipAdminSession) - a
``RelationshipAdminSession``
raise: NotFound - no family ... | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"the",
"relationship",
"administration",
"service",
"for",
"the",
"given",
"family",
"."
] | python | train |
klen/peewee_migrate | peewee_migrate/router.py | https://github.com/klen/peewee_migrate/blob/b77895ab1c9be3121bc127e0c2dfb047eed8b24c/peewee_migrate/router.py#L134-L168 | def run_one(self, name, migrator, fake=True, downgrade=False, force=False):
"""Run/emulate a migration with given name."""
try:
migrate, rollback = self.read(name)
if fake:
with mock.patch('peewee.Model.select'):
with mock.patch('peewee.Query._... | [
"def",
"run_one",
"(",
"self",
",",
"name",
",",
"migrator",
",",
"fake",
"=",
"True",
",",
"downgrade",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"try",
":",
"migrate",
",",
"rollback",
"=",
"self",
".",
"read",
"(",
"name",
")",
"if",
... | Run/emulate a migration with given name. | [
"Run",
"/",
"emulate",
"a",
"migration",
"with",
"given",
"name",
"."
] | python | train |
DataONEorg/d1_python | lib_client/src/d1_client/cnclient.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/cnclient.py#L100-L111 | def getFormat(self, formatId, vendorSpecific=None):
"""See Also: getFormatResponse()
Args:
formatId:
vendorSpecific:
Returns:
"""
response = self.getFormatResponse(formatId, vendorSpecific)
return self._read_dataone_type_response(response, 'ObjectFo... | [
"def",
"getFormat",
"(",
"self",
",",
"formatId",
",",
"vendorSpecific",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"getFormatResponse",
"(",
"formatId",
",",
"vendorSpecific",
")",
"return",
"self",
".",
"_read_dataone_type_response",
"(",
"response",... | See Also: getFormatResponse()
Args:
formatId:
vendorSpecific:
Returns: | [
"See",
"Also",
":",
"getFormatResponse",
"()"
] | python | train |
gem/oq-engine | openquake/hmtk/plotting/seismicity/catalogue_plots.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L261-L342 | def plot_magnitude_time_density(
catalogue, mag_int, time_int, completeness=None,
normalisation=False, logscale=True, bootstrap=None, xlim=[], ylim=[],
filename=None, figure_size=(8, 6), filetype='png', dpi=300, ax=None):
"""
Creates a plot of magnitude-time density
:param catalogue... | [
"def",
"plot_magnitude_time_density",
"(",
"catalogue",
",",
"mag_int",
",",
"time_int",
",",
"completeness",
"=",
"None",
",",
"normalisation",
"=",
"False",
",",
"logscale",
"=",
"True",
",",
"bootstrap",
"=",
"None",
",",
"xlim",
"=",
"[",
"]",
",",
"yl... | Creates a plot of magnitude-time density
:param catalogue:
Earthquake catalogue as instance of :class:
openquake.hmtk.seismicity.catalogue.Catalogue
:param float mag_int:
Width of the histogram for the magnitude bins
:param float time_int:
Width of the histogram for the time... | [
"Creates",
"a",
"plot",
"of",
"magnitude",
"-",
"time",
"density"
] | python | train |
ceph/ceph-deploy | ceph_deploy/config.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/config.py#L81-L111 | def make(parser):
"""
Copy ceph.conf to/from remote host(s)
"""
config_parser = parser.add_subparsers(dest='subcommand')
config_parser.required = True
config_push = config_parser.add_parser(
'push',
help='push Ceph config file to one or more remote hosts'
)
config_pu... | [
"def",
"make",
"(",
"parser",
")",
":",
"config_parser",
"=",
"parser",
".",
"add_subparsers",
"(",
"dest",
"=",
"'subcommand'",
")",
"config_parser",
".",
"required",
"=",
"True",
"config_push",
"=",
"config_parser",
".",
"add_parser",
"(",
"'push'",
",",
"... | Copy ceph.conf to/from remote host(s) | [
"Copy",
"ceph",
".",
"conf",
"to",
"/",
"from",
"remote",
"host",
"(",
"s",
")"
] | python | train |
rsgalloway/grit | grit/server/git_http_backend.py | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/git_http_backend.py#L162-L212 | def add(self, path, default_handler = None, **http_methods):
"""
Add a selector mapping.
add(path, default_handler, **named_handlers)
Adding order is important. Firt added = first matched.
If you want to hand special case URI handled by one app and shorter
versi... | [
"def",
"add",
"(",
"self",
",",
"path",
",",
"default_handler",
"=",
"None",
",",
"*",
"*",
"http_methods",
")",
":",
"if",
"default_handler",
":",
"methods",
"=",
"defaultdict",
"(",
"lambda",
":",
"default_handler",
",",
"http_methods",
".",
"copy",
"(",... | Add a selector mapping.
add(path, default_handler, **named_handlers)
Adding order is important. Firt added = first matched.
If you want to hand special case URI handled by one app and shorter
version of the same regex string by anoter app,
.add() special case first.
... | [
"Add",
"a",
"selector",
"mapping",
".",
"add",
"(",
"path",
"default_handler",
"**",
"named_handlers",
")",
"Adding",
"order",
"is",
"important",
".",
"Firt",
"added",
"=",
"first",
"matched",
".",
"If",
"you",
"want",
"to",
"hand",
"special",
"case",
"URI... | python | train |
numenta/nupic | src/nupic/swarming/dummy_model_runner.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/dummy_model_runner.py#L339-L349 | def _loadDummyModelParameters(self, params):
""" Loads all the parameters for this dummy model. For any paramters
specified as lists, read the appropriate value for this model using the model
index """
for key, value in params.iteritems():
if type(value) == list:
index = self.modelIndex %... | [
"def",
"_loadDummyModelParameters",
"(",
"self",
",",
"params",
")",
":",
"for",
"key",
",",
"value",
"in",
"params",
".",
"iteritems",
"(",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"list",
":",
"index",
"=",
"self",
".",
"modelIndex",
"%",
"... | Loads all the parameters for this dummy model. For any paramters
specified as lists, read the appropriate value for this model using the model
index | [
"Loads",
"all",
"the",
"parameters",
"for",
"this",
"dummy",
"model",
".",
"For",
"any",
"paramters",
"specified",
"as",
"lists",
"read",
"the",
"appropriate",
"value",
"for",
"this",
"model",
"using",
"the",
"model",
"index"
] | python | valid |
klen/makesite | makesite/core.py | https://github.com/klen/makesite/blob/f6f77a43a04a256189e8fffbeac1ffd63f35a10c/makesite/core.py#L109-L114 | def get_base_modules():
" Get list of installed modules. "
return sorted(filter(
lambda x: op.isdir(op.join(MOD_DIR, x)),
listdir(MOD_DIR))) | [
"def",
"get_base_modules",
"(",
")",
":",
"return",
"sorted",
"(",
"filter",
"(",
"lambda",
"x",
":",
"op",
".",
"isdir",
"(",
"op",
".",
"join",
"(",
"MOD_DIR",
",",
"x",
")",
")",
",",
"listdir",
"(",
"MOD_DIR",
")",
")",
")"
] | Get list of installed modules. | [
"Get",
"list",
"of",
"installed",
"modules",
"."
] | python | train |
vicalloy/lbutils | lbutils/qs.py | https://github.com/vicalloy/lbutils/blob/66ae7e73bc939f073cdc1b91602a95e67caf4ba6/lbutils/qs.py#L52-L72 | def do_filter(qs, qdata, quick_query_fields=[], int_quick_query_fields=[]):
"""
auto filter queryset by dict.
qs: queryset need to filter.
qdata:
quick_query_fields:
int_quick_query_fields:
"""
try:
qs = qs.filter(
__gen_quick_query_params(
qdata.get(... | [
"def",
"do_filter",
"(",
"qs",
",",
"qdata",
",",
"quick_query_fields",
"=",
"[",
"]",
",",
"int_quick_query_fields",
"=",
"[",
"]",
")",
":",
"try",
":",
"qs",
"=",
"qs",
".",
"filter",
"(",
"__gen_quick_query_params",
"(",
"qdata",
".",
"get",
"(",
"... | auto filter queryset by dict.
qs: queryset need to filter.
qdata:
quick_query_fields:
int_quick_query_fields: | [
"auto",
"filter",
"queryset",
"by",
"dict",
"."
] | python | train |
GeorgeArgyros/symautomata | symautomata/pdastring.py | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/pdastring.py#L437-L501 | def _stage(self, accepted, count=0):
"""This is a repeated state in the state removal algorithm"""
new5 = self._combine_rest_push()
new1 = self._combine_push_pop()
new2 = self._combine_push_rest()
new3 = self._combine_pop_rest()
new4 = self._combine_rest_rest()
ne... | [
"def",
"_stage",
"(",
"self",
",",
"accepted",
",",
"count",
"=",
"0",
")",
":",
"new5",
"=",
"self",
".",
"_combine_rest_push",
"(",
")",
"new1",
"=",
"self",
".",
"_combine_push_pop",
"(",
")",
"new2",
"=",
"self",
".",
"_combine_push_rest",
"(",
")"... | This is a repeated state in the state removal algorithm | [
"This",
"is",
"a",
"repeated",
"state",
"in",
"the",
"state",
"removal",
"algorithm"
] | python | train |
childsish/lhc-python | lhc/graph/hyper_graph.py | https://github.com/childsish/lhc-python/blob/0a669f46a40a39f24d28665e8b5b606dc7e86beb/lhc/graph/hyper_graph.py#L25-L31 | def add_vertex(self, v):
""" Add a vertex to the graph
:param v: The vertex name.
"""
self.graph.add_vertex(v)
self.vs.add(v) | [
"def",
"add_vertex",
"(",
"self",
",",
"v",
")",
":",
"self",
".",
"graph",
".",
"add_vertex",
"(",
"v",
")",
"self",
".",
"vs",
".",
"add",
"(",
"v",
")"
] | Add a vertex to the graph
:param v: The vertex name. | [
"Add",
"a",
"vertex",
"to",
"the",
"graph"
] | python | train |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shcoeffsgrid.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shcoeffsgrid.py#L2876-L2879 | def _lons(self):
"""Return the longitudes (in degrees) of the gridded data."""
lons = _np.linspace(0.0, 360.0 - 360.0 / self.nlon, num=self.nlon)
return lons | [
"def",
"_lons",
"(",
"self",
")",
":",
"lons",
"=",
"_np",
".",
"linspace",
"(",
"0.0",
",",
"360.0",
"-",
"360.0",
"/",
"self",
".",
"nlon",
",",
"num",
"=",
"self",
".",
"nlon",
")",
"return",
"lons"
] | Return the longitudes (in degrees) of the gridded data. | [
"Return",
"the",
"longitudes",
"(",
"in",
"degrees",
")",
"of",
"the",
"gridded",
"data",
"."
] | python | train |
gmr/rejected | rejected/mixins.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mixins.py#L32-L40 | def collection_cycle(self, value):
"""Set the number of messages to process before invoking ``gc.collect``
:param int value: Cycle size
"""
if value is not None:
self._collection_cycle = value
self._cycles_left = min(self._cycles_left, self._collection_cycle) | [
"def",
"collection_cycle",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"_collection_cycle",
"=",
"value",
"self",
".",
"_cycles_left",
"=",
"min",
"(",
"self",
".",
"_cycles_left",
",",
"self",
".",
"_collec... | Set the number of messages to process before invoking ``gc.collect``
:param int value: Cycle size | [
"Set",
"the",
"number",
"of",
"messages",
"to",
"process",
"before",
"invoking",
"gc",
".",
"collect"
] | python | train |
TrafficSenseMSD/SumoTools | traci/_vehicle.py | https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/traci/_vehicle.py#L989-L999 | def setColor(self, vehID, color):
"""setColor(string, (integer, integer, integer, integer))
sets color for vehicle with the given ID.
i.e. (255,0,0,0) for the color red.
The fourth integer (alpha) is only used when drawing vehicles with raster images
"""
self._connection.... | [
"def",
"setColor",
"(",
"self",
",",
"vehID",
",",
"color",
")",
":",
"self",
".",
"_connection",
".",
"_beginMessage",
"(",
"tc",
".",
"CMD_SET_VEHICLE_VARIABLE",
",",
"tc",
".",
"VAR_COLOR",
",",
"vehID",
",",
"1",
"+",
"1",
"+",
"1",
"+",
"1",
"+"... | setColor(string, (integer, integer, integer, integer))
sets color for vehicle with the given ID.
i.e. (255,0,0,0) for the color red.
The fourth integer (alpha) is only used when drawing vehicles with raster images | [
"setColor",
"(",
"string",
"(",
"integer",
"integer",
"integer",
"integer",
"))",
"sets",
"color",
"for",
"vehicle",
"with",
"the",
"given",
"ID",
".",
"i",
".",
"e",
".",
"(",
"255",
"0",
"0",
"0",
")",
"for",
"the",
"color",
"red",
".",
"The",
"f... | python | train |
PyGithub/PyGithub | github/Branch.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/Branch.py#L243-L276 | def edit_required_pull_request_reviews(self, dismissal_users=github.GithubObject.NotSet, dismissal_teams=github.GithubObject.NotSet, dismiss_stale_reviews=github.GithubObject.NotSet, require_code_owner_reviews=github.GithubObject.NotSet, required_approving_review_count=github.GithubObject.NotSet):
"""
:... | [
"def",
"edit_required_pull_request_reviews",
"(",
"self",
",",
"dismissal_users",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"dismissal_teams",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"dismiss_stale_reviews",
"=",
"github",
".",
"GithubO... | :calls: `PATCH /repos/:owner/:repo/branches/:branch/protection/required_pull_request_reviews <https://developer.github.com/v3/repos/branches>`_
:dismissal_users: list of strings
:dismissal_teams: list of strings
:dismiss_stale_reviews: bool
:require_code_owner_reviews: bool
:requ... | [
":",
"calls",
":",
"PATCH",
"/",
"repos",
"/",
":",
"owner",
"/",
":",
"repo",
"/",
"branches",
"/",
":",
"branch",
"/",
"protection",
"/",
"required_pull_request_reviews",
"<https",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"r... | python | train |
emc-openstack/storops | storops/unity/resource/replication_session.py | https://github.com/emc-openstack/storops/blob/24b4b13bf065c0ef0538dd0b5ebb8f25d24176bd/storops/unity/resource/replication_session.py#L159-L236 | def create_with_dst_resource_provisioning(
cls, cli, src_resource_id, dst_resource_config,
max_time_out_of_sync, name=None, remote_system=None,
src_spa_interface=None, src_spb_interface=None,
dst_spa_interface=None, dst_spb_interface=None,
dst_resource_element... | [
"def",
"create_with_dst_resource_provisioning",
"(",
"cls",
",",
"cli",
",",
"src_resource_id",
",",
"dst_resource_config",
",",
"max_time_out_of_sync",
",",
"name",
"=",
"None",
",",
"remote_system",
"=",
"None",
",",
"src_spa_interface",
"=",
"None",
",",
"src_spb... | Create a replication session along with destination resource
provisioning.
:param cli: the rest cli.
:param src_resource_id: id of the replication source, could be
lun/fs/cg.
:param dst_resource_config: `UnityResourceConfig` object. The user
chosen config for des... | [
"Create",
"a",
"replication",
"session",
"along",
"with",
"destination",
"resource",
"provisioning",
"."
] | python | train |
jaredLunde/vital-tools | vital/tools/__init__.py | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/__init__.py#L20-L32 | def getattr_in(obj, name):
""" Finds an in @obj via a period-delimited string @name.
@obj: (#object)
@name: (#str) |.|-separated keys to search @obj in
..
obj.deep.attr = 'deep value'
getattr_in(obj, 'obj.deep.attr')
..
|'deep value'|
"""
for p... | [
"def",
"getattr_in",
"(",
"obj",
",",
"name",
")",
":",
"for",
"part",
"in",
"name",
".",
"split",
"(",
"'.'",
")",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"part",
")",
"return",
"obj"
] | Finds an in @obj via a period-delimited string @name.
@obj: (#object)
@name: (#str) |.|-separated keys to search @obj in
..
obj.deep.attr = 'deep value'
getattr_in(obj, 'obj.deep.attr')
..
|'deep value'| | [
"Finds",
"an",
"in"
] | python | train |
klen/graphite-beacon | graphite_beacon/alerts.py | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L259-L285 | def load(self):
"""Load data from Graphite."""
LOGGER.debug('%s: start checking: %s', self.name, self.query)
if self.waiting:
self.notify('warning', 'Process takes too much time', target='waiting', ntype='common')
else:
self.waiting = True
try:
... | [
"def",
"load",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'%s: start checking: %s'",
",",
"self",
".",
"name",
",",
"self",
".",
"query",
")",
"if",
"self",
".",
"waiting",
":",
"self",
".",
"notify",
"(",
"'warning'",
",",
"'Process takes too ... | Load data from Graphite. | [
"Load",
"data",
"from",
"Graphite",
"."
] | python | train |
numenta/nupic | src/nupic/regions/sp_region.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/regions/sp_region.py#L750-L762 | def getSpec(cls):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
The parameters collection is constructed based on the parameters specified
by the various components (spatialSpec, temporalSpec and otherSpec)
"""
spec = cls.getBaseSpec()
s, o = _getAdditionalSpecs(s... | [
"def",
"getSpec",
"(",
"cls",
")",
":",
"spec",
"=",
"cls",
".",
"getBaseSpec",
"(",
")",
"s",
",",
"o",
"=",
"_getAdditionalSpecs",
"(",
"spatialImp",
"=",
"getDefaultSPImp",
"(",
")",
")",
"spec",
"[",
"'parameters'",
"]",
".",
"update",
"(",
"s",
... | Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
The parameters collection is constructed based on the parameters specified
by the various components (spatialSpec, temporalSpec and otherSpec) | [
"Overrides",
":",
"meth",
":",
"~nupic",
".",
"bindings",
".",
"regions",
".",
"PyRegion",
".",
"PyRegion",
".",
"getSpec",
"."
] | python | valid |
ejeschke/ginga | ginga/rv/plugins/PlotTable.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L231-L235 | def clear_plot(self):
"""Clear plot display."""
self.tab_plot.clear()
self.tab_plot.draw()
self.save_plot.set_enabled(False) | [
"def",
"clear_plot",
"(",
"self",
")",
":",
"self",
".",
"tab_plot",
".",
"clear",
"(",
")",
"self",
".",
"tab_plot",
".",
"draw",
"(",
")",
"self",
".",
"save_plot",
".",
"set_enabled",
"(",
"False",
")"
] | Clear plot display. | [
"Clear",
"plot",
"display",
"."
] | python | train |
chimera0/accel-brain-code | Reinforcement-Learning/demo/demo_maze_deep_q_network.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/demo/demo_maze_deep_q_network.py#L166-L193 | def observe_reward_value(self, state_arr, action_arr):
'''
Compute the reward value.
Args:
state_arr: `np.ndarray` of state.
action_arr: `np.ndarray` of action.
Returns:
Reward value.
'''
if se... | [
"def",
"observe_reward_value",
"(",
"self",
",",
"state_arr",
",",
"action_arr",
")",
":",
"if",
"self",
".",
"__check_goal_flag",
"(",
"action_arr",
")",
"is",
"True",
":",
"return",
"1.0",
"else",
":",
"x",
",",
"y",
"=",
"np",
".",
"where",
"(",
"ac... | Compute the reward value.
Args:
state_arr: `np.ndarray` of state.
action_arr: `np.ndarray` of action.
Returns:
Reward value. | [
"Compute",
"the",
"reward",
"value",
".",
"Args",
":",
"state_arr",
":",
"np",
".",
"ndarray",
"of",
"state",
".",
"action_arr",
":",
"np",
".",
"ndarray",
"of",
"action",
".",
"Returns",
":",
"Reward",
"value",
"."
] | python | train |
google/grumpy | third_party/pypy/_sre.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sre.py#L155-L181 | def split(self, string, maxsplit=0):
"""Split string by the occurrences of pattern."""
splitlist = []
state = _State(string, 0, sys.maxint, self.flags)
n = 0
last = state.start
while not maxsplit or n < maxsplit:
state.reset()
state.string_position... | [
"def",
"split",
"(",
"self",
",",
"string",
",",
"maxsplit",
"=",
"0",
")",
":",
"splitlist",
"=",
"[",
"]",
"state",
"=",
"_State",
"(",
"string",
",",
"0",
",",
"sys",
".",
"maxint",
",",
"self",
".",
"flags",
")",
"n",
"=",
"0",
"last",
"=",... | Split string by the occurrences of pattern. | [
"Split",
"string",
"by",
"the",
"occurrences",
"of",
"pattern",
"."
] | python | valid |
tradenity/python-sdk | tradenity/resources/customer_group.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/customer_group.py#L375-L395 | def delete_customer_group_by_id(cls, customer_group_id, **kwargs):
"""Delete CustomerGroup
Delete an instance of CustomerGroup by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete... | [
"def",
"delete_customer_group_by_id",
"(",
"cls",
",",
"customer_group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_delete_c... | Delete CustomerGroup
Delete an instance of CustomerGroup by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_customer_group_by_id(customer_group_id, async=True)
>>> result = thre... | [
"Delete",
"CustomerGroup"
] | python | train |
emory-libraries/eulfedora | eulfedora/api.py | https://github.com/emory-libraries/eulfedora/blob/161826f3fdcdab4007f6fa7dfd9f1ecabc4bcbe4/eulfedora/api.py#L1077-L1085 | def sparql_count(self, query, flush=None):
"""
Count results for a Sparql query.
:param query: sparql query string
:rtype: int
"""
return self.count_statements(query, language='sparql', type='tuples',
flush=flush) | [
"def",
"sparql_count",
"(",
"self",
",",
"query",
",",
"flush",
"=",
"None",
")",
":",
"return",
"self",
".",
"count_statements",
"(",
"query",
",",
"language",
"=",
"'sparql'",
",",
"type",
"=",
"'tuples'",
",",
"flush",
"=",
"flush",
")"
] | Count results for a Sparql query.
:param query: sparql query string
:rtype: int | [
"Count",
"results",
"for",
"a",
"Sparql",
"query",
"."
] | python | train |
getnikola/coil | coil/web.py | https://github.com/getnikola/coil/blob/80ef1827460b0691cf2c98351a14d88e235c9899/coil/web.py#L925-L935 | def serve_assets(path):
"""Serve Nikola assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/assets/ => output/assets
"""
res = os.path.join(app.config['NIKOLA_ROOT'],
_site.config["OUTPU... | [
"def",
"serve_assets",
"(",
"path",
")",
":",
"res",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app",
".",
"config",
"[",
"'NIKOLA_ROOT'",
"]",
",",
"_site",
".",
"config",
"[",
"\"OUTPUT_FOLDER\"",
"]",
",",
"'assets'",
")",
"return",
"send_from_directo... | Serve Nikola assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/assets/ => output/assets | [
"Serve",
"Nikola",
"assets",
"."
] | python | train |
JoelBender/bacpypes | py25/bacpypes/constructeddata.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/constructeddata.py#L1483-L1504 | def cast_out(self, klass):
"""Interpret the content as a particular class."""
if _debug: SequenceOfAny._debug("cast_out %r", klass)
# make sure it is a list
if not issubclass(klass, List):
raise DecodingError("%r is not a list" % (klass,))
# build a helper
h... | [
"def",
"cast_out",
"(",
"self",
",",
"klass",
")",
":",
"if",
"_debug",
":",
"SequenceOfAny",
".",
"_debug",
"(",
"\"cast_out %r\"",
",",
"klass",
")",
"# make sure it is a list",
"if",
"not",
"issubclass",
"(",
"klass",
",",
"List",
")",
":",
"raise",
"De... | Interpret the content as a particular class. | [
"Interpret",
"the",
"content",
"as",
"a",
"particular",
"class",
"."
] | python | train |
edx/XBlock | xblock/fields.py | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/fields.py#L110-L117 | def scopes(cls):
"""
Return a list of valid/understood class scopes.
"""
# Why do we need this? This should either
# * Be bubbled to the places where it is used (AcidXBlock).
# * Be automatic. Look for all members of a type.
return [cls.USAGE, cls.DEFINITION, cls.... | [
"def",
"scopes",
"(",
"cls",
")",
":",
"# Why do we need this? This should either",
"# * Be bubbled to the places where it is used (AcidXBlock).",
"# * Be automatic. Look for all members of a type.",
"return",
"[",
"cls",
".",
"USAGE",
",",
"cls",
".",
"DEFINITION",
",",
"cls",... | Return a list of valid/understood class scopes. | [
"Return",
"a",
"list",
"of",
"valid",
"/",
"understood",
"class",
"scopes",
"."
] | python | train |
dwkim78/upsilon | upsilon/extract_features/extract_features.py | https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L510-L543 | def slope_percentile(self, date, mag):
"""
Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Return... | [
"def",
"slope_percentile",
"(",
"self",
",",
"date",
",",
"mag",
")",
":",
"date_diff",
"=",
"date",
"[",
"1",
":",
"]",
"-",
"date",
"[",
":",
"len",
"(",
"date",
")",
"-",
"1",
"]",
"mag_diff",
"=",
"mag",
"[",
"1",
":",
"]",
"-",
"mag",
"[... | Return 10% and 90% percentile of slope.
Parameters
----------
date : array_like
An array of phase-folded date. Sorted.
mag : array_like
An array of phase-folded magnitudes. Sorted by date.
Returns
-------
per_10 : float
10% pe... | [
"Return",
"10%",
"and",
"90%",
"percentile",
"of",
"slope",
"."
] | python | train |
ajyoon/blur | blur/markov/node.py | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/node.py#L200-L232 | def add_reciprocal_link(self, target, weight):
"""
Add links pointing in either direction between ``self`` and ``target``.
This creates a ``Link`` from ``self`` to ``target`` and a ``Link``
from ``target`` to ``self`` of equal weight. If ``target`` is a list
of ``Node`` 's, repe... | [
"def",
"add_reciprocal_link",
"(",
"self",
",",
"target",
",",
"weight",
")",
":",
"# Generalize ``target`` to a list",
"if",
"not",
"isinstance",
"(",
"target",
",",
"list",
")",
":",
"target_list",
"=",
"[",
"target",
"]",
"else",
":",
"target_list",
"=",
... | Add links pointing in either direction between ``self`` and ``target``.
This creates a ``Link`` from ``self`` to ``target`` and a ``Link``
from ``target`` to ``self`` of equal weight. If ``target`` is a list
of ``Node`` 's, repeat this for each one.
Args:
target (Node or li... | [
"Add",
"links",
"pointing",
"in",
"either",
"direction",
"between",
"self",
"and",
"target",
"."
] | python | train |
happyleavesaoc/python-motorparts | motorparts/__init__.py | https://github.com/happyleavesaoc/python-motorparts/blob/4a6b4dc72dd45524dd64a7a079478bd98c55215c/motorparts/__init__.py#L159-L165 | def get_tow_guide(session, vehicle_index):
"""Get tow guide information."""
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
return session.post(TOW_URL, {
'vin': profile['vehicles'][vehicle_index]['vin']
}).json() | [
"def",
"get_tow_guide",
"(",
"session",
",",
"vehicle_index",
")",
":",
"profile",
"=",
"get_profile",
"(",
"session",
")",
"_validate_vehicle",
"(",
"vehicle_index",
",",
"profile",
")",
"return",
"session",
".",
"post",
"(",
"TOW_URL",
",",
"{",
"'vin'",
"... | Get tow guide information. | [
"Get",
"tow",
"guide",
"information",
"."
] | python | train |
FNNDSC/med2image | med2image/systemMisc.py | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L271-L324 | def b10_convertFrom(anum10, aradix, *args):
"""
ARGS
anum10 in number in base 10
aradix in convert <anum10> to number in base
+ <aradix>
OPTIONAL
forcelength in if nonzero, indicates the length
... | [
"def",
"b10_convertFrom",
"(",
"anum10",
",",
"aradix",
",",
"*",
"args",
")",
":",
"i",
"=",
"0",
"k",
"=",
"0",
"# Cycle up in powers of radix until the largest exponent is found.",
"# This is required to determine the word length",
"while",
"(",
"pow",
"(",
"aradix",... | ARGS
anum10 in number in base 10
aradix in convert <anum10> to number in base
+ <aradix>
OPTIONAL
forcelength in if nonzero, indicates the length
+ of the return array. Useful ... | [
"ARGS",
"anum10",
"in",
"number",
"in",
"base",
"10",
"aradix",
"in",
"convert",
"<anum10",
">",
"to",
"number",
"in",
"base",
"+",
"<aradix",
">"
] | python | train |
qualisys/qualisys_python_sdk | qtm/qrt.py | https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L230-L236 | async def start(self, rtfromfile=False):
"""Start RT from file. You need to be in control of QTM to be able to do this.
"""
cmd = "start" + (" rtfromfile" if rtfromfile else "")
return await asyncio.wait_for(
self._protocol.send_command(cmd), timeout=self._timeout
) | [
"async",
"def",
"start",
"(",
"self",
",",
"rtfromfile",
"=",
"False",
")",
":",
"cmd",
"=",
"\"start\"",
"+",
"(",
"\" rtfromfile\"",
"if",
"rtfromfile",
"else",
"\"\"",
")",
"return",
"await",
"asyncio",
".",
"wait_for",
"(",
"self",
".",
"_protocol",
... | Start RT from file. You need to be in control of QTM to be able to do this. | [
"Start",
"RT",
"from",
"file",
".",
"You",
"need",
"to",
"be",
"in",
"control",
"of",
"QTM",
"to",
"be",
"able",
"to",
"do",
"this",
"."
] | python | valid |
junzis/pyModeS | pyModeS/decoder/bds/bds44.py | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds44.py#L121-L138 | def p44(msg):
"""Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
"""
d = hex2bin(data(msg))
if d[34] == '0':
return None
p = bin2int(d[35:46]) # hPa
return p | [
"def",
"p44",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"34",
"]",
"==",
"'0'",
":",
"return",
"None",
"p",
"=",
"bin2int",
"(",
"d",
"[",
"35",
":",
"46",
"]",
")",
"# hPa",
"return",
"p"... | Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa | [
"Static",
"pressure",
"."
] | python | train |
log2timeline/plaso | plaso/cli/psort_tool.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/psort_tool.py#L102-L127 | def _CheckStorageFile(self, storage_file_path): # pylint: disable=arguments-differ
"""Checks if the storage file path is valid.
Args:
storage_file_path (str): path of the storage file.
Raises:
BadConfigOption: if the storage file path is invalid.
"""
if os.path.exists(storage_file_pat... | [
"def",
"_CheckStorageFile",
"(",
"self",
",",
"storage_file_path",
")",
":",
"# pylint: disable=arguments-differ",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"storage_file_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"storage_file_path"... | Checks if the storage file path is valid.
Args:
storage_file_path (str): path of the storage file.
Raises:
BadConfigOption: if the storage file path is invalid. | [
"Checks",
"if",
"the",
"storage",
"file",
"path",
"is",
"valid",
"."
] | python | train |
nuagenetworks/bambou | bambou/nurest_fetcher.py | https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_fetcher.py#L256-L291 | def fetch(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
""" Fetch objects according to given filter and page.
Note:
This method fetches all managed class objects and store them
... | [
"def",
"fetch",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"group_by",
"=",
"[",
"]",
",",
"page",
"=",
"None",
",",
"page_size",
"=",
"None",
",",
"query_parameters",
"=",
"None",
",",
"commit",
"=",
"True",
",",
"... | Fetch objects according to given filter and page.
Note:
This method fetches all managed class objects and store them
in local_name of the served object. which means that the parent
object will hold them in a list. You can prevent this behavior
... | [
"Fetch",
"objects",
"according",
"to",
"given",
"filter",
"and",
"page",
"."
] | python | train |
Azure/msrest-for-python | msrest/paging.py | https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/paging.py#L96-L107 | def get(self, url):
# type: (str) -> List[Model]
"""Get an arbitrary page.
This resets the iterator and then fully consumes it to return the
specific page **only**.
:param str url: URL to arbitrary page results.
"""
self.reset()
self.next_link = url
... | [
"def",
"get",
"(",
"self",
",",
"url",
")",
":",
"# type: (str) -> List[Model]",
"self",
".",
"reset",
"(",
")",
"self",
".",
"next_link",
"=",
"url",
"return",
"self",
".",
"advance_page",
"(",
")"
] | Get an arbitrary page.
This resets the iterator and then fully consumes it to return the
specific page **only**.
:param str url: URL to arbitrary page results. | [
"Get",
"an",
"arbitrary",
"page",
"."
] | python | train |
ctuning/ck | ck/kernel.py | https://github.com/ctuning/ck/blob/7e009814e975f8742790d3106340088a46223714/ck/kernel.py#L1135-L1186 | def get_os_ck(i):
"""
Input: {
(bits) - force OS bits
}
Output: {
return - return code = 0
platform - 'win' or 'linux'
bits - OS bits in string: 32 or 64
python_bits - Python installation bits in string:... | [
"def",
"get_os_ck",
"(",
"i",
")",
":",
"import",
"os",
"import",
"platform",
"import",
"struct",
"pbits",
"=",
"str",
"(",
"8",
"*",
"struct",
".",
"calcsize",
"(",
"\"P\"",
")",
")",
"plat",
"=",
"'linux'",
"if",
"platform",
".",
"system",
"(",
")"... | Input: {
(bits) - force OS bits
}
Output: {
return - return code = 0
platform - 'win' or 'linux'
bits - OS bits in string: 32 or 64
python_bits - Python installation bits in string: 32 or 64
} | [
"Input",
":",
"{",
"(",
"bits",
")",
"-",
"force",
"OS",
"bits",
"}"
] | python | train |
mitodl/pylti | pylti/common.py | https://github.com/mitodl/pylti/blob/18a608282e0d5bc941beb2eaaeea3b7ad484b399/pylti/common.py#L311-L353 | def generate_request_xml(message_identifier_id, operation,
lis_result_sourcedid, score):
# pylint: disable=too-many-locals
"""
Generates LTI 1.1 XML for posting result to LTI consumer.
:param message_identifier_id:
:param operation:
:param lis_result_sourcedid:
:par... | [
"def",
"generate_request_xml",
"(",
"message_identifier_id",
",",
"operation",
",",
"lis_result_sourcedid",
",",
"score",
")",
":",
"# pylint: disable=too-many-locals",
"root",
"=",
"etree",
".",
"Element",
"(",
"u'imsx_POXEnvelopeRequest'",
",",
"xmlns",
"=",
"u'http:/... | Generates LTI 1.1 XML for posting result to LTI consumer.
:param message_identifier_id:
:param operation:
:param lis_result_sourcedid:
:param score:
:return: XML string | [
"Generates",
"LTI",
"1",
".",
"1",
"XML",
"for",
"posting",
"result",
"to",
"LTI",
"consumer",
"."
] | python | train |
PyCQA/pyflakes | pyflakes/checker.py | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L712-L719 | def runDeferred(self, deferred):
"""
Run the callables in C{deferred} using their associated scope stack.
"""
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler() | [
"def",
"runDeferred",
"(",
"self",
",",
"deferred",
")",
":",
"for",
"handler",
",",
"scope",
",",
"offset",
"in",
"deferred",
":",
"self",
".",
"scopeStack",
"=",
"scope",
"self",
".",
"offset",
"=",
"offset",
"handler",
"(",
")"
] | Run the callables in C{deferred} using their associated scope stack. | [
"Run",
"the",
"callables",
"in",
"C",
"{",
"deferred",
"}",
"using",
"their",
"associated",
"scope",
"stack",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L558-L563 | def _focus_tab(self, tab_idx):
"""Change tab focus"""
for i in range(self.tab_widget.count()):
self.tab_widget.setTabEnabled(i, False)
self.tab_widget.setTabEnabled(tab_idx, True)
self.tab_widget.setCurrentIndex(tab_idx) | [
"def",
"_focus_tab",
"(",
"self",
",",
"tab_idx",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"tab_widget",
".",
"count",
"(",
")",
")",
":",
"self",
".",
"tab_widget",
".",
"setTabEnabled",
"(",
"i",
",",
"False",
")",
"self",
".",
"tab... | Change tab focus | [
"Change",
"tab",
"focus"
] | python | train |
ANTsX/ANTsPy | ants/registration/reorient_image.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reorient_image.py#L56-L82 | def reorient_image2(image, orientation='RAS'):
"""
Reorient an image.
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = mni.reorient_image2()
"""
if image.dimension != 3:
raise ValueError('image must have 3 dimensions')
inpixelt... | [
"def",
"reorient_image2",
"(",
"image",
",",
"orientation",
"=",
"'RAS'",
")",
":",
"if",
"image",
".",
"dimension",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'image must have 3 dimensions'",
")",
"inpixeltype",
"=",
"image",
".",
"pixeltype",
"ndim",
"=",
... | Reorient an image.
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = mni.reorient_image2() | [
"Reorient",
"an",
"image",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/nodes.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/nodes.py#L1189-L1191 | def critical(self, msg, *args, **kwargs):
"""Log 'msg % args' with the critical severity level"""
self._log("CRITICAL", msg, args, kwargs) | [
"def",
"critical",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_log",
"(",
"\"CRITICAL\"",
",",
"msg",
",",
"args",
",",
"kwargs",
")"
] | Log 'msg % args' with the critical severity level | [
"Log",
"msg",
"%",
"args",
"with",
"the",
"critical",
"severity",
"level"
] | python | train |
mushkevych/scheduler | synergy/db/model/queue_context_entry.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/db/model/queue_context_entry.py#L28-L38 | def queue_context_entry(exchange,
queue_name,
routing=None):
""" forms queue's context entry """
if routing is None:
routing = queue_name
queue_entry = QueueContextEntry(mq_queue=queue_name,
mq_exchange=exchange,
... | [
"def",
"queue_context_entry",
"(",
"exchange",
",",
"queue_name",
",",
"routing",
"=",
"None",
")",
":",
"if",
"routing",
"is",
"None",
":",
"routing",
"=",
"queue_name",
"queue_entry",
"=",
"QueueContextEntry",
"(",
"mq_queue",
"=",
"queue_name",
",",
"mq_exc... | forms queue's context entry | [
"forms",
"queue",
"s",
"context",
"entry"
] | python | train |
d0c-s4vage/pfp | pfp/bitwrap.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L82-L87 | def close(self):
"""Close the stream
"""
self.closed = True
self._flush_bits_to_stream()
self._stream.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"closed",
"=",
"True",
"self",
".",
"_flush_bits_to_stream",
"(",
")",
"self",
".",
"_stream",
".",
"close",
"(",
")"
] | Close the stream | [
"Close",
"the",
"stream"
] | python | train |
dfm/george | george/modeling.py | https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L176-L188 | def get_parameter_dict(self, include_frozen=False):
"""
Get an ordered dictionary of the parameters
Args:
include_frozen (Optional[bool]): Should the frozen parameters be
included in the returned value? (default: ``False``)
"""
return OrderedDict(zip... | [
"def",
"get_parameter_dict",
"(",
"self",
",",
"include_frozen",
"=",
"False",
")",
":",
"return",
"OrderedDict",
"(",
"zip",
"(",
"self",
".",
"get_parameter_names",
"(",
"include_frozen",
"=",
"include_frozen",
")",
",",
"self",
".",
"get_parameter_vector",
"(... | Get an ordered dictionary of the parameters
Args:
include_frozen (Optional[bool]): Should the frozen parameters be
included in the returned value? (default: ``False``) | [
"Get",
"an",
"ordered",
"dictionary",
"of",
"the",
"parameters"
] | python | train |
phoebe-project/phoebe2 | phoebe/backend/universe.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/universe.py#L1608-L1622 | def _fill_albedos(self, mesh=None, irrad_frac_refl=0.0):
"""
TODO: add documentation
"""
logger.debug("{}._fill_albedos".format(self.component))
if mesh is None:
mesh = self.mesh
mesh.update_columns(irrad_frac_refl=irrad_frac_refl)
if not self.needs... | [
"def",
"_fill_albedos",
"(",
"self",
",",
"mesh",
"=",
"None",
",",
"irrad_frac_refl",
"=",
"0.0",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}._fill_albedos\"",
".",
"format",
"(",
"self",
".",
"component",
")",
")",
"if",
"mesh",
"is",
"None",
":",
"... | TODO: add documentation | [
"TODO",
":",
"add",
"documentation"
] | python | train |
Yipit/ejson | ejson/__init__.py | https://github.com/Yipit/ejson/blob/6665703f1534923d1c30849e08339f0ff97d8230/ejson/__init__.py#L179-L194 | def _converter(data):
"""Internal function that will be passed to the native `json.dumps`.
This function uses the `REGISTRY` of serializers and try to convert
a given instance to an object that json.dumps can understand.
"""
handler = REGISTRY.get(data.__class__)
if handler:
full_name =... | [
"def",
"_converter",
"(",
"data",
")",
":",
"handler",
"=",
"REGISTRY",
".",
"get",
"(",
"data",
".",
"__class__",
")",
"if",
"handler",
":",
"full_name",
"=",
"'{}.{}'",
".",
"format",
"(",
"data",
".",
"__class__",
".",
"__module__",
",",
"data",
"."... | Internal function that will be passed to the native `json.dumps`.
This function uses the `REGISTRY` of serializers and try to convert
a given instance to an object that json.dumps can understand. | [
"Internal",
"function",
"that",
"will",
"be",
"passed",
"to",
"the",
"native",
"json",
".",
"dumps",
"."
] | python | train |
metric-learn/metric-learn | metric_learn/mmc.py | https://github.com/metric-learn/metric-learn/blob/d945df1342c69012608bb70b92520392a0853de6/metric_learn/mmc.py#L212-L271 | def _fit_diag(self, pairs, y):
"""Learn diagonal metric using MMC.
Parameters
----------
X : (n x d) data matrix
each row corresponds to a single instance
constraints : 4-tuple of arrays
(a,b,c,d) indices into X, with (a,b) specifying similar and (c,d)
dissimilar pairs
""... | [
"def",
"_fit_diag",
"(",
"self",
",",
"pairs",
",",
"y",
")",
":",
"num_dim",
"=",
"pairs",
".",
"shape",
"[",
"2",
"]",
"pos_pairs",
",",
"neg_pairs",
"=",
"pairs",
"[",
"y",
"==",
"1",
"]",
",",
"pairs",
"[",
"y",
"==",
"-",
"1",
"]",
"s_sum"... | Learn diagonal metric using MMC.
Parameters
----------
X : (n x d) data matrix
each row corresponds to a single instance
constraints : 4-tuple of arrays
(a,b,c,d) indices into X, with (a,b) specifying similar and (c,d)
dissimilar pairs | [
"Learn",
"diagonal",
"metric",
"using",
"MMC",
".",
"Parameters",
"----------",
"X",
":",
"(",
"n",
"x",
"d",
")",
"data",
"matrix",
"each",
"row",
"corresponds",
"to",
"a",
"single",
"instance",
"constraints",
":",
"4",
"-",
"tuple",
"of",
"arrays",
"("... | python | train |
gwastro/pycbc | pycbc/dq.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/dq.py#L34-L92 | def parse_veto_definer(veto_def_filename):
""" Parse a veto definer file from the filename and return a dictionary
indexed by ifo and veto definer category level.
Parameters
----------
veto_def_filename: str
The path to the veto definer file
Returns:
parsed_definition: dict
... | [
"def",
"parse_veto_definer",
"(",
"veto_def_filename",
")",
":",
"from",
"glue",
".",
"ligolw",
"import",
"table",
",",
"lsctables",
",",
"utils",
"as",
"ligolw_utils",
"from",
"glue",
".",
"ligolw",
".",
"ligolw",
"import",
"LIGOLWContentHandler",
"as",
"h",
... | Parse a veto definer file from the filename and return a dictionary
indexed by ifo and veto definer category level.
Parameters
----------
veto_def_filename: str
The path to the veto definer file
Returns:
parsed_definition: dict
Returns a dictionary first indexed by ifo,... | [
"Parse",
"a",
"veto",
"definer",
"file",
"from",
"the",
"filename",
"and",
"return",
"a",
"dictionary",
"indexed",
"by",
"ifo",
"and",
"veto",
"definer",
"category",
"level",
"."
] | python | train |
Jarn/jarn.mkrelease | jarn/mkrelease/mkrelease.py | https://github.com/Jarn/jarn.mkrelease/blob/844377f37a3cdc0a154148790a926f991019ec4a/jarn/mkrelease/mkrelease.py#L393-L418 | def get_uploadflags(self, location):
"""Return uploadflags for the given server.
"""
uploadflags = []
server = self.defaults.servers[location]
if self.sign:
uploadflags.append('--sign')
elif server.sign is not None:
if server.sign:
... | [
"def",
"get_uploadflags",
"(",
"self",
",",
"location",
")",
":",
"uploadflags",
"=",
"[",
"]",
"server",
"=",
"self",
".",
"defaults",
".",
"servers",
"[",
"location",
"]",
"if",
"self",
".",
"sign",
":",
"uploadflags",
".",
"append",
"(",
"'--sign'",
... | Return uploadflags for the given server. | [
"Return",
"uploadflags",
"for",
"the",
"given",
"server",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/natural_language_classifier_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/natural_language_classifier_v1.py#L415-L426 | def _from_dict(cls, _dict):
"""Initialize a ClassificationCollection object from a json dictionary."""
args = {}
if 'classifier_id' in _dict:
args['classifier_id'] = _dict.get('classifier_id')
if 'url' in _dict:
args['url'] = _dict.get('url')
if 'collectio... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'classifier_id'",
"in",
"_dict",
":",
"args",
"[",
"'classifier_id'",
"]",
"=",
"_dict",
".",
"get",
"(",
"'classifier_id'",
")",
"if",
"'url'",
"in",
"_dict",
":",
... | Initialize a ClassificationCollection object from a json dictionary. | [
"Initialize",
"a",
"ClassificationCollection",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | python | train |
scieloorg/publicationstatsapi | publicationstats/queries.py | https://github.com/scieloorg/publicationstatsapi/blob/118995d75ef9478f64d5707107f4ce1640a0aa8e/publicationstats/queries.py#L227-L286 | def journals_status(collection, raw=False):
"""
This method retrieve the total of documents, articles (citable documents),
issues and bibliografic references of a journal
arguments
collection: SciELO 3 letters Acronym
issn: Journal ISSN
return for journal context
{
"citable": 1... | [
"def",
"journals_status",
"(",
"collection",
",",
"raw",
"=",
"False",
")",
":",
"tc",
"=",
"ThriftClient",
"(",
")",
"body",
"=",
"{",
"\"query\"",
":",
"{",
"\"filtered\"",
":",
"{",
"}",
"}",
"}",
"fltr",
"=",
"{",
"}",
"query",
"=",
"{",
"\"que... | This method retrieve the total of documents, articles (citable documents),
issues and bibliografic references of a journal
arguments
collection: SciELO 3 letters Acronym
issn: Journal ISSN
return for journal context
{
"citable": 12140,
"non_citable": 20,
"docs": 12160,
... | [
"This",
"method",
"retrieve",
"the",
"total",
"of",
"documents",
"articles",
"(",
"citable",
"documents",
")",
"issues",
"and",
"bibliografic",
"references",
"of",
"a",
"journal"
] | python | train |
django-parler/django-parler | parler/views.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L243-L253 | def get_language_tabs(self):
"""
Determine the language tabs to show.
"""
current_language = self.get_current_language()
if self.object:
available_languages = list(self.object.get_available_languages())
else:
available_languages = []
retur... | [
"def",
"get_language_tabs",
"(",
"self",
")",
":",
"current_language",
"=",
"self",
".",
"get_current_language",
"(",
")",
"if",
"self",
".",
"object",
":",
"available_languages",
"=",
"list",
"(",
"self",
".",
"object",
".",
"get_available_languages",
"(",
")... | Determine the language tabs to show. | [
"Determine",
"the",
"language",
"tabs",
"to",
"show",
"."
] | python | train |
saltstack/salt | salt/modules/aws_sqs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aws_sqs.py#L71-L112 | def receive_message(queue, region, num=1, opts=None, user=None):
'''
Receive one or more messages from a queue in a region
queue
The name of the queue to receive messages from
region
Region where SQS queues exists
num : 1
The max number of messages to receive
opts : N... | [
"def",
"receive_message",
"(",
"queue",
",",
"region",
",",
"num",
"=",
"1",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'Messages'",
":",
"None",
",",
"}",
"queues",
"=",
"list_queues",
"(",
"region",
",",
"opts... | Receive one or more messages from a queue in a region
queue
The name of the queue to receive messages from
region
Region where SQS queues exists
num : 1
The max number of messages to receive
opts : None
Any additional options to add to the command line
user : Non... | [
"Receive",
"one",
"or",
"more",
"messages",
"from",
"a",
"queue",
"in",
"a",
"region"
] | python | train |
Spirent/py-stcrestclient | stcrestclient/stchttp.py | https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L142-L154 | def join_session(self, sid):
"""Attach to an existing session."""
self._rest.add_header('X-STC-API-Session', sid)
self._sid = sid
try:
status, data = self._rest.get_request('objects', 'system1',
['version', 'name'])
ex... | [
"def",
"join_session",
"(",
"self",
",",
"sid",
")",
":",
"self",
".",
"_rest",
".",
"add_header",
"(",
"'X-STC-API-Session'",
",",
"sid",
")",
"self",
".",
"_sid",
"=",
"sid",
"try",
":",
"status",
",",
"data",
"=",
"self",
".",
"_rest",
".",
"get_r... | Attach to an existing session. | [
"Attach",
"to",
"an",
"existing",
"session",
"."
] | python | train |
apple/turicreate | src/external/xgboost/subtree/rabit/wrapper/rabit.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/wrapper/rabit.py#L283-L314 | def checkpoint(global_model, local_model=None):
"""Checkpoint the model.
This means we finished a stage of execution.
Every time we call check point, there is a version number which will increase by one.
Parameters
----------
global_model: anytype that can be pickled
globally shared mo... | [
"def",
"checkpoint",
"(",
"global_model",
",",
"local_model",
"=",
"None",
")",
":",
"sglobal",
"=",
"pickle",
".",
"dumps",
"(",
"global_model",
")",
"if",
"local_model",
"is",
"None",
":",
"_LIB",
".",
"RabitCheckPoint",
"(",
"sglobal",
",",
"len",
"(",
... | Checkpoint the model.
This means we finished a stage of execution.
Every time we call check point, there is a version number which will increase by one.
Parameters
----------
global_model: anytype that can be pickled
globally shared model/state when calling this function,
the calle... | [
"Checkpoint",
"the",
"model",
"."
] | python | train |
noahbenson/neuropythy | neuropythy/vision/retinotopy.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/vision/retinotopy.py#L1929-L2166 | def clean_retinotopy_potential(hemi, retinotopy=Ellipsis, mask=Ellipsis, weight=Ellipsis,
surface='midgray', min_weight=Ellipsis, min_eccentricity=0.75,
visual_area=None, map_visual_areas=Ellipsis,
visual_area_field_signs=Ellip... | [
"def",
"clean_retinotopy_potential",
"(",
"hemi",
",",
"retinotopy",
"=",
"Ellipsis",
",",
"mask",
"=",
"Ellipsis",
",",
"weight",
"=",
"Ellipsis",
",",
"surface",
"=",
"'midgray'",
",",
"min_weight",
"=",
"Ellipsis",
",",
"min_eccentricity",
"=",
"0.75",
",",... | clean_retinotopy_potential(hemi) yields a retinotopic potential function for the given
hemisphere that, when minimized, should yeild a cleaned/smoothed version of the retinotopic
maps.
The potential function f returned by clean_retinotopy_potential() is a PotentialFunction object,
as defined in neu... | [
"clean_retinotopy_potential",
"(",
"hemi",
")",
"yields",
"a",
"retinotopic",
"potential",
"function",
"for",
"the",
"given",
"hemisphere",
"that",
"when",
"minimized",
"should",
"yeild",
"a",
"cleaned",
"/",
"smoothed",
"version",
"of",
"the",
"retinotopic",
"map... | python | train |
openego/eDisGo | edisgo/grid/network.py | https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/network.py#L3391-L3434 | def v_res(self, nodes=None, level=None):
"""
Get resulting voltage level at node.
Parameters
----------
nodes : :obj:`list`
List of string representatives of grid topology components, e.g.
:class:`~.grid.components.Generator`. If not provided defaults to
... | [
"def",
"v_res",
"(",
"self",
",",
"nodes",
"=",
"None",
",",
"level",
"=",
"None",
")",
":",
"# check if voltages are available:",
"if",
"hasattr",
"(",
"self",
",",
"'pfa_v_mag_pu'",
")",
":",
"self",
".",
"pfa_v_mag_pu",
".",
"sort_index",
"(",
"axis",
"... | Get resulting voltage level at node.
Parameters
----------
nodes : :obj:`list`
List of string representatives of grid topology components, e.g.
:class:`~.grid.components.Generator`. If not provided defaults to
all nodes available in grid level `level`.
... | [
"Get",
"resulting",
"voltage",
"level",
"at",
"node",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/grading/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/objects.py#L596-L607 | def get_based_on_grades_metadata(self):
"""Gets the metadata for a grade-based designation.
return: (osid.Metadata) - metadata for the grade-based
designation
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.re... | [
"def",
"get_based_on_grades_metadata",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_mdata",
"[",
"'based_on_grades'",
"]",
")",
"metadata",
".",
"update",
"(",
... | Gets the metadata for a grade-based designation.
return: (osid.Metadata) - metadata for the grade-based
designation
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"metadata",
"for",
"a",
"grade",
"-",
"based",
"designation",
"."
] | python | train |
KyleWpppd/css-audit | cssaudit/parser.py | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L44-L82 | def handle_starttag(self, tag, attrs):
"""
This method handles any HTML tags that have a matching
closing tag. So elements like <p> and <div> are handled
by this method.
@param <string> tag
An html tag that has a separate closing tag such as <p>
<div> or <b... | [
"def",
"handle_starttag",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"dattrs",
"=",
"dict",
"(",
"attrs",
")",
"# look for '<link type='text/css' rel='stylesheet' href='...' > tags",
"# to see if looking for link tags makes sense here, we need to know",
"# a little more abo... | This method handles any HTML tags that have a matching
closing tag. So elements like <p> and <div> are handled
by this method.
@param <string> tag
An html tag that has a separate closing tag such as <p>
<div> or <body>
@param <tuple> attrs
A tuple of HTM... | [
"This",
"method",
"handles",
"any",
"HTML",
"tags",
"that",
"have",
"a",
"matching",
"closing",
"tag",
".",
"So",
"elements",
"like",
"<p",
">",
"and",
"<div",
">",
"are",
"handled",
"by",
"this",
"method",
"."
] | python | train |
google/grumpy | third_party/pythonparser/parser.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L987-L998 | def raise_stmt__30(self, raise_loc, exc_opt):
"""(3.0-) raise_stmt: 'raise' [test ['from' test]]"""
exc = from_loc = cause = None
loc = raise_loc
if exc_opt:
exc, cause_opt = exc_opt
loc = loc.join(exc.loc)
if cause_opt:
from_loc, cause... | [
"def",
"raise_stmt__30",
"(",
"self",
",",
"raise_loc",
",",
"exc_opt",
")",
":",
"exc",
"=",
"from_loc",
"=",
"cause",
"=",
"None",
"loc",
"=",
"raise_loc",
"if",
"exc_opt",
":",
"exc",
",",
"cause_opt",
"=",
"exc_opt",
"loc",
"=",
"loc",
".",
"join",... | (3.0-) raise_stmt: 'raise' [test ['from' test]] | [
"(",
"3",
".",
"0",
"-",
")",
"raise_stmt",
":",
"raise",
"[",
"test",
"[",
"from",
"test",
"]]"
] | python | valid |
mdickinson/bigfloat | bigfloat/core.py | https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L2411-L2429 | def trunc(x, context=None):
"""
Return the next integer towards zero.
If the result is not exactly representable, it will be rounded according to
the current context.
.. note::
This function corresponds to the MPFR function ``mpfr_rint_trunc``,
not to ``mpfr_trunc``.
"""
re... | [
"def",
"trunc",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_rint_trunc",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
... | Return the next integer towards zero.
If the result is not exactly representable, it will be rounded according to
the current context.
.. note::
This function corresponds to the MPFR function ``mpfr_rint_trunc``,
not to ``mpfr_trunc``. | [
"Return",
"the",
"next",
"integer",
"towards",
"zero",
"."
] | python | train |
seanpar203/event-bus | event_bus/bus.py | https://github.com/seanpar203/event-bus/blob/60319b9eb4e38c348e80f3ec625312eda75da765/event_bus/bus.py#L73-L92 | def on(self, event: str) -> Callable:
""" Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable
"""
def outer(func):
self.add_event(f... | [
"def",
"on",
"(",
"self",
",",
"event",
":",
"str",
")",
"->",
"Callable",
":",
"def",
"outer",
"(",
"func",
")",
":",
"self",
".",
"add_event",
"(",
"func",
",",
"event",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
... | Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable | [
"Decorator",
"for",
"subscribing",
"a",
"function",
"to",
"a",
"specific",
"event",
"."
] | python | train |
thefactory/marathon-python | marathon/client.py | https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/client.py#L301-L325 | def update_apps(self, apps, force=False, minimal=True):
"""Update multiple apps.
Applies writable settings in elements of apps either by upgrading existing ones or creating new ones
:param apps: sequence of application settings
:param bool force: apply even if a deployment is in progre... | [
"def",
"update_apps",
"(",
"self",
",",
"apps",
",",
"force",
"=",
"False",
",",
"minimal",
"=",
"True",
")",
":",
"json_repr_apps",
"=",
"[",
"]",
"for",
"app",
"in",
"apps",
":",
"# Changes won't take if version is set - blank it for convenience",
"app",
".",
... | Update multiple apps.
Applies writable settings in elements of apps either by upgrading existing ones or creating new ones
:param apps: sequence of application settings
:param bool force: apply even if a deployment is in progress
:param bool minimal: ignore nulls and empty collections
... | [
"Update",
"multiple",
"apps",
"."
] | python | train |
Kane610/deconz | pydeconz/__init__.py | https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/__init__.py#L200-L225 | def update_group_color(self, lights: list) -> None:
"""Update group colors based on light states.
deCONZ group updates don't contain any information about the current
state of the lights in the group. This method updates the color
properties of the group to the current color of the ligh... | [
"def",
"update_group_color",
"(",
"self",
",",
"lights",
":",
"list",
")",
"->",
"None",
":",
"for",
"group",
"in",
"self",
".",
"groups",
".",
"values",
"(",
")",
":",
"# Skip group if there are no common light ids.",
"if",
"not",
"any",
"(",
"{",
"*",
"l... | Update group colors based on light states.
deCONZ group updates don't contain any information about the current
state of the lights in the group. This method updates the color
properties of the group to the current color of the lights in the
group.
For groups where the lights h... | [
"Update",
"group",
"colors",
"based",
"on",
"light",
"states",
"."
] | python | train |
teepark/greenhouse | greenhouse/io/ssl.py | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/ssl.py#L242-L261 | def do_handshake(self, timeout):
'perform a SSL/TLS handshake'
tout = _timeout(timeout)
if not self._blocking:
return self._sslobj.do_handshake()
while 1:
try:
return self._sslobj.do_handshake()
except ssl.SSLError, exc:
... | [
"def",
"do_handshake",
"(",
"self",
",",
"timeout",
")",
":",
"tout",
"=",
"_timeout",
"(",
"timeout",
")",
"if",
"not",
"self",
".",
"_blocking",
":",
"return",
"self",
".",
"_sslobj",
".",
"do_handshake",
"(",
")",
"while",
"1",
":",
"try",
":",
"r... | perform a SSL/TLS handshake | [
"perform",
"a",
"SSL",
"/",
"TLS",
"handshake"
] | python | train |
buildbot/buildbot | master/buildbot/steps/cmake.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/steps/cmake.py#L62-L87 | def run(self):
"""
run CMake
"""
command = [self.cmake]
if self.generator:
command.extend([
'-G', self.generator
])
if self.path:
command.append(self.path)
if self.definitions is not None:
for item... | [
"def",
"run",
"(",
"self",
")",
":",
"command",
"=",
"[",
"self",
".",
"cmake",
"]",
"if",
"self",
".",
"generator",
":",
"command",
".",
"extend",
"(",
"[",
"'-G'",
",",
"self",
".",
"generator",
"]",
")",
"if",
"self",
".",
"path",
":",
"comman... | run CMake | [
"run",
"CMake"
] | python | train |
tensorflow/mesh | mesh_tensorflow/auto_mtf/layout.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/auto_mtf/layout.py#L47-L63 | def layout(mtf_graph, mesh_shape, mtf_outputs=()):
"""Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the c... | [
"def",
"layout",
"(",
"mtf_graph",
",",
"mesh_shape",
",",
"mtf_outputs",
"=",
"(",
")",
")",
":",
"mesh_shape",
"=",
"mtf",
".",
"convert_to_shape",
"(",
"mesh_shape",
")",
"estimator",
"=",
"memory_estimator",
".",
"MemoryEstimator",
"(",
"mtf_graph",
",",
... | Compute layout rules based on a computational graph and mesh shape.
Args:
mtf_graph: a mtf.Graph.
mesh_shape: an mtf.Shape, str, or listlike of mtf.Dimension.
mtf_outputs: an optional iterable of mtf.Tensor, representing the outputs
of the computation.
Returns:
a mtf.LayoutRules | [
"Compute",
"layout",
"rules",
"based",
"on",
"a",
"computational",
"graph",
"and",
"mesh",
"shape",
"."
] | python | train |
mdiener/grace | grace/py27/cssmin.py | https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/cssmin.py#L19-L50 | def remove_comments(css):
"""Remove all CSS comment blocks."""
iemac = False
preserve = False
comment_start = css.find("/*")
while comment_start >= 0:
# Preserve comments that look like `/*!...*/`.
# Slicing is used to make sure we don"t get an IndexError.
preserve = css[com... | [
"def",
"remove_comments",
"(",
"css",
")",
":",
"iemac",
"=",
"False",
"preserve",
"=",
"False",
"comment_start",
"=",
"css",
".",
"find",
"(",
"\"/*\"",
")",
"while",
"comment_start",
">=",
"0",
":",
"# Preserve comments that look like `/*!...*/`.",
"# Slicing is... | Remove all CSS comment blocks. | [
"Remove",
"all",
"CSS",
"comment",
"blocks",
"."
] | python | train |
wmayner/pyphi | pyphi/subsystem.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/subsystem.py#L259-L274 | def indices2nodes(self, indices):
"""Return |Nodes| for these indices.
Args:
indices (tuple[int]): The indices in question.
Returns:
tuple[Node]: The |Node| objects corresponding to these indices.
Raises:
ValueError: If requested indices are not in ... | [
"def",
"indices2nodes",
"(",
"self",
",",
"indices",
")",
":",
"if",
"set",
"(",
"indices",
")",
"-",
"set",
"(",
"self",
".",
"node_indices",
")",
":",
"raise",
"ValueError",
"(",
"\"`indices` must be a subset of the Subsystem's indices.\"",
")",
"return",
"tup... | Return |Nodes| for these indices.
Args:
indices (tuple[int]): The indices in question.
Returns:
tuple[Node]: The |Node| objects corresponding to these indices.
Raises:
ValueError: If requested indices are not in the subsystem. | [
"Return",
"|Nodes|",
"for",
"these",
"indices",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L825-L923 | def convert_sqla_type_for_dialect(
coltype: TypeEngine,
dialect: Dialect,
strip_collation: bool = True,
convert_mssql_timestamp: bool = True,
expand_for_scrubbing: bool = False) -> TypeEngine:
"""
Converts an SQLAlchemy column type from one SQL dialect to another.
Ar... | [
"def",
"convert_sqla_type_for_dialect",
"(",
"coltype",
":",
"TypeEngine",
",",
"dialect",
":",
"Dialect",
",",
"strip_collation",
":",
"bool",
"=",
"True",
",",
"convert_mssql_timestamp",
":",
"bool",
"=",
"True",
",",
"expand_for_scrubbing",
":",
"bool",
"=",
... | Converts an SQLAlchemy column type from one SQL dialect to another.
Args:
coltype: SQLAlchemy column type in the source dialect
dialect: destination :class:`Dialect`
strip_collation: remove any ``COLLATION`` information?
convert_mssql_timestamp:
since you cannot write... | [
"Converts",
"an",
"SQLAlchemy",
"column",
"type",
"from",
"one",
"SQL",
"dialect",
"to",
"another",
"."
] | python | train |
barrust/pyspellchecker | spellchecker/spellchecker.py | https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L413-L420 | def remove_words(self, words):
""" Remove a list of words from the word frequency list
Args:
words (list): The list of words to remove """
for word in words:
self._dictionary.pop(word.lower())
self._update_dictionary() | [
"def",
"remove_words",
"(",
"self",
",",
"words",
")",
":",
"for",
"word",
"in",
"words",
":",
"self",
".",
"_dictionary",
".",
"pop",
"(",
"word",
".",
"lower",
"(",
")",
")",
"self",
".",
"_update_dictionary",
"(",
")"
] | Remove a list of words from the word frequency list
Args:
words (list): The list of words to remove | [
"Remove",
"a",
"list",
"of",
"words",
"from",
"the",
"word",
"frequency",
"list"
] | python | train |
huyingxi/Synonyms | synonyms/synonyms.py | https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/synonyms.py#L125-L133 | def _load_w2v(model_file=_f_model, binary=True):
'''
load word2vec model
'''
if not os.path.exists(model_file):
print("os.path : ", os.path)
raise Exception("Model file [%s] does not exist." % model_file)
return KeyedVectors.load_word2vec_format(
model_file, binary=binary, un... | [
"def",
"_load_w2v",
"(",
"model_file",
"=",
"_f_model",
",",
"binary",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"model_file",
")",
":",
"print",
"(",
"\"os.path : \"",
",",
"os",
".",
"path",
")",
"raise",
"Exception",... | load word2vec model | [
"load",
"word2vec",
"model"
] | python | train |
Galarzaa90/tibia.py | tibiapy/utils.py | https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/tibiapy/utils.py#L242-L262 | def parse_tibiacom_content(content, *, html_class="BoxContent", tag="div", builder="lxml"):
"""Parses HTML content from Tibia.com into a BeautifulSoup object.
Parameters
----------
content: :class:`str`
The raw HTML content from Tibia.com
html_class: :class:`str`
The HTML class of t... | [
"def",
"parse_tibiacom_content",
"(",
"content",
",",
"*",
",",
"html_class",
"=",
"\"BoxContent\"",
",",
"tag",
"=",
"\"div\"",
",",
"builder",
"=",
"\"lxml\"",
")",
":",
"return",
"bs4",
".",
"BeautifulSoup",
"(",
"content",
".",
"replace",
"(",
"'ISO-8859... | Parses HTML content from Tibia.com into a BeautifulSoup object.
Parameters
----------
content: :class:`str`
The raw HTML content from Tibia.com
html_class: :class:`str`
The HTML class of the parsed element. The default value is ``BoxContent``.
tag: :class:`str`
The HTML tag ... | [
"Parses",
"HTML",
"content",
"from",
"Tibia",
".",
"com",
"into",
"a",
"BeautifulSoup",
"object",
"."
] | python | train |
arcticfoxnv/slackminion | slackminion/dispatcher.py | https://github.com/arcticfoxnv/slackminion/blob/62ea77aba5ac5ba582793e578a379a76f7d26cdb/slackminion/dispatcher.py#L77-L86 | def _ignore_event(self, message):
"""
message_replied event is not truly a message event and does not have a message.text
don't process such events
commands may not be idempotent, so ignore message_changed events.
"""
if hasattr(message, 'subtype') and message.subtype in... | [
"def",
"_ignore_event",
"(",
"self",
",",
"message",
")",
":",
"if",
"hasattr",
"(",
"message",
",",
"'subtype'",
")",
"and",
"message",
".",
"subtype",
"in",
"self",
".",
"ignored_events",
":",
"return",
"True",
"return",
"False"
] | message_replied event is not truly a message event and does not have a message.text
don't process such events
commands may not be idempotent, so ignore message_changed events. | [
"message_replied",
"event",
"is",
"not",
"truly",
"a",
"message",
"event",
"and",
"does",
"not",
"have",
"a",
"message",
".",
"text",
"don",
"t",
"process",
"such",
"events"
] | python | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.