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 |
|---|---|---|---|---|---|---|---|---|
jart/fabulous | fabulous/casts.py | https://github.com/jart/fabulous/blob/19903cf0a980b82f5928c3bec1f28b6bdd3785bd/fabulous/casts.py#L32-L42 | def file(value, **kwarg):
"""value should be a path to file in the filesystem.
returns a file object
"""
#a bit weird, but I don't want to hard code default values
try:
f = open(value, **kwarg)
except IOError as e:
raise ValueError("unable to open %s : %s" % (path.abspath(va... | [
"def",
"file",
"(",
"value",
",",
"*",
"*",
"kwarg",
")",
":",
"#a bit weird, but I don't want to hard code default values",
"try",
":",
"f",
"=",
"open",
"(",
"value",
",",
"*",
"*",
"kwarg",
")",
"except",
"IOError",
"as",
"e",
":",
"raise",
"ValueError",
... | value should be a path to file in the filesystem.
returns a file object | [
"value",
"should",
"be",
"a",
"path",
"to",
"file",
"in",
"the",
"filesystem",
".",
"returns",
"a",
"file",
"object"
] | python | train |
COALAIP/pycoalaip | coalaip/model_validators.py | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L21-L42 | def does_not_contain(*avoid_keys, error_cls=ValueError):
"""Decorator: value must not contain any of the :attr:`avoid_keys`.
"""
def decorator(func):
def not_contains(instance, attribute, value):
instance_name = instance.__class__.__name__
num_matched_keys = len(set(avoid_k... | [
"def",
"does_not_contain",
"(",
"*",
"avoid_keys",
",",
"error_cls",
"=",
"ValueError",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"not_contains",
"(",
"instance",
",",
"attribute",
",",
"value",
")",
":",
"instance_name",
"=",
"instance",
... | Decorator: value must not contain any of the :attr:`avoid_keys`. | [
"Decorator",
":",
"value",
"must",
"not",
"contain",
"any",
"of",
"the",
":",
"attr",
":",
"avoid_keys",
"."
] | python | train |
rouk1/django-image-renderer | renderer/models.py | https://github.com/rouk1/django-image-renderer/blob/6a4326b77709601e18ee04f5626cf475c5ea0bb5/renderer/models.py#L49-L64 | def get_rendition_size(self, width=0, height=0):
'''returns real rendition URL'''
if width == 0 and height == 0:
return (self.master_width, self.master_height)
target_width = int(width)
target_height = int(height)
ratio = self.master_width / float(self.master_height... | [
"def",
"get_rendition_size",
"(",
"self",
",",
"width",
"=",
"0",
",",
"height",
"=",
"0",
")",
":",
"if",
"width",
"==",
"0",
"and",
"height",
"==",
"0",
":",
"return",
"(",
"self",
".",
"master_width",
",",
"self",
".",
"master_height",
")",
"targe... | returns real rendition URL | [
"returns",
"real",
"rendition",
"URL"
] | python | train |
python-odin/odinweb | odinweb/signing.py | https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/signing.py#L49-L67 | def sign_url_path(url, secret_key, expire_in=None, digest=None):
# type: (str, bytes, int, Callable) -> str
"""
Sign a URL (excluding the domain and scheme).
:param url: URL to sign
:param secret_key: Secret key
:param expire_in: Expiry time.
:param digest: Specify the digest function to us... | [
"def",
"sign_url_path",
"(",
"url",
",",
"secret_key",
",",
"expire_in",
"=",
"None",
",",
"digest",
"=",
"None",
")",
":",
"# type: (str, bytes, int, Callable) -> str",
"result",
"=",
"urlparse",
"(",
"url",
")",
"query_args",
"=",
"MultiValueDict",
"(",
"parse... | Sign a URL (excluding the domain and scheme).
:param url: URL to sign
:param secret_key: Secret key
:param expire_in: Expiry time.
:param digest: Specify the digest function to use; default is sha256 from hashlib
:return: Signed URL | [
"Sign",
"a",
"URL",
"(",
"excluding",
"the",
"domain",
"and",
"scheme",
")",
"."
] | python | train |
has2k1/plotnine | plotnine/aes.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L169-L177 | def get_calculated_aes(aesthetics):
"""
Return a list of the aesthetics that are calculated
"""
calculated_aesthetics = []
for name, value in aesthetics.items():
if is_calculated_aes(value):
calculated_aesthetics.append(name)
return calculated_aesthetics | [
"def",
"get_calculated_aes",
"(",
"aesthetics",
")",
":",
"calculated_aesthetics",
"=",
"[",
"]",
"for",
"name",
",",
"value",
"in",
"aesthetics",
".",
"items",
"(",
")",
":",
"if",
"is_calculated_aes",
"(",
"value",
")",
":",
"calculated_aesthetics",
".",
"... | Return a list of the aesthetics that are calculated | [
"Return",
"a",
"list",
"of",
"the",
"aesthetics",
"that",
"are",
"calculated"
] | python | train |
saltstack/salt | salt/modules/opkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1368-L1376 | def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr | [
"def",
"_set_trusted_option_if_needed",
"(",
"repostr",
",",
"trusted",
")",
":",
"if",
"trusted",
"is",
"True",
":",
"repostr",
"+=",
"' [trusted=yes]'",
"elif",
"trusted",
"is",
"False",
":",
"repostr",
"+=",
"' [trusted=no]'",
"return",
"repostr"
] | Set trusted option to repo if needed | [
"Set",
"trusted",
"option",
"to",
"repo",
"if",
"needed"
] | python | train |
ekmmetering/ekmmeters | ekmmeters.py | https://github.com/ekmmetering/ekmmeters/blob/b3748bdf30263bfa46ea40157bdf8df2522e1904/ekmmeters.py#L3203-L3209 | def updateObservers(self):
""" Fire update method in all attached observers in order of attachment. """
for observer in self.m_observers:
try:
observer.update(self.m_req)
except:
ekm_log(traceback.format_exc(sys.exc_info())) | [
"def",
"updateObservers",
"(",
"self",
")",
":",
"for",
"observer",
"in",
"self",
".",
"m_observers",
":",
"try",
":",
"observer",
".",
"update",
"(",
"self",
".",
"m_req",
")",
"except",
":",
"ekm_log",
"(",
"traceback",
".",
"format_exc",
"(",
"sys",
... | Fire update method in all attached observers in order of attachment. | [
"Fire",
"update",
"method",
"in",
"all",
"attached",
"observers",
"in",
"order",
"of",
"attachment",
"."
] | python | test |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnodescene.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L346-L375 | def autoLayout( self,
padX = None,
padY = None,
direction = Qt.Horizontal,
layout = 'Layered',
animate = 0,
centerOn = None,
center = None,
debug=False ):
... | [
"def",
"autoLayout",
"(",
"self",
",",
"padX",
"=",
"None",
",",
"padY",
"=",
"None",
",",
"direction",
"=",
"Qt",
".",
"Horizontal",
",",
"layout",
"=",
"'Layered'",
",",
"animate",
"=",
"0",
",",
"centerOn",
"=",
"None",
",",
"center",
"=",
"None",... | Automatically lays out all the nodes in the scene using the \
autoLayoutNodes method.
:param padX | <int> || None | default is 2 * cell width
padY | <int> || None | default is 2 * cell height
direction | <Qt.Direction>
layout | <s... | [
"Automatically",
"lays",
"out",
"all",
"the",
"nodes",
"in",
"the",
"scene",
"using",
"the",
"\\",
"autoLayoutNodes",
"method",
".",
":",
"param",
"padX",
"|",
"<int",
">",
"||",
"None",
"|",
"default",
"is",
"2",
"*",
"cell",
"width",
"padY",
"|",
"<i... | python | train |
defunkt/pystache | pystache/init.py | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/init.py#L13-L19 | def render(template, context=None, **kwargs):
"""
Return the given template string rendered using the given context.
"""
renderer = Renderer()
return renderer.render(template, context, **kwargs) | [
"def",
"render",
"(",
"template",
",",
"context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"renderer",
"=",
"Renderer",
"(",
")",
"return",
"renderer",
".",
"render",
"(",
"template",
",",
"context",
",",
"*",
"*",
"kwargs",
")"
] | Return the given template string rendered using the given context. | [
"Return",
"the",
"given",
"template",
"string",
"rendered",
"using",
"the",
"given",
"context",
"."
] | python | train |
oseledets/ttpy | tt/solvers.py | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/solvers.py#L10-L95 | def GMRES(A, u_0, b, eps=1e-6, maxit=100, m=20, _iteration=0, callback=None, verbose=0):
"""
Flexible TT GMRES
:param A: matvec(x[, eps])
:param u_0: initial vector
:param b: answer
:param maxit: max number of iterations
:param eps: required accuracy
:param m: number of iteration without... | [
"def",
"GMRES",
"(",
"A",
",",
"u_0",
",",
"b",
",",
"eps",
"=",
"1e-6",
",",
"maxit",
"=",
"100",
",",
"m",
"=",
"20",
",",
"_iteration",
"=",
"0",
",",
"callback",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"maxitexceeded",
"=",
"False"... | Flexible TT GMRES
:param A: matvec(x[, eps])
:param u_0: initial vector
:param b: answer
:param maxit: max number of iterations
:param eps: required accuracy
:param m: number of iteration without restart
:param _iteration: iteration counter
:param callback:
:param verbose: to print d... | [
"Flexible",
"TT",
"GMRES",
":",
"param",
"A",
":",
"matvec",
"(",
"x",
"[",
"eps",
"]",
")",
":",
"param",
"u_0",
":",
"initial",
"vector",
":",
"param",
"b",
":",
"answer",
":",
"param",
"maxit",
":",
"max",
"number",
"of",
"iterations",
":",
"par... | python | train |
quikmile/trellio | trellio/services.py | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/services.py#L105-L118 | def api(func=None, timeout=API_TIMEOUT): # incoming
"""
provide a request/response api
receives any requests here and return value is the response
all functions must have the following signature
- request_id
- entity (partition/routing key)
followed by kwargs
"""
if func... | [
"def",
"api",
"(",
"func",
"=",
"None",
",",
"timeout",
"=",
"API_TIMEOUT",
")",
":",
"# incoming",
"if",
"func",
"is",
"None",
":",
"return",
"partial",
"(",
"api",
",",
"timeout",
"=",
"timeout",
")",
"else",
":",
"wrapper",
"=",
"_get_api_decorator",
... | provide a request/response api
receives any requests here and return value is the response
all functions must have the following signature
- request_id
- entity (partition/routing key)
followed by kwargs | [
"provide",
"a",
"request",
"/",
"response",
"api",
"receives",
"any",
"requests",
"here",
"and",
"return",
"value",
"is",
"the",
"response",
"all",
"functions",
"must",
"have",
"the",
"following",
"signature",
"-",
"request_id",
"-",
"entity",
"(",
"partition"... | python | train |
rameshg87/pyremotevbox | pyremotevbox/ZSI/writer.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/writer.py#L163-L170 | def Forget(self, obj):
'''Forget we've seen this object.
'''
obj = _get_idstr(obj)
try:
self.memo.remove(obj)
except ValueError:
pass | [
"def",
"Forget",
"(",
"self",
",",
"obj",
")",
":",
"obj",
"=",
"_get_idstr",
"(",
"obj",
")",
"try",
":",
"self",
".",
"memo",
".",
"remove",
"(",
"obj",
")",
"except",
"ValueError",
":",
"pass"
] | Forget we've seen this object. | [
"Forget",
"we",
"ve",
"seen",
"this",
"object",
"."
] | python | train |
RealGeeks/batman | batman/path_utils.py | https://github.com/RealGeeks/batman/blob/ac61d193cbc6cc736f61ae8cf5e933a576b50698/batman/path_utils.py#L4-L26 | def normalize_path(path, basedir=None):
"""
Just a utility function that will both expand user paths if they are there:
>>> normalize_path("~/ssh")
'/home/kevin/ssh'
but won't if they are not
>>> normalize_path("ssh")
'ssh'
and you can pass a basepath to combine
>>> normalize_path(... | [
"def",
"normalize_path",
"(",
"path",
",",
"basedir",
"=",
"None",
")",
":",
"out",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
"and",
"basedir",
":",
"out",
"=",
"o... | Just a utility function that will both expand user paths if they are there:
>>> normalize_path("~/ssh")
'/home/kevin/ssh'
but won't if they are not
>>> normalize_path("ssh")
'ssh'
and you can pass a basepath to combine
>>> normalize_path("ssh","foo")
'/foo/ssh'
and wont' mess up a... | [
"Just",
"a",
"utility",
"function",
"that",
"will",
"both",
"expand",
"user",
"paths",
"if",
"they",
"are",
"there",
":",
">>>",
"normalize_path",
"(",
"~",
"/",
"ssh",
")",
"/",
"home",
"/",
"kevin",
"/",
"ssh"
] | python | train |
paramiko/paramiko | paramiko/agent.py | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/agent.py#L167-L180 | def get_connection(self):
"""
Return a pair of socket object and string address.
May block!
"""
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
conn.bind(self._agent._get_filename())
conn.listen(1)
(r, addr) = conn.accept... | [
"def",
"get_connection",
"(",
"self",
")",
":",
"conn",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"conn",
".",
"bind",
"(",
"self",
".",
"_agent",
".",
"_get_filename",
"(",
")",
... | Return a pair of socket object and string address.
May block! | [
"Return",
"a",
"pair",
"of",
"socket",
"object",
"and",
"string",
"address",
"."
] | python | train |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L86-L119 | def add_edge(self, head_id, tail_id, edge_data=1, create_nodes=True):
"""
Adds a directed edge going from head_id to tail_id.
Arbitrary data can be attached to the edge via edge_data.
It may create the nodes if adding edges between nonexisting ones.
:param head_id: head node
... | [
"def",
"add_edge",
"(",
"self",
",",
"head_id",
",",
"tail_id",
",",
"edge_data",
"=",
"1",
",",
"create_nodes",
"=",
"True",
")",
":",
"# shorcut",
"edge",
"=",
"self",
".",
"next_edge",
"# add nodes if on automatic node creation",
"if",
"create_nodes",
":",
... | Adds a directed edge going from head_id to tail_id.
Arbitrary data can be attached to the edge via edge_data.
It may create the nodes if adding edges between nonexisting ones.
:param head_id: head node
:param tail_id: tail node
:param edge_data: (optional) data attached to the e... | [
"Adds",
"a",
"directed",
"edge",
"going",
"from",
"head_id",
"to",
"tail_id",
".",
"Arbitrary",
"data",
"can",
"be",
"attached",
"to",
"the",
"edge",
"via",
"edge_data",
".",
"It",
"may",
"create",
"the",
"nodes",
"if",
"adding",
"edges",
"between",
"nonex... | python | train |
NuGrid/NuGridPy | nugridpy/ppn.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L209-L273 | def plot_xtime(self, y, x='time', label='default', labelx=None,
labely=None ,title=None, shape='.', logx=False,
logy=True, base=10):
'''
make a simple plot of two columns against each other.
An example would be instance.plot_xtime('PB206', label='PB206 vs t... | [
"def",
"plot_xtime",
"(",
"self",
",",
"y",
",",
"x",
"=",
"'time'",
",",
"label",
"=",
"'default'",
",",
"labelx",
"=",
"None",
",",
"labely",
"=",
"None",
",",
"title",
"=",
"None",
",",
"shape",
"=",
"'.'",
",",
"logx",
"=",
"False",
",",
"log... | make a simple plot of two columns against each other.
An example would be instance.plot_xtime('PB206', label='PB206 vs t_y'
Recomend using the plot function DataPlot.plot() it has more
functionality.
Parameters
----------
Y : string
Column on Y-axis.
... | [
"make",
"a",
"simple",
"plot",
"of",
"two",
"columns",
"against",
"each",
"other",
"."
] | python | train |
opennode/waldur-core | waldur_core/quotas/views.py | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/quotas/views.py#L96-L151 | def history(self, request, uuid=None):
"""
Historical data endpoints could be available for any objects (currently
implemented for quotas and events count). The data is available at *<object_endpoint>/history/*,
for example: */api/quotas/<uuid>/history/*.
There are two ways to d... | [
"def",
"history",
"(",
"self",
",",
"request",
",",
"uuid",
"=",
"None",
")",
":",
"mapped",
"=",
"{",
"'start'",
":",
"request",
".",
"query_params",
".",
"get",
"(",
"'start'",
")",
",",
"'end'",
":",
"request",
".",
"query_params",
".",
"get",
"("... | Historical data endpoints could be available for any objects (currently
implemented for quotas and events count). The data is available at *<object_endpoint>/history/*,
for example: */api/quotas/<uuid>/history/*.
There are two ways to define datetime points for historical data.
1. Send... | [
"Historical",
"data",
"endpoints",
"could",
"be",
"available",
"for",
"any",
"objects",
"(",
"currently",
"implemented",
"for",
"quotas",
"and",
"events",
"count",
")",
".",
"The",
"data",
"is",
"available",
"at",
"*",
"<object_endpoint",
">",
"/",
"history",
... | python | train |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/input_readers.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L1516-L1527 | def from_json(cls, json):
"""Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json.
"""
return cls(json[cls.BLOB_KEY_PARAM],
... | [
"def",
"from_json",
"(",
"cls",
",",
"json",
")",
":",
"return",
"cls",
"(",
"json",
"[",
"cls",
".",
"BLOB_KEY_PARAM",
"]",
",",
"json",
"[",
"cls",
".",
"START_INDEX_PARAM",
"]",
",",
"json",
"[",
"cls",
".",
"END_INDEX_PARAM",
"]",
")"
] | Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the values of json. | [
"Creates",
"an",
"instance",
"of",
"the",
"InputReader",
"for",
"the",
"given",
"input",
"shard",
"state",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnodescene.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1127-L1193 | def rebuild( self ):
"""
Rebuilds the grid lines based on the current settings and \
scene width. This method is triggered automatically, and \
shouldn't need to be manually called.
"""
rect = self.sceneRect()
x = rect.left()
y = rect.top()... | [
"def",
"rebuild",
"(",
"self",
")",
":",
"rect",
"=",
"self",
".",
"sceneRect",
"(",
")",
"x",
"=",
"rect",
".",
"left",
"(",
")",
"y",
"=",
"rect",
".",
"top",
"(",
")",
"w",
"=",
"rect",
".",
"width",
"(",
")",
"h",
"=",
"rect",
".",
"hei... | Rebuilds the grid lines based on the current settings and \
scene width. This method is triggered automatically, and \
shouldn't need to be manually called. | [
"Rebuilds",
"the",
"grid",
"lines",
"based",
"on",
"the",
"current",
"settings",
"and",
"\\",
"scene",
"width",
".",
"This",
"method",
"is",
"triggered",
"automatically",
"and",
"\\",
"shouldn",
"t",
"need",
"to",
"be",
"manually",
"called",
"."
] | python | train |
junzis/pyModeS | pyModeS/decoder/adsb.py | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/adsb.py#L311-L345 | def nic_v2(msg, NICa, NICbc):
"""Calculate NIC, navigation integrity category, for ADS-B version 2
Args:
msg (string): 28 bytes hexadecimal message string
NICa (int or string): NIC supplement - A
NICbc (int or srting): NIC supplement - B or C
Returns:
int or string: Horizon... | [
"def",
"nic_v2",
"(",
"msg",
",",
"NICa",
",",
"NICbc",
")",
":",
"if",
"typecode",
"(",
"msg",
")",
"<",
"5",
"or",
"typecode",
"(",
"msg",
")",
">",
"22",
":",
"raise",
"RuntimeError",
"(",
"\"%s: Not a surface position message (5<TC<8), \\\n airb... | Calculate NIC, navigation integrity category, for ADS-B version 2
Args:
msg (string): 28 bytes hexadecimal message string
NICa (int or string): NIC supplement - A
NICbc (int or srting): NIC supplement - B or C
Returns:
int or string: Horizontal Radius of Containment | [
"Calculate",
"NIC",
"navigation",
"integrity",
"category",
"for",
"ADS",
"-",
"B",
"version",
"2"
] | python | train |
chaoss/grimoirelab-perceval | perceval/backends/core/mattermost.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mattermost.py#L297-L311 | def posts(self, channel, page=None):
"""Fetch the history of a channel."""
entrypoint = self.RCHANNELS + '/' + channel + '/' + self.RPOSTS
params = {
self.PPER_PAGE: self.max_items
}
if page is not None:
params[self.PPAGE] = page
response = sel... | [
"def",
"posts",
"(",
"self",
",",
"channel",
",",
"page",
"=",
"None",
")",
":",
"entrypoint",
"=",
"self",
".",
"RCHANNELS",
"+",
"'/'",
"+",
"channel",
"+",
"'/'",
"+",
"self",
".",
"RPOSTS",
"params",
"=",
"{",
"self",
".",
"PPER_PAGE",
":",
"se... | Fetch the history of a channel. | [
"Fetch",
"the",
"history",
"of",
"a",
"channel",
"."
] | python | test |
NYUCCL/psiTurk | psiturk/psiturk_shell.py | https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L525-L532 | def print_config(self, _):
''' Print configuration. '''
for section in self.config.sections():
print '[%s]' % section
items = dict(self.config.items(section))
for k in items:
print "%(a)s=%(b)s" % {'a': k, 'b': items[k]}
print '' | [
"def",
"print_config",
"(",
"self",
",",
"_",
")",
":",
"for",
"section",
"in",
"self",
".",
"config",
".",
"sections",
"(",
")",
":",
"print",
"'[%s]'",
"%",
"section",
"items",
"=",
"dict",
"(",
"self",
".",
"config",
".",
"items",
"(",
"section",
... | Print configuration. | [
"Print",
"configuration",
"."
] | python | train |
saltstack/salt | salt/sdb/vault.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/vault.py#L55-L85 | def set_(key, value, profile=None):
'''
Set a key/value pair in the vault service
'''
if '?' in key:
__utils__['versions.warn_until'](
'Neon',
(
'Using ? to seperate between the path and key for vault has been deprecated '
'and will be remo... | [
"def",
"set_",
"(",
"key",
",",
"value",
",",
"profile",
"=",
"None",
")",
":",
"if",
"'?'",
"in",
"key",
":",
"__utils__",
"[",
"'versions.warn_until'",
"]",
"(",
"'Neon'",
",",
"(",
"'Using ? to seperate between the path and key for vault has been deprecated '",
... | Set a key/value pair in the vault service | [
"Set",
"a",
"key",
"/",
"value",
"pair",
"in",
"the",
"vault",
"service"
] | python | train |
elliterate/capybara.py | capybara/selector/selector.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L172-L184 | def build_selector(self):
""" Selector: Returns a new :class:`Selector` instance with the current configuration. """
kwargs = {
'label': self.label,
'descriptions': self.descriptions,
'filters': self.filters}
if self.format == "xpath":
kwargs['xpa... | [
"def",
"build_selector",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'label'",
":",
"self",
".",
"label",
",",
"'descriptions'",
":",
"self",
".",
"descriptions",
",",
"'filters'",
":",
"self",
".",
"filters",
"}",
"if",
"self",
".",
"format",
"==",
"\... | Selector: Returns a new :class:`Selector` instance with the current configuration. | [
"Selector",
":",
"Returns",
"a",
"new",
":",
"class",
":",
"Selector",
"instance",
"with",
"the",
"current",
"configuration",
"."
] | python | test |
deepmipt/DeepPavlov | deeppavlov/core/models/tf_backend.py | https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/tf_backend.py#L22-L28 | def _graph_wrap(func, graph):
"""Constructs function encapsulated in the graph."""
@wraps(func)
def _wrapped(*args, **kwargs):
with graph.as_default():
return func(*args, **kwargs)
return _wrapped | [
"def",
"_graph_wrap",
"(",
"func",
",",
"graph",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"_wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"graph",
".",
"as_default",
"(",
")",
":",
"return",
"func",
"(",
"*",
"arg... | Constructs function encapsulated in the graph. | [
"Constructs",
"function",
"encapsulated",
"in",
"the",
"graph",
"."
] | python | test |
poppy-project/pypot | pypot/vrep/remoteApiBindings/vrep.py | https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/remoteApiBindings/vrep.py#L1417-L1430 | def simxGetObjectVelocity(clientID, objectHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
linearVel = (ct.c_float*3)()
angularVel = (ct.c_float*3)()
ret = c_GetObjectVelocity(clientID, objectHandle, linearVel, angularVel, ope... | [
"def",
"simxGetObjectVelocity",
"(",
"clientID",
",",
"objectHandle",
",",
"operationMode",
")",
":",
"linearVel",
"=",
"(",
"ct",
".",
"c_float",
"*",
"3",
")",
"(",
")",
"angularVel",
"=",
"(",
"ct",
".",
"c_float",
"*",
"3",
")",
"(",
")",
"ret",
... | Please have a look at the function description/documentation in the V-REP user manual | [
"Please",
"have",
"a",
"look",
"at",
"the",
"function",
"description",
"/",
"documentation",
"in",
"the",
"V",
"-",
"REP",
"user",
"manual"
] | python | train |
synw/dataswim | dataswim/charts/__init__.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/charts/__init__.py#L458-L467 | def ropt(self, name):
"""
Remove one option
"""
try:
del self.chart_opts[name]
except KeyError:
self.warning("Option " + name + " is not set")
except:
self.err("Can not remove option " + name) | [
"def",
"ropt",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"del",
"self",
".",
"chart_opts",
"[",
"name",
"]",
"except",
"KeyError",
":",
"self",
".",
"warning",
"(",
"\"Option \"",
"+",
"name",
"+",
"\" is not set\"",
")",
"except",
":",
"self",
... | Remove one option | [
"Remove",
"one",
"option"
] | python | train |
fastai/fastai | fastai/vision/image.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L186-L192 | def resize(self, size:Union[int,TensorImageSize])->'Image':
"Resize the image to `size`, size can be a single int."
assert self._flow is None
if isinstance(size, int): size=(self.shape[0], size, size)
if tuple(size)==tuple(self.shape): return self
self.flow = _affine_grid(size)
... | [
"def",
"resize",
"(",
"self",
",",
"size",
":",
"Union",
"[",
"int",
",",
"TensorImageSize",
"]",
")",
"->",
"'Image'",
":",
"assert",
"self",
".",
"_flow",
"is",
"None",
"if",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"size",
"=",
"(",
"sel... | Resize the image to `size`, size can be a single int. | [
"Resize",
"the",
"image",
"to",
"size",
"size",
"can",
"be",
"a",
"single",
"int",
"."
] | python | train |
ejeschke/ginga | ginga/opengl/Camera.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/opengl/Camera.py#L155-L175 | def pan_delta(self, dx_px, dy_px):
"""
This causes the scene to appear to translate right and up
(i.e., what really happens is the camera is translated left and down).
This is also called "panning" in some software packages.
Passing in negative delta values causes the opposite mo... | [
"def",
"pan_delta",
"(",
"self",
",",
"dx_px",
",",
"dy_px",
")",
":",
"direction",
"=",
"self",
".",
"target",
"-",
"self",
".",
"position",
"distance_from_target",
"=",
"direction",
".",
"length",
"(",
")",
"direction",
"=",
"direction",
".",
"normalized... | This causes the scene to appear to translate right and up
(i.e., what really happens is the camera is translated left and down).
This is also called "panning" in some software packages.
Passing in negative delta values causes the opposite motion. | [
"This",
"causes",
"the",
"scene",
"to",
"appear",
"to",
"translate",
"right",
"and",
"up",
"(",
"i",
".",
"e",
".",
"what",
"really",
"happens",
"is",
"the",
"camera",
"is",
"translated",
"left",
"and",
"down",
")",
".",
"This",
"is",
"also",
"called",... | python | train |
ly0/baidupcsapi | baidupcsapi/api.py | https://github.com/ly0/baidupcsapi/blob/6f6feeef0767a75b3b968924727460eb09242d76/baidupcsapi/api.py#L1333-L1346 | def delete(self, path_list, **kwargs):
"""
删除文件或文件夹
:param path_list: 待删除的文件或文件夹列表,每一项为服务器路径
:type path_list: list
"""
data = {
'filelist': json.dumps([path for path in path_list])
}
url = 'http://{0}/api/filemanager?opera=delete'.format(BAI... | [
"def",
"delete",
"(",
"self",
",",
"path_list",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"'filelist'",
":",
"json",
".",
"dumps",
"(",
"[",
"path",
"for",
"path",
"in",
"path_list",
"]",
")",
"}",
"url",
"=",
"'http://{0}/api/filemanager?op... | 删除文件或文件夹
:param path_list: 待删除的文件或文件夹列表,每一项为服务器路径
:type path_list: list | [
"删除文件或文件夹"
] | python | train |
iotaledger/iota.lib.py | iota/codecs.py | https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/codecs.py#L197-L220 | def check_trytes_codec(encoding):
"""
Determines which codec to use for the specified encoding.
References:
- https://docs.python.org/3/library/codecs.html#codecs.register
"""
if encoding == AsciiTrytesCodec.name:
return AsciiTrytesCodec.get_codec_info()
elif encoding == AsciiTryt... | [
"def",
"check_trytes_codec",
"(",
"encoding",
")",
":",
"if",
"encoding",
"==",
"AsciiTrytesCodec",
".",
"name",
":",
"return",
"AsciiTrytesCodec",
".",
"get_codec_info",
"(",
")",
"elif",
"encoding",
"==",
"AsciiTrytesCodec",
".",
"compat_name",
":",
"warn",
"(... | Determines which codec to use for the specified encoding.
References:
- https://docs.python.org/3/library/codecs.html#codecs.register | [
"Determines",
"which",
"codec",
"to",
"use",
"for",
"the",
"specified",
"encoding",
"."
] | python | test |
aestrivex/bctpy | bct/algorithms/motifs.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/motifs.py#L398-L477 | def motif3struct_wei(W):
'''
Structural motifs are patterns of local connectivity. Motif frequency
is the frequency of occurrence of motifs around a node. Motif intensity
and coherence are weighted generalizations of motif frequency.
Parameters
----------
W : NxN np.ndarray
weighted... | [
"def",
"motif3struct_wei",
"(",
"W",
")",
":",
"from",
"scipy",
"import",
"io",
"import",
"os",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"motiflib",
")",
"mot",
"=",
"io",
".",... | Structural motifs are patterns of local connectivity. Motif frequency
is the frequency of occurrence of motifs around a node. Motif intensity
and coherence are weighted generalizations of motif frequency.
Parameters
----------
W : NxN np.ndarray
weighted directed connection matrix (all weig... | [
"Structural",
"motifs",
"are",
"patterns",
"of",
"local",
"connectivity",
".",
"Motif",
"frequency",
"is",
"the",
"frequency",
"of",
"occurrence",
"of",
"motifs",
"around",
"a",
"node",
".",
"Motif",
"intensity",
"and",
"coherence",
"are",
"weighted",
"generaliz... | python | train |
pvlib/pvlib-python | pvlib/pvsystem.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L2667-L2795 | def adrinverter(v_dc, p_dc, inverter, vtol=0.10):
r'''
Converts DC power and voltage to AC power using Anton Driesse's
Grid-Connected PV Inverter efficiency model
Parameters
----------
v_dc : numeric
A scalar or pandas series of DC voltages, in volts, which are provided
as input... | [
"def",
"adrinverter",
"(",
"v_dc",
",",
"p_dc",
",",
"inverter",
",",
"vtol",
"=",
"0.10",
")",
":",
"p_nom",
"=",
"inverter",
"[",
"'Pnom'",
"]",
"v_nom",
"=",
"inverter",
"[",
"'Vnom'",
"]",
"pac_max",
"=",
"inverter",
"[",
"'Pacmax'",
"]",
"p_nt",
... | r'''
Converts DC power and voltage to AC power using Anton Driesse's
Grid-Connected PV Inverter efficiency model
Parameters
----------
v_dc : numeric
A scalar or pandas series of DC voltages, in volts, which are provided
as input to the inverter. If Vdc and Pdc are vectors, they mus... | [
"r",
"Converts",
"DC",
"power",
"and",
"voltage",
"to",
"AC",
"power",
"using",
"Anton",
"Driesse",
"s",
"Grid",
"-",
"Connected",
"PV",
"Inverter",
"efficiency",
"model"
] | python | train |
iclab/centinel | centinel/primitives/traceroute.py | https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/traceroute.py#L22-L145 | def traceroute(domain, method="udp", cmd_arguments=None,
external=None, log_prefix=''):
"""
This function uses centinel.command to issue
a traceroute command, wait for it to finish execution and
parse the results out to a dictionary.
:param domain: the domain to be queried
:param... | [
"def",
"traceroute",
"(",
"domain",
",",
"method",
"=",
"\"udp\"",
",",
"cmd_arguments",
"=",
"None",
",",
"external",
"=",
"None",
",",
"log_prefix",
"=",
"''",
")",
":",
"# the method specified by the function parameter here will",
"# over-ride the ones given in cmd_a... | This function uses centinel.command to issue
a traceroute command, wait for it to finish execution and
parse the results out to a dictionary.
:param domain: the domain to be queried
:param method: the packet type used for traceroute, UDP by default
:param cmd_arguments: the list of arguments that n... | [
"This",
"function",
"uses",
"centinel",
".",
"command",
"to",
"issue",
"a",
"traceroute",
"command",
"wait",
"for",
"it",
"to",
"finish",
"execution",
"and",
"parse",
"the",
"results",
"out",
"to",
"a",
"dictionary",
"."
] | python | train |
SmokinCaterpillar/pypet | pypet/parameter.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/parameter.py#L1792-L1832 | def _load(self, load_dict):
"""Reconstructs objects from the pickle dumps in `load_dict`.
The 'explored_data' entry in `load_dict` is used to reconstruct
the exploration range in the correct order.
Sets the `v_protocol` property to the protocol used to store 'data'.
"""
... | [
"def",
"_load",
"(",
"self",
",",
"load_dict",
")",
":",
"if",
"self",
".",
"v_locked",
":",
"raise",
"pex",
".",
"ParameterLockedException",
"(",
"'Parameter `%s` is locked!'",
"%",
"self",
".",
"v_full_name",
")",
"if",
"'data'",
"in",
"load_dict",
":",
"d... | Reconstructs objects from the pickle dumps in `load_dict`.
The 'explored_data' entry in `load_dict` is used to reconstruct
the exploration range in the correct order.
Sets the `v_protocol` property to the protocol used to store 'data'. | [
"Reconstructs",
"objects",
"from",
"the",
"pickle",
"dumps",
"in",
"load_dict",
"."
] | python | test |
python-bonobo/bonobo | bonobo/nodes/io/file.py | https://github.com/python-bonobo/bonobo/blob/70c8e62c4a88576976e5b52e58d380d6e3227ab4/bonobo/nodes/io/file.py#L40-L58 | def output(self, context, *args, **kwargs):
"""
Allow all readers to use eventually use output_fields XOR output_type options.
"""
output_fields = self.output_fields
output_type = self.output_type
if output_fields and output_type:
raise UnrecoverableError("... | [
"def",
"output",
"(",
"self",
",",
"context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"output_fields",
"=",
"self",
".",
"output_fields",
"output_type",
"=",
"self",
".",
"output_type",
"if",
"output_fields",
"and",
"output_type",
":",
"raise"... | Allow all readers to use eventually use output_fields XOR output_type options. | [
"Allow",
"all",
"readers",
"to",
"use",
"eventually",
"use",
"output_fields",
"XOR",
"output_type",
"options",
"."
] | python | train |
kubernetes-client/python | kubernetes/client/apis/core_v1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/core_v1_api.py#L9128-L9154 | def delete_namespaced_config_map(self, name, namespace, **kwargs):
"""
delete a ConfigMap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_config_map(name, namespace, async... | [
"def",
"delete_namespaced_config_map",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
"... | delete a ConfigMap
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_config_map(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:pa... | [
"delete",
"a",
"ConfigMap",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",
">>>",
"thread",
"=",
"api",
".",
"delete_n... | python | train |
daler/metaseq | metaseq/plotutils.py | https://github.com/daler/metaseq/blob/fa875d1f72317aa7ef95cb128b739956b16eef9f/metaseq/plotutils.py#L598-L660 | def clustered_sortind(x, k=10, scorefunc=None):
"""
Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
Returns the index t... | [
"def",
"clustered_sortind",
"(",
"x",
",",
"k",
"=",
"10",
",",
"scorefunc",
"=",
"None",
")",
":",
"try",
":",
"from",
"sklearn",
".",
"cluster",
"import",
"MiniBatchKMeans",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'please install scikits.... | Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
Returns the index that will sort the rows of `x` and a list of "breaks".
`b... | [
"Uses",
"MiniBatch",
"k",
"-",
"means",
"clustering",
"to",
"cluster",
"matrix",
"into",
"groups",
"."
] | python | train |
boriel/zxbasic | asmlex.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asmlex.py#L299-L303 | def t_RP(self, t):
r'[])]'
if t.value != ']' and OPTIONS.bracket.value:
t.type = 'RPP'
return t | [
"def",
"t_RP",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
".",
"value",
"!=",
"']'",
"and",
"OPTIONS",
".",
"bracket",
".",
"value",
":",
"t",
".",
"type",
"=",
"'RPP'",
"return",
"t"
] | r'[])] | [
"r",
"[]",
")",
"]"
] | python | train |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/phystokens.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/phystokens.py#L112-L210 | def source_encoding(source):
"""Determine the encoding for `source` (a string), according to PEP 263.
Returns a string, the name of the encoding.
"""
# Note: this function should never be called on Python 3, since py3 has
# built-in tools to do this.
assert sys.version_info < (3, 0)
# Thi... | [
"def",
"source_encoding",
"(",
"source",
")",
":",
"# Note: this function should never be called on Python 3, since py3 has",
"# built-in tools to do this.",
"assert",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
"# This is mostly code adapted from Py3.2's tokenize m... | Determine the encoding for `source` (a string), according to PEP 263.
Returns a string, the name of the encoding. | [
"Determine",
"the",
"encoding",
"for",
"source",
"(",
"a",
"string",
")",
"according",
"to",
"PEP",
"263",
"."
] | python | test |
jerith/txTwitter | txtwitter/twitter.py | https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L175-L221 | def set_list_param(params, name, value, min_len=None, max_len=None):
"""
Set a list parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param list value:
The value of the parameter. If ``None``, the field ... | [
"def",
"set_list_param",
"(",
"params",
",",
"name",
",",
"value",
",",
"min_len",
"=",
"None",
",",
"max_len",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"type",
"(",
"value",
")",
"is",
"dict",
":",
"raise",
"ValueErro... | Set a list parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param list value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of ``set``, ``tuple``, or type that can b... | [
"Set",
"a",
"list",
"parameter",
"if",
"applicable",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/skarlatoudis_2013.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/skarlatoudis_2013.py#L122-L130 | def _compute_distance(self, rup, dists, C):
"""
equation 3 pag 1960:
``c31 * logR + c32 * (R-Rref)``
"""
rref = 1.0
c31 = -1.7
return (c31 * np.log10(dists.rhypo) + C['c32'] * (dists.rhypo - rref)) | [
"def",
"_compute_distance",
"(",
"self",
",",
"rup",
",",
"dists",
",",
"C",
")",
":",
"rref",
"=",
"1.0",
"c31",
"=",
"-",
"1.7",
"return",
"(",
"c31",
"*",
"np",
".",
"log10",
"(",
"dists",
".",
"rhypo",
")",
"+",
"C",
"[",
"'c32'",
"]",
"*",... | equation 3 pag 1960:
``c31 * logR + c32 * (R-Rref)`` | [
"equation",
"3",
"pag",
"1960",
":"
] | python | train |
aio-libs/yarl | yarl/__init__.py | https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L619-L627 | def _validate_authority_uri_abs_path(host, path):
"""Ensure that path in URL with authority starts with a leading slash.
Raise ValueError if not.
"""
if len(host) > 0 and len(path) > 0 and not path.startswith("/"):
raise ValueError(
"Path in a URL with author... | [
"def",
"_validate_authority_uri_abs_path",
"(",
"host",
",",
"path",
")",
":",
"if",
"len",
"(",
"host",
")",
">",
"0",
"and",
"len",
"(",
"path",
")",
">",
"0",
"and",
"not",
"path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"raise",
"ValueError",
... | Ensure that path in URL with authority starts with a leading slash.
Raise ValueError if not. | [
"Ensure",
"that",
"path",
"in",
"URL",
"with",
"authority",
"starts",
"with",
"a",
"leading",
"slash",
"."
] | python | train |
mlperf/training | reinforcement/tensorflow/minigo/coords.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/coords.py#L88-L93 | def to_gtp(coord):
"""Converts from a Minigo coordinate to a GTP coordinate."""
if coord is None:
return 'pass'
y, x = coord
return '{}{}'.format(_GTP_COLUMNS[x], go.N - y) | [
"def",
"to_gtp",
"(",
"coord",
")",
":",
"if",
"coord",
"is",
"None",
":",
"return",
"'pass'",
"y",
",",
"x",
"=",
"coord",
"return",
"'{}{}'",
".",
"format",
"(",
"_GTP_COLUMNS",
"[",
"x",
"]",
",",
"go",
".",
"N",
"-",
"y",
")"
] | Converts from a Minigo coordinate to a GTP coordinate. | [
"Converts",
"from",
"a",
"Minigo",
"coordinate",
"to",
"a",
"GTP",
"coordinate",
"."
] | python | train |
PaloAltoNetworks/pancloud | pancloud/credentials.py | https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/credentials.py#L502-L533 | def revoke_access_token(self, **kwargs):
"""Revoke access token."""
c = self.get_credentials()
data = {
'client_id': c.client_id,
'client_secret': c.client_secret,
'token': c.access_token,
'token_type_hint': 'access_token'
}
r = sel... | [
"def",
"revoke_access_token",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"c",
"=",
"self",
".",
"get_credentials",
"(",
")",
"data",
"=",
"{",
"'client_id'",
":",
"c",
".",
"client_id",
",",
"'client_secret'",
":",
"c",
".",
"client_secret",
",",
... | Revoke access token. | [
"Revoke",
"access",
"token",
"."
] | python | train |
aio-libs/aiohttp | aiohttp/client_reqrep.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/client_reqrep.py#L322-L343 | def update_headers(self, headers: Optional[LooseHeaders]) -> None:
"""Update request headers."""
self.headers = CIMultiDict() # type: CIMultiDict[str]
# add host
netloc = cast(str, self.url.raw_host)
if helpers.is_ipv6_address(netloc):
netloc = '[{}]'.format(netloc)... | [
"def",
"update_headers",
"(",
"self",
",",
"headers",
":",
"Optional",
"[",
"LooseHeaders",
"]",
")",
"->",
"None",
":",
"self",
".",
"headers",
"=",
"CIMultiDict",
"(",
")",
"# type: CIMultiDict[str]",
"# add host",
"netloc",
"=",
"cast",
"(",
"str",
",",
... | Update request headers. | [
"Update",
"request",
"headers",
"."
] | python | train |
wiredrive/wtframework | wtframework/wtf/web/page.py | https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/page.py#L167-L296 | def create_page(page_object_class_or_interface,
webdriver=None, **kwargs):
"""
Instantiate a page object from a given Interface or Abstract class.
Args:
page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or
Interface to atte... | [
"def",
"create_page",
"(",
"page_object_class_or_interface",
",",
"webdriver",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"webdriver",
":",
"webdriver",
"=",
"WTF_WEBDRIVER_MANAGER",
".",
"get_driver",
"(",
")",
"# will be used later when tracking ... | Instantiate a page object from a given Interface or Abstract class.
Args:
page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or
Interface to attempt to consturct.
Kwargs:
webdriver (WebDriver): Selenium Webdriver to use to instantiate the ... | [
"Instantiate",
"a",
"page",
"object",
"from",
"a",
"given",
"Interface",
"or",
"Abstract",
"class",
"."
] | python | train |
xtream1101/cutil | cutil/database.py | https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/database.py#L10-L20 | def _check_values(in_values):
""" Check if values need to be converted before they get mogrify'd
"""
out_values = []
for value in in_values:
# if isinstance(value, (dict, list)):
# out_values.append(json.dumps(value))
# else:
out_values... | [
"def",
"_check_values",
"(",
"in_values",
")",
":",
"out_values",
"=",
"[",
"]",
"for",
"value",
"in",
"in_values",
":",
"# if isinstance(value, (dict, list)):",
"# out_values.append(json.dumps(value))",
"# else:",
"out_values",
".",
"append",
"(",
"value",
")",
"... | Check if values need to be converted before they get mogrify'd | [
"Check",
"if",
"values",
"need",
"to",
"be",
"converted",
"before",
"they",
"get",
"mogrify",
"d"
] | python | train |
Metatab/metapack | metapack/html.py | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/html.py#L174-L242 | def make_citation_dict(td):
"""
Update a citation dictionary by editing the Author field
:param td: A BixTex format citation dict or a term
:return:
"""
from datetime import datetime
if isinstance(td, dict):
d = td
name = d['name_link']
else:
d = td.as_dict()
... | [
"def",
"make_citation_dict",
"(",
"td",
")",
":",
"from",
"datetime",
"import",
"datetime",
"if",
"isinstance",
"(",
"td",
",",
"dict",
")",
":",
"d",
"=",
"td",
"name",
"=",
"d",
"[",
"'name_link'",
"]",
"else",
":",
"d",
"=",
"td",
".",
"as_dict",
... | Update a citation dictionary by editing the Author field
:param td: A BixTex format citation dict or a term
:return: | [
"Update",
"a",
"citation",
"dictionary",
"by",
"editing",
"the",
"Author",
"field",
":",
"param",
"td",
":",
"A",
"BixTex",
"format",
"citation",
"dict",
"or",
"a",
"term",
":",
"return",
":"
] | python | train |
senaite/senaite.core | bika/lims/browser/widgets/analysisprofileanalyseswidget.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/widgets/analysisprofileanalyseswidget.py#L190-L195 | def folderitems(self):
"""TODO: Refactor to non-classic mode
"""
items = super(AnalysisProfileAnalysesView, self).folderitems()
self.categories.sort()
return items | [
"def",
"folderitems",
"(",
"self",
")",
":",
"items",
"=",
"super",
"(",
"AnalysisProfileAnalysesView",
",",
"self",
")",
".",
"folderitems",
"(",
")",
"self",
".",
"categories",
".",
"sort",
"(",
")",
"return",
"items"
] | TODO: Refactor to non-classic mode | [
"TODO",
":",
"Refactor",
"to",
"non",
"-",
"classic",
"mode"
] | python | train |
PMEAL/OpenPNM | openpnm/core/Base.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/core/Base.py#L1008-L1112 | def interleave_data(self, prop):
r"""
Retrieves requested property from associated objects, to produce a full
Np or Nt length array.
Parameters
----------
prop : string
The property name to be retrieved
Returns
-------
A full length (... | [
"def",
"interleave_data",
"(",
"self",
",",
"prop",
")",
":",
"element",
"=",
"self",
".",
"_parse_element",
"(",
"prop",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
",",
"single",
"=",
"True",
")",
"N",
"=",
"self",
".",
"project",
".",
"network... | r"""
Retrieves requested property from associated objects, to produce a full
Np or Nt length array.
Parameters
----------
prop : string
The property name to be retrieved
Returns
-------
A full length (Np or Nt) array of requested property val... | [
"r",
"Retrieves",
"requested",
"property",
"from",
"associated",
"objects",
"to",
"produce",
"a",
"full",
"Np",
"or",
"Nt",
"length",
"array",
"."
] | python | train |
jazzband/sorl-thumbnail | sorl/thumbnail/engines/wand_engine.py | https://github.com/jazzband/sorl-thumbnail/blob/22ccd9781462a820f963f57018ad3dcef85053ed/sorl/thumbnail/engines/wand_engine.py#L18-L28 | def is_valid_image(self, raw_data):
'''
Wand library makes sure when opening any image that is fine, when
the image is corrupted raises an exception.
'''
try:
Image(blob=raw_data)
return True
except (exceptions.CorruptImageError, exceptions.Missin... | [
"def",
"is_valid_image",
"(",
"self",
",",
"raw_data",
")",
":",
"try",
":",
"Image",
"(",
"blob",
"=",
"raw_data",
")",
"return",
"True",
"except",
"(",
"exceptions",
".",
"CorruptImageError",
",",
"exceptions",
".",
"MissingDelegateError",
")",
":",
"retur... | Wand library makes sure when opening any image that is fine, when
the image is corrupted raises an exception. | [
"Wand",
"library",
"makes",
"sure",
"when",
"opening",
"any",
"image",
"that",
"is",
"fine",
"when",
"the",
"image",
"is",
"corrupted",
"raises",
"an",
"exception",
"."
] | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1555-L1559 | def help_center_article_translations(self, article_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#list-translations"
api_path = "/api/v2/help_center/articles/{article_id}/translations.json"
api_path = api_path.format(article_id=article_id)
return sel... | [
"def",
"help_center_article_translations",
"(",
"self",
",",
"article_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/articles/{article_id}/translations.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"article_id",
"=",
"article... | https://developer.zendesk.com/rest_api/docs/help_center/translations#list-translations | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"help_center",
"/",
"translations#list",
"-",
"translations"
] | python | train |
trec-kba/streamcorpus-pipeline | streamcorpus_pipeline/_clean_visible.py | https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_clean_visible.py#L252-L278 | def make_clean_visible_from_raw(_html, tag_replacement_char=' '):
'''Takes an HTML-like Unicode (or UTF-8 encoded) string as input and
returns a Unicode string with all tags replaced by whitespace. In
particular, all Unicode characters inside HTML are replaced with a
single whitespace character.
Th... | [
"def",
"make_clean_visible_from_raw",
"(",
"_html",
",",
"tag_replacement_char",
"=",
"' '",
")",
":",
"if",
"not",
"isinstance",
"(",
"_html",
",",
"unicode",
")",
":",
"_html",
"=",
"unicode",
"(",
"_html",
",",
"'utf-8'",
")",
"#Strip tags with logic above",
... | Takes an HTML-like Unicode (or UTF-8 encoded) string as input and
returns a Unicode string with all tags replaced by whitespace. In
particular, all Unicode characters inside HTML are replaced with a
single whitespace character.
This *does* detect comments, style, script, link tags and replaces
them... | [
"Takes",
"an",
"HTML",
"-",
"like",
"Unicode",
"(",
"or",
"UTF",
"-",
"8",
"encoded",
")",
"string",
"as",
"input",
"and",
"returns",
"a",
"Unicode",
"string",
"with",
"all",
"tags",
"replaced",
"by",
"whitespace",
".",
"In",
"particular",
"all",
"Unicod... | python | test |
CalebBell/fluids | fluids/nrlmsise00/nrlmsise_00.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/nrlmsise00/nrlmsise_00.py#L487-L586 | def densu(alt, dlb, tinf, tlb, xm, alpha, tz, zlb, s2, mn1, zn1, tn1, tgn1):
'''
/* Calculate Temperature and Density Profiles for MSIS models
* New lower thermo polynomial
*/
tz, zn1, tn1, and tgn1 are simulated pointers
'''
rgas = 831.4
#rgas = 831.44621 #maybe make this a global constant... | [
"def",
"densu",
"(",
"alt",
",",
"dlb",
",",
"tinf",
",",
"tlb",
",",
"xm",
",",
"alpha",
",",
"tz",
",",
"zlb",
",",
"s2",
",",
"mn1",
",",
"zn1",
",",
"tn1",
",",
"tgn1",
")",
":",
"rgas",
"=",
"831.4",
"#rgas = 831.44621 #maybe make this a glob... | /* Calculate Temperature and Density Profiles for MSIS models
* New lower thermo polynomial
*/
tz, zn1, tn1, and tgn1 are simulated pointers | [
"/",
"*",
"Calculate",
"Temperature",
"and",
"Density",
"Profiles",
"for",
"MSIS",
"models",
"*",
"New",
"lower",
"thermo",
"polynomial",
"*",
"/",
"tz",
"zn1",
"tn1",
"and",
"tgn1",
"are",
"simulated",
"pointers"
] | python | train |
LLNL/certipy | certipy/certipy.py | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L203-L212 | def to_record(self):
"""Create a CertStore record from this TLSFileBundle"""
tf_list = [getattr(self, k, None) for k in
[_.value for _ in TLSFileType]]
# If a cert isn't defined in this bundle, remove it
tf_list = filter(lambda x: x, tf_list)
files = {tf.file_... | [
"def",
"to_record",
"(",
"self",
")",
":",
"tf_list",
"=",
"[",
"getattr",
"(",
"self",
",",
"k",
",",
"None",
")",
"for",
"k",
"in",
"[",
"_",
".",
"value",
"for",
"_",
"in",
"TLSFileType",
"]",
"]",
"# If a cert isn't defined in this bundle, remove it",
... | Create a CertStore record from this TLSFileBundle | [
"Create",
"a",
"CertStore",
"record",
"from",
"this",
"TLSFileBundle"
] | python | train |
obsrvbl/flowlogs-reader | flowlogs_reader/__main__.py | https://github.com/obsrvbl/flowlogs-reader/blob/248d8cb3cc586859b6744d30cebce0f359d9900c/flowlogs_reader/__main__.py#L50-L60 | def action_ipset(reader, *args):
"""Show the set of IPs seen in Flow Log records."""
ip_set = set()
for record in reader:
if record.log_status in (SKIPDATA, NODATA):
continue
ip_set.add(record.srcaddr)
ip_set.add(record.dstaddr)
for ip in ip_set:
print(ip) | [
"def",
"action_ipset",
"(",
"reader",
",",
"*",
"args",
")",
":",
"ip_set",
"=",
"set",
"(",
")",
"for",
"record",
"in",
"reader",
":",
"if",
"record",
".",
"log_status",
"in",
"(",
"SKIPDATA",
",",
"NODATA",
")",
":",
"continue",
"ip_set",
".",
"add... | Show the set of IPs seen in Flow Log records. | [
"Show",
"the",
"set",
"of",
"IPs",
"seen",
"in",
"Flow",
"Log",
"records",
"."
] | python | train |
mjirik/imcut | imcut/graph.py | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/graph.py#L586-L636 | def gen_grid_2d(shape, voxelsize):
"""
Generate list of edges for a base grid.
"""
nr, nc = shape
nrm1, ncm1 = nr - 1, nc - 1
# sh = nm.asarray(shape)
# calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols)
nedges = 0
for direction in range(len(shape)):
... | [
"def",
"gen_grid_2d",
"(",
"shape",
",",
"voxelsize",
")",
":",
"nr",
",",
"nc",
"=",
"shape",
"nrm1",
",",
"ncm1",
"=",
"nr",
"-",
"1",
",",
"nc",
"-",
"1",
"# sh = nm.asarray(shape)",
"# calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncol... | Generate list of edges for a base grid. | [
"Generate",
"list",
"of",
"edges",
"for",
"a",
"base",
"grid",
"."
] | python | train |
SheffieldML/GPy | GPy/examples/regression.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/examples/regression.py#L404-L420 | def silhouette(max_iters=100, optimize=True, plot=True):
"""Predict the pose of a figure given a silhouette. This is a task from Agarwal and Triggs 2004 ICML paper."""
try:import pods
except ImportError:
print('pods unavailable, see https://github.com/sods/ods for example datasets')
return
... | [
"def",
"silhouette",
"(",
"max_iters",
"=",
"100",
",",
"optimize",
"=",
"True",
",",
"plot",
"=",
"True",
")",
":",
"try",
":",
"import",
"pods",
"except",
"ImportError",
":",
"print",
"(",
"'pods unavailable, see https://github.com/sods/ods for example datasets'",... | Predict the pose of a figure given a silhouette. This is a task from Agarwal and Triggs 2004 ICML paper. | [
"Predict",
"the",
"pose",
"of",
"a",
"figure",
"given",
"a",
"silhouette",
".",
"This",
"is",
"a",
"task",
"from",
"Agarwal",
"and",
"Triggs",
"2004",
"ICML",
"paper",
"."
] | python | train |
Ex-Mente/auxi.0 | auxi/modelling/business/structure.py | https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L185-L197 | def remove_component(self, name):
"""
Remove a sub component from the component.
:param name: The name of the component to remove.
"""
component_to_remove = None
for c in self.components:
if c.name == name:
component_to_remove = c
if ... | [
"def",
"remove_component",
"(",
"self",
",",
"name",
")",
":",
"component_to_remove",
"=",
"None",
"for",
"c",
"in",
"self",
".",
"components",
":",
"if",
"c",
".",
"name",
"==",
"name",
":",
"component_to_remove",
"=",
"c",
"if",
"component_to_remove",
"i... | Remove a sub component from the component.
:param name: The name of the component to remove. | [
"Remove",
"a",
"sub",
"component",
"from",
"the",
"component",
"."
] | python | valid |
abseil/abseil-py | absl/logging/__init__.py | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L451-L476 | def log(level, msg, *args, **kwargs):
"""Logs 'msg % args' at absl logging level 'level'.
If no args are given just print msg, ignoring any interpolation specifiers.
Args:
level: int, the absl logging level at which to log the message
(logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose ... | [
"def",
"log",
"(",
"level",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"level",
">",
"converter",
".",
"ABSL_DEBUG",
":",
"# Even though this function supports level that is greater than 1, users",
"# should use logging.vlog instead for such ... | Logs 'msg % args' at absl logging level 'level'.
If no args are given just print msg, ignoring any interpolation specifiers.
Args:
level: int, the absl logging level at which to log the message
(logging.DEBUG|INFO|WARNING|ERROR|FATAL). While some C++ verbose logging
level constants are also su... | [
"Logs",
"msg",
"%",
"args",
"at",
"absl",
"logging",
"level",
"level",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/type/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/type/objects.py#L193-L203 | def clear_description(self):
"""Clears the description.
raise: NoAccess - ``description`` cannot be modified
*compliance: mandatory -- This method must be implemented.*
"""
if (self.get_domain_metadata().is_read_only() or
self.get_domain_metadata().is_required(... | [
"def",
"clear_description",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"get_domain_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
"or",
"self",
".",
"get_domain_metadata",
"(",
")",
".",
"is_required",
"(",
")",
")",
":",
"raise",
"errors",
".",... | Clears the description.
raise: NoAccess - ``description`` cannot be modified
*compliance: mandatory -- This method must be implemented.* | [
"Clears",
"the",
"description",
"."
] | python | train |
mfussenegger/cr8 | cr8/java_magic.py | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/java_magic.py#L57-L65 | def find_java_home(cratedb_version: tuple) -> str:
""" Return a path to a JAVA_HOME suites for the given CrateDB version """
if MIN_VERSION_FOR_JVM11 <= cratedb_version < (4, 0):
# Supports 8 to 11+, use whatever is set
return os.environ.get('JAVA_HOME', '')
if cratedb_version < MIN_VERSION_... | [
"def",
"find_java_home",
"(",
"cratedb_version",
":",
"tuple",
")",
"->",
"str",
":",
"if",
"MIN_VERSION_FOR_JVM11",
"<=",
"cratedb_version",
"<",
"(",
"4",
",",
"0",
")",
":",
"# Supports 8 to 11+, use whatever is set",
"return",
"os",
".",
"environ",
".",
"get... | Return a path to a JAVA_HOME suites for the given CrateDB version | [
"Return",
"a",
"path",
"to",
"a",
"JAVA_HOME",
"suites",
"for",
"the",
"given",
"CrateDB",
"version"
] | python | train |
klahnakoski/pyLibrary | pyLibrary/env/big_data.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/env/big_data.py#L390-L408 | def scompressed2ibytes(stream):
"""
:param stream: SOMETHING WITH read() METHOD TO GET MORE BYTES
:return: GENERATOR OF UNCOMPRESSED BYTES
"""
def more():
try:
while True:
bytes_ = stream.read(4096)
if not bytes_:
return
... | [
"def",
"scompressed2ibytes",
"(",
"stream",
")",
":",
"def",
"more",
"(",
")",
":",
"try",
":",
"while",
"True",
":",
"bytes_",
"=",
"stream",
".",
"read",
"(",
"4096",
")",
"if",
"not",
"bytes_",
":",
"return",
"yield",
"bytes_",
"except",
"Exception"... | :param stream: SOMETHING WITH read() METHOD TO GET MORE BYTES
:return: GENERATOR OF UNCOMPRESSED BYTES | [
":",
"param",
"stream",
":",
"SOMETHING",
"WITH",
"read",
"()",
"METHOD",
"TO",
"GET",
"MORE",
"BYTES",
":",
"return",
":",
"GENERATOR",
"OF",
"UNCOMPRESSED",
"BYTES"
] | python | train |
merll/docker-map | dockermap/map/client.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/client.py#L276-L292 | def restart(self, container, instances=None, map_name=None, **kwargs):
"""
Restarts instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to stop. If not specified, will restart all instances as... | [
"def",
"restart",
"(",
"self",
",",
"container",
",",
"instances",
"=",
"None",
",",
"map_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"run_actions",
"(",
"'restart'",
",",
"container",
",",
"instances",
"=",
"instances",... | Restarts instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to stop. If not specified, will restart all instances as specified in the
configuration (or just one default instance).
:type inst... | [
"Restarts",
"instances",
"for",
"a",
"container",
"configuration",
"."
] | python | train |
slightlynybbled/tk_tools | tk_tools/groups.py | https://github.com/slightlynybbled/tk_tools/blob/7c1792cad42890251a34f0617ce9b4b3e7abcf50/tk_tools/groups.py#L840-L853 | def add(self, string: (str, list)):
"""
Add a new slot to the multi-frame containing the string.
:param string: a string to insert
:return: None
"""
slot = _SlotFrame(self,
remove_callback=self._redraw,
entries=self._slo... | [
"def",
"add",
"(",
"self",
",",
"string",
":",
"(",
"str",
",",
"list",
")",
")",
":",
"slot",
"=",
"_SlotFrame",
"(",
"self",
",",
"remove_callback",
"=",
"self",
".",
"_redraw",
",",
"entries",
"=",
"self",
".",
"_slot_columns",
")",
"slot",
".",
... | Add a new slot to the multi-frame containing the string.
:param string: a string to insert
:return: None | [
"Add",
"a",
"new",
"slot",
"to",
"the",
"multi",
"-",
"frame",
"containing",
"the",
"string",
".",
":",
"param",
"string",
":",
"a",
"string",
"to",
"insert",
":",
"return",
":",
"None"
] | python | train |
dereneaton/ipyrad | ipyrad/core/assembly.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/core/assembly.py#L1503-L1585 | def merge(name, assemblies):
"""
Creates and returns a new Assembly object in which samples from two or more
Assembly objects with matching names are 'merged'. Merging does not affect
the actual files written on disk, but rather creates new Samples that are
linked to multiple data files, and with ... | [
"def",
"merge",
"(",
"name",
",",
"assemblies",
")",
":",
"## checks",
"assemblies",
"=",
"list",
"(",
"assemblies",
")",
"## create new Assembly as a branch (deepcopy)",
"merged",
"=",
"assemblies",
"[",
"0",
"]",
".",
"branch",
"(",
"name",
")",
"## get all sa... | Creates and returns a new Assembly object in which samples from two or more
Assembly objects with matching names are 'merged'. Merging does not affect
the actual files written on disk, but rather creates new Samples that are
linked to multiple data files, and with stats summed. | [
"Creates",
"and",
"returns",
"a",
"new",
"Assembly",
"object",
"in",
"which",
"samples",
"from",
"two",
"or",
"more",
"Assembly",
"objects",
"with",
"matching",
"names",
"are",
"merged",
".",
"Merging",
"does",
"not",
"affect",
"the",
"actual",
"files",
"wri... | python | valid |
Neurita/boyle | boyle/dicom/comparison.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/dicom/comparison.py#L542-L558 | def move_to_folder(self, folder_path, groupby_field_name=None):
"""Copy the file groups to folder_path. Each group will be copied into
a subfolder with named given by groupby_field.
Parameters
----------
folder_path: str
Path to where copy the DICOM files.
grou... | [
"def",
"move_to_folder",
"(",
"self",
",",
"folder_path",
",",
"groupby_field_name",
"=",
"None",
")",
":",
"try",
":",
"copy_groups_to_folder",
"(",
"self",
".",
"dicom_groups",
",",
"folder_path",
",",
"groupby_field_name",
")",
"except",
"IOError",
"as",
"ioe... | Copy the file groups to folder_path. Each group will be copied into
a subfolder with named given by groupby_field.
Parameters
----------
folder_path: str
Path to where copy the DICOM files.
groupby_field_name: str
DICOM field name. Will get the value of this f... | [
"Copy",
"the",
"file",
"groups",
"to",
"folder_path",
".",
"Each",
"group",
"will",
"be",
"copied",
"into",
"a",
"subfolder",
"with",
"named",
"given",
"by",
"groupby_field",
"."
] | python | valid |
kejbaly2/members | members/orgchart3.py | https://github.com/kejbaly2/members/blob/28e70a25cceade514c550e3ce9963f73167e8572/members/orgchart3.py#L83-L116 | def extract(uid=None, base_url=None, use_default_email_domain=False,
default_email_domain=None, user=None, password=None):
'''
FIXME: DOCS...
'''
assert base_url and isinstance(base_url, (unicode, str))
export_url = os.path.join(base_url, 'export_csv')
# ded is shortform for "defaul... | [
"def",
"extract",
"(",
"uid",
"=",
"None",
",",
"base_url",
"=",
"None",
",",
"use_default_email_domain",
"=",
"False",
",",
"default_email_domain",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"assert",
"base_url",
"and",... | FIXME: DOCS... | [
"FIXME",
":",
"DOCS",
"..."
] | python | train |
rbarrois/xworkflows | src/xworkflows/base.py | https://github.com/rbarrois/xworkflows/blob/4a94b04ba83cb43f61d4b0f7db6964a667c86b5b/src/xworkflows/base.py#L734-L745 | def get_custom_implementations(self):
"""Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation.
... | [
"def",
"get_custom_implementations",
"(",
"self",
")",
":",
"for",
"trname",
"in",
"self",
".",
"custom_implems",
":",
"attr",
"=",
"self",
".",
"transitions_at",
"[",
"trname",
"]",
"implem",
"=",
"self",
".",
"implementations",
"[",
"trname",
"]",
"yield",... | Retrieve a list of cutom implementations.
Yields:
(str, str, ImplementationProperty) tuples: The name of the attribute
an implementation lives at, the name of the related transition,
and the related implementation. | [
"Retrieve",
"a",
"list",
"of",
"cutom",
"implementations",
"."
] | python | train |
google/apitools | apitools/base/py/credentials_lib.py | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/credentials_lib.py#L477-L489 | def _refresh(self, _):
"""Refresh self.access_token.
Args:
_: (ignored) A function matching httplib2.Http.request's signature.
"""
# pylint: disable=import-error
from google.appengine.api import app_identity
try:
token, _ = app_identity.get_access_t... | [
"def",
"_refresh",
"(",
"self",
",",
"_",
")",
":",
"# pylint: disable=import-error",
"from",
"google",
".",
"appengine",
".",
"api",
"import",
"app_identity",
"try",
":",
"token",
",",
"_",
"=",
"app_identity",
".",
"get_access_token",
"(",
"self",
".",
"_s... | Refresh self.access_token.
Args:
_: (ignored) A function matching httplib2.Http.request's signature. | [
"Refresh",
"self",
".",
"access_token",
"."
] | python | train |
python-rope/rope | rope/base/pyscopes.py | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/pyscopes.py#L22-L26 | def get_name(self, name):
"""Return name `PyName` defined in this scope"""
if name not in self.get_names():
raise exceptions.NameNotFoundError('name %s not found' % name)
return self.get_names()[name] | [
"def",
"get_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"get_names",
"(",
")",
":",
"raise",
"exceptions",
".",
"NameNotFoundError",
"(",
"'name %s not found'",
"%",
"name",
")",
"return",
"self",
".",
"get_names",
... | Return name `PyName` defined in this scope | [
"Return",
"name",
"PyName",
"defined",
"in",
"this",
"scope"
] | python | train |
zetaops/zengine | zengine/messaging/model.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/messaging/model.py#L145-L151 | def delete_exchange(self):
"""
Deletes MQ exchange for this channel
Needs to be defined only once.
"""
mq_channel = self._connect_mq()
mq_channel.exchange_delete(exchange=self.code_name) | [
"def",
"delete_exchange",
"(",
"self",
")",
":",
"mq_channel",
"=",
"self",
".",
"_connect_mq",
"(",
")",
"mq_channel",
".",
"exchange_delete",
"(",
"exchange",
"=",
"self",
".",
"code_name",
")"
] | Deletes MQ exchange for this channel
Needs to be defined only once. | [
"Deletes",
"MQ",
"exchange",
"for",
"this",
"channel",
"Needs",
"to",
"be",
"defined",
"only",
"once",
"."
] | python | train |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/directory.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L4248-L4262 | def team_2_json(self):
"""
transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("Team.team_2_json")
json_obj = {
'teamID': self.id,
'teamName': self.name,
'teamDescription': self.descrip... | [
"def",
"team_2_json",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Team.team_2_json\"",
")",
"json_obj",
"=",
"{",
"'teamID'",
":",
"self",
".",
"id",
",",
"'teamName'",
":",
"self",
".",
"name",
",",
"'teamDescription'",
":",
"self",
".",
"des... | transform ariane_clip3 team object to Ariane server JSON obj
:return: Ariane JSON obj | [
"transform",
"ariane_clip3",
"team",
"object",
"to",
"Ariane",
"server",
"JSON",
"obj",
":",
"return",
":",
"Ariane",
"JSON",
"obj"
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L13801-L13820 | def set_storage_controller_bootable(self, name, bootable):
"""Sets the bootable flag of the storage controller with the given name.
in name of type str
in bootable of type bool
raises :class:`VBoxErrorObjectNotFound`
A storage controller with given name doesn't exist.
... | [
"def",
"set_storage_controller_bootable",
"(",
"self",
",",
"name",
",",
"bootable",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of type basestring\"",
")",
"if",
"not",
... | Sets the bootable flag of the storage controller with the given name.
in name of type str
in bootable of type bool
raises :class:`VBoxErrorObjectNotFound`
A storage controller with given name doesn't exist.
raises :class:`VBoxErrorObjectInUse`
Another ... | [
"Sets",
"the",
"bootable",
"flag",
"of",
"the",
"storage",
"controller",
"with",
"the",
"given",
"name",
"."
] | python | train |
slightlynybbled/tk_tools | tk_tools/groups.py | https://github.com/slightlynybbled/tk_tools/blob/7c1792cad42890251a34f0617ce9b4b3e7abcf50/tk_tools/groups.py#L109-L132 | def add_row(self, data: list):
"""
Add a row of data to the current widget
:param data: a row of data
:return: None
"""
# validation
if self.headers:
if len(self.headers) != len(data):
raise ValueError
if len(data) != self.num... | [
"def",
"add_row",
"(",
"self",
",",
"data",
":",
"list",
")",
":",
"# validation",
"if",
"self",
".",
"headers",
":",
"if",
"len",
"(",
"self",
".",
"headers",
")",
"!=",
"len",
"(",
"data",
")",
":",
"raise",
"ValueError",
"if",
"len",
"(",
"data"... | Add a row of data to the current widget
:param data: a row of data
:return: None | [
"Add",
"a",
"row",
"of",
"data",
"to",
"the",
"current",
"widget"
] | python | train |
argaen/aiocache | aiocache/base.py | https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L278-L308 | async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
... | [
"async",
"def",
"multi_set",
"(",
"self",
",",
"pairs",
",",
"ttl",
"=",
"SENTINEL",
",",
"dumps_fn",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"_conn",
"=",
"None",
")",
":",
"start",
"=",
"time",
".",
"monotonic",
"(",
")",
"dumps",
"=",
"... | Stores multiple values in the given keys.
:param pairs: list of two element iterables. First is key and second is value
:param ttl: int the expiration time in seconds. Due to memcached
restrictions if you want compatibility use int. In case you
need miliseconds, redis and memory... | [
"Stores",
"multiple",
"values",
"in",
"the",
"given",
"keys",
"."
] | python | train |
NoneGG/aredis | aredis/commands/sorted_set.py | https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sorted_set.py#L81-L110 | async def zaddoption(self, name, option=None, *args, **kwargs):
"""
Differs from zadd in that you can set either 'XX' or 'NX' option as
described here: https://redis.io/commands/zadd. Only for Redis 3.0.2 or
later.
The following example would add four values to the 'my-key' key:... | [
"async",
"def",
"zaddoption",
"(",
"self",
",",
"name",
",",
"option",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"option",
":",
"raise",
"RedisError",
"(",
"\"ZADDOPTION must take options\"",
")",
"options",
"=",
"set... | Differs from zadd in that you can set either 'XX' or 'NX' option as
described here: https://redis.io/commands/zadd. Only for Redis 3.0.2 or
later.
The following example would add four values to the 'my-key' key:
redis.zaddoption('my-key', 'XX', 1.1, 'name1', 2.2, 'name2', name3=3.3, nam... | [
"Differs",
"from",
"zadd",
"in",
"that",
"you",
"can",
"set",
"either",
"XX",
"or",
"NX",
"option",
"as",
"described",
"here",
":",
"https",
":",
"//",
"redis",
".",
"io",
"/",
"commands",
"/",
"zadd",
".",
"Only",
"for",
"Redis",
"3",
".",
"0",
".... | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/breakpoint.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L2792-L2814 | def disable_code_breakpoint(self, dwProcessId, address):
"""
Disables the code breakpoint at the given address.
@see:
L{define_code_breakpoint},
L{has_code_breakpoint},
L{get_code_breakpoint},
L{enable_code_breakpoint}
L{enable_one_sho... | [
"def",
"disable_code_breakpoint",
"(",
"self",
",",
"dwProcessId",
",",
"address",
")",
":",
"p",
"=",
"self",
".",
"system",
".",
"get_process",
"(",
"dwProcessId",
")",
"bp",
"=",
"self",
".",
"get_code_breakpoint",
"(",
"dwProcessId",
",",
"address",
")",... | Disables the code breakpoint at the given address.
@see:
L{define_code_breakpoint},
L{has_code_breakpoint},
L{get_code_breakpoint},
L{enable_code_breakpoint}
L{enable_one_shot_code_breakpoint},
L{erase_code_breakpoint},
@type dwP... | [
"Disables",
"the",
"code",
"breakpoint",
"at",
"the",
"given",
"address",
"."
] | python | train |
apache/incubator-mxnet | example/gluon/embedding_learning/train.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/embedding_learning/train.py#L169-L250 | def train(epochs, ctx):
"""Training function."""
if isinstance(ctx, mx.Context):
ctx = [ctx]
net.initialize(mx.init.Xavier(magnitude=2), ctx=ctx)
opt_options = {'learning_rate': opt.lr, 'wd': opt.wd}
if opt.optimizer == 'sgd':
opt_options['momentum'] = 0.9
if opt.optimizer == 'a... | [
"def",
"train",
"(",
"epochs",
",",
"ctx",
")",
":",
"if",
"isinstance",
"(",
"ctx",
",",
"mx",
".",
"Context",
")",
":",
"ctx",
"=",
"[",
"ctx",
"]",
"net",
".",
"initialize",
"(",
"mx",
".",
"init",
".",
"Xavier",
"(",
"magnitude",
"=",
"2",
... | Training function. | [
"Training",
"function",
"."
] | python | train |
danilobellini/audiolazy | audiolazy/lazy_auditory.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_auditory.py#L91-L125 | def gammatone_erb_constants(n):
"""
Constants for using the real bandwidth in the gammatone filter, given its
order. Returns a pair :math:`(x, y) = (1/a_n, c_n)`.
Based on equations from:
``Holdsworth, J.; Patterson, R.; Nimmo-Smith, I.; Rice, P. Implementing a
GammaTone Filter Bank. In: SVOS Final Re... | [
"def",
"gammatone_erb_constants",
"(",
"n",
")",
":",
"tnt",
"=",
"2",
"*",
"n",
"-",
"2",
"return",
"(",
"factorial",
"(",
"n",
"-",
"1",
")",
"**",
"2",
"/",
"(",
"pi",
"*",
"factorial",
"(",
"tnt",
")",
"*",
"2",
"**",
"-",
"tnt",
")",
","... | Constants for using the real bandwidth in the gammatone filter, given its
order. Returns a pair :math:`(x, y) = (1/a_n, c_n)`.
Based on equations from:
``Holdsworth, J.; Patterson, R.; Nimmo-Smith, I.; Rice, P. Implementing a
GammaTone Filter Bank. In: SVOS Final Report, Annex C, Part A: The
Auditory ... | [
"Constants",
"for",
"using",
"the",
"real",
"bandwidth",
"in",
"the",
"gammatone",
"filter",
"given",
"its",
"order",
".",
"Returns",
"a",
"pair",
":",
"math",
":",
"(",
"x",
"y",
")",
"=",
"(",
"1",
"/",
"a_n",
"c_n",
")",
"."
] | python | train |
MillionIntegrals/vel | vel/models/imagenet/resnet34.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/imagenet/resnet34.py#L75-L78 | def unfreeze(self):
""" Unfreeze model layers """
for idx, child in enumerate(self.model.children()):
mu.unfreeze_layer(child) | [
"def",
"unfreeze",
"(",
"self",
")",
":",
"for",
"idx",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"model",
".",
"children",
"(",
")",
")",
":",
"mu",
".",
"unfreeze_layer",
"(",
"child",
")"
] | Unfreeze model layers | [
"Unfreeze",
"model",
"layers"
] | python | train |
obulpathi/cdn-fastly-python | bin/fastly_upload_vcl.py | https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/bin/fastly_upload_vcl.py#L34-L111 | def main():
"""
Upload a vcl file to a fastly service, cloning the current version if
necessary. The uploaded vcl is set as main unless --include is given.
All existing vcl files will be deleted first if --delete is given.
"""
parser = OptionParser(description=
"Upload ... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"description",
"=",
"\"Upload a vcl file (set as main) to a given fastly service. All arguments are required.\"",
")",
"parser",
".",
"add_option",
"(",
"\"-k\"",
",",
"\"--key\"",
",",
"dest",
"=",
"\"ap... | Upload a vcl file to a fastly service, cloning the current version if
necessary. The uploaded vcl is set as main unless --include is given.
All existing vcl files will be deleted first if --delete is given. | [
"Upload",
"a",
"vcl",
"file",
"to",
"a",
"fastly",
"service",
"cloning",
"the",
"current",
"version",
"if",
"necessary",
".",
"The",
"uploaded",
"vcl",
"is",
"set",
"as",
"main",
"unless",
"--",
"include",
"is",
"given",
".",
"All",
"existing",
"vcl",
"f... | python | train |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L57-L80 | def tlog(x, th=1, r=_display_max, d=_l_mmax):
"""
Truncated log10 transform.
Parameters
----------
x : num | num iterable
values to be transformed.
th : num
values below th are transormed to 0.
Must be positive.
r : num (default = 10**4)
maximal transformed v... | [
"def",
"tlog",
"(",
"x",
",",
"th",
"=",
"1",
",",
"r",
"=",
"_display_max",
",",
"d",
"=",
"_l_mmax",
")",
":",
"if",
"th",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Threshold value must be positive. %s given.'",
"%",
"th",
")",
"return",
"where",
... | Truncated log10 transform.
Parameters
----------
x : num | num iterable
values to be transformed.
th : num
values below th are transormed to 0.
Must be positive.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 o... | [
"Truncated",
"log10",
"transform",
"."
] | python | train |
elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L664-L680 | def count(self):
"""
Return the number of hits matching the query and filters. Note that
only the actual number is returned.
"""
if hasattr(self, '_response'):
return self._response.hits.total
es = connections.get_connection(self._using)
d = self.to_... | [
"def",
"count",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_response'",
")",
":",
"return",
"self",
".",
"_response",
".",
"hits",
".",
"total",
"es",
"=",
"connections",
".",
"get_connection",
"(",
"self",
".",
"_using",
")",
"d",
"... | Return the number of hits matching the query and filters. Note that
only the actual number is returned. | [
"Return",
"the",
"number",
"of",
"hits",
"matching",
"the",
"query",
"and",
"filters",
".",
"Note",
"that",
"only",
"the",
"actual",
"number",
"is",
"returned",
"."
] | python | train |
janpipek/physt | physt/histogram_base.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_base.py#L244-L278 | def set_dtype(self, value, check: bool = True):
"""Change data type of the bin contents.
Allowed conversions:
- from integral to float types
- between the same category of type (float/integer)
- from float types to integer if weights are trivial
Parameters
-----... | [
"def",
"set_dtype",
"(",
"self",
",",
"value",
",",
"check",
":",
"bool",
"=",
"True",
")",
":",
"# TODO? Deal with unsigned types",
"value",
",",
"type_info",
"=",
"self",
".",
"_eval_dtype",
"(",
"value",
")",
"if",
"value",
"==",
"self",
".",
"_dtype",
... | Change data type of the bin contents.
Allowed conversions:
- from integral to float types
- between the same category of type (float/integer)
- from float types to integer if weights are trivial
Parameters
----------
value: np.dtype or something convertible to i... | [
"Change",
"data",
"type",
"of",
"the",
"bin",
"contents",
"."
] | python | train |
gitenberg-dev/gitberg | gitenberg/util/tenprintcover.py | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/util/tenprintcover.py#L97-L107 | def triangle(self, x1, y1, x2, y2, x3, y3, color):
"""
See the Processing function triangle():
https://processing.org/reference/triangle_.html
"""
self.context.set_source_rgb(*color)
self.context.move_to(self.tx(x1), self.ty(y1))
self.context.line_to(self.tx(x2), ... | [
"def",
"triangle",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
",",
"color",
")",
":",
"self",
".",
"context",
".",
"set_source_rgb",
"(",
"*",
"color",
")",
"self",
".",
"context",
".",
"move_to",
"(",
"self",
... | See the Processing function triangle():
https://processing.org/reference/triangle_.html | [
"See",
"the",
"Processing",
"function",
"triangle",
"()",
":",
"https",
":",
"//",
"processing",
".",
"org",
"/",
"reference",
"/",
"triangle_",
".",
"html"
] | python | train |
PmagPy/PmagPy | programs/pmag_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/pmag_gui.py#L441-L471 | def on_btn_thellier_gui(self, event):
"""
Open Thellier GUI
"""
if not self.check_for_meas_file():
return
if not self.check_for_uncombined_files():
return
outstring = "thellier_gui.py -WD %s"%self.WD
print("-I- running python script:\n %s"%... | [
"def",
"on_btn_thellier_gui",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"check_for_meas_file",
"(",
")",
":",
"return",
"if",
"not",
"self",
".",
"check_for_uncombined_files",
"(",
")",
":",
"return",
"outstring",
"=",
"\"thellier_gui.py -... | Open Thellier GUI | [
"Open",
"Thellier",
"GUI"
] | python | train |
bpsmith/tia | tia/rlab/table.py | https://github.com/bpsmith/tia/blob/a7043b6383e557aeea8fc7112bbffd6e36a230e9/tia/rlab/table.py#L391-L405 | def apply_styles(self, cmdmap):
"""
Apply the set of commands defined in cmdmap. for example, apply_styles({'FONTSIZE': 12, 'BACKGROUND': white})
:param cmdmap: dict of commands mapped to the command arguments
:return: self
"""
is_list_like = lambda arg: isinstance(arg, (... | [
"def",
"apply_styles",
"(",
"self",
",",
"cmdmap",
")",
":",
"is_list_like",
"=",
"lambda",
"arg",
":",
"isinstance",
"(",
"arg",
",",
"(",
"list",
",",
"tuple",
")",
")",
"is_first_param_list",
"=",
"lambda",
"c",
":",
"c",
"in",
"(",
"'COLBACKGROUNDS'"... | Apply the set of commands defined in cmdmap. for example, apply_styles({'FONTSIZE': 12, 'BACKGROUND': white})
:param cmdmap: dict of commands mapped to the command arguments
:return: self | [
"Apply",
"the",
"set",
"of",
"commands",
"defined",
"in",
"cmdmap",
".",
"for",
"example",
"apply_styles",
"(",
"{",
"FONTSIZE",
":",
"12",
"BACKGROUND",
":",
"white",
"}",
")",
":",
"param",
"cmdmap",
":",
"dict",
"of",
"commands",
"mapped",
"to",
"the"... | python | train |
modin-project/modin | modin/experimental/engines/pandas_on_ray/sql.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L93-L106 | def check_query(query):
""" Check query sanity
Args:
query: query string
Returns:
None
"""
q = query.lower()
if "select " not in q:
raise InvalidQuery("SELECT word not found in the query: {0}".format(query))
if " from " not in q:
raise InvalidQuery("FROM wor... | [
"def",
"check_query",
"(",
"query",
")",
":",
"q",
"=",
"query",
".",
"lower",
"(",
")",
"if",
"\"select \"",
"not",
"in",
"q",
":",
"raise",
"InvalidQuery",
"(",
"\"SELECT word not found in the query: {0}\"",
".",
"format",
"(",
"query",
")",
")",
"if",
"... | Check query sanity
Args:
query: query string
Returns:
None | [
"Check",
"query",
"sanity"
] | python | train |
CZ-NIC/python-rt | rt.py | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1079-L1123 | def get_user(self, user_id):
""" Get user details.
:param user_id: Identification of user by username (str) or user ID
(int)
:returns: User details as strings in dictionary with these keys for RT
users:
* Lang
... | [
"def",
"get_user",
"(",
"self",
",",
"user_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'user/{}'",
".",
"format",
"(",
"str",
"(",
"user_id",
")",
",",
")",
")",
"status_code",
"=",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"i... | Get user details.
:param user_id: Identification of user by username (str) or user ID
(int)
:returns: User details as strings in dictionary with these keys for RT
users:
* Lang
* RealName
* Priv... | [
"Get",
"user",
"details",
"."
] | python | train |
Britefury/batchup | batchup/data_source.py | https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L1404-L1424 | def samples_by_indices_nomapping(self, indices):
"""
Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Re... | [
"def",
"samples_by_indices_nomapping",
"(",
"self",
",",
"indices",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'samples_by_indices_nomapping method not '",
"'supported as one or more of the underlying '",
"'data sources does not suppo... | Gather a batch of samples by indices *without* applying any index
mapping.
Parameters
----------
indices: 1D-array of ints or slice
An index array or a slice that selects the samples to retrieve
Returns
-------
nested list of arrays
A min... | [
"Gather",
"a",
"batch",
"of",
"samples",
"by",
"indices",
"*",
"without",
"*",
"applying",
"any",
"index",
"mapping",
"."
] | python | train |
toomore/grs | grs/twseopen.py | https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/twseopen.py#L52-L71 | def __loaddate():
''' 載入檔案
檔案依據 http://www.twse.com.tw/ch/trading/trading_days.php
'''
csv_path = os.path.join(os.path.dirname(__file__), 'opendate.csv')
with open(csv_path) as csv_file:
csv_data = csv.reader(csv_file)
result = {}
result['c... | [
"def",
"__loaddate",
"(",
")",
":",
"csv_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'opendate.csv'",
")",
"with",
"open",
"(",
"csv_path",
")",
"as",
"csv_file",
":",
"csv_data",
"=... | 載入檔案
檔案依據 http://www.twse.com.tw/ch/trading/trading_days.php | [
"載入檔案",
"檔案依據",
"http",
":",
"//",
"www",
".",
"twse",
".",
"com",
".",
"tw",
"/",
"ch",
"/",
"trading",
"/",
"trading_days",
".",
"php"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/lib/deepreload.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/deepreload.py#L46-L117 | def get_parent(globals, level):
"""
parent, name = get_parent(globals, level)
Return the package that an import is being performed in. If globals comes
from the module foo.bar.bat (not itself a package), this returns the
sys.modules entry for foo.bar. If globals is from a package's __init__.py,
... | [
"def",
"get_parent",
"(",
"globals",
",",
"level",
")",
":",
"orig_level",
"=",
"level",
"if",
"not",
"level",
"or",
"not",
"isinstance",
"(",
"globals",
",",
"dict",
")",
":",
"return",
"None",
",",
"''",
"pkgname",
"=",
"globals",
".",
"get",
"(",
... | parent, name = get_parent(globals, level)
Return the package that an import is being performed in. If globals comes
from the module foo.bar.bat (not itself a package), this returns the
sys.modules entry for foo.bar. If globals is from a package's __init__.py,
the package's entry in sys.modules is ret... | [
"parent",
"name",
"=",
"get_parent",
"(",
"globals",
"level",
")"
] | python | test |
hweickert/where | where/__init__.py | https://github.com/hweickert/where/blob/ff07c5df81a2e854e8e1b88c932b493452b9cb83/where/__init__.py#L32-L37 | def iwhere( filename ):
""" Like where() but returns an iterator. """
possible_paths = _gen_possible_matches( filename )
existing_file_paths = filter( os.path.isfile, possible_paths )
return existing_file_paths | [
"def",
"iwhere",
"(",
"filename",
")",
":",
"possible_paths",
"=",
"_gen_possible_matches",
"(",
"filename",
")",
"existing_file_paths",
"=",
"filter",
"(",
"os",
".",
"path",
".",
"isfile",
",",
"possible_paths",
")",
"return",
"existing_file_paths"
] | Like where() but returns an iterator. | [
"Like",
"where",
"()",
"but",
"returns",
"an",
"iterator",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/hierarchy/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/hierarchy/sessions.py#L1146-L1186 | def update_hierarchy(self, hierarchy_form):
"""Updates an existing hierarchy.
arg: hierarchy_form (osid.hierarchy.HierarchyForm): the form
containing the elements to be updated
raise: IllegalState - ``hierarchy_form`` already used in an
update transaction
... | [
"def",
"update_hierarchy",
"(",
"self",
",",
"hierarchy_form",
")",
":",
"# Implemented from template for",
"# osid.resource.BinAdminSession.update_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
"... | Updates an existing hierarchy.
arg: hierarchy_form (osid.hierarchy.HierarchyForm): the form
containing the elements to be updated
raise: IllegalState - ``hierarchy_form`` already used in an
update transaction
raise: InvalidArgument - the form contains an inv... | [
"Updates",
"an",
"existing",
"hierarchy",
"."
] | python | train |
maaku/python-bitcoin | bitcoin/merkle.py | https://github.com/maaku/python-bitcoin/blob/1b80c284170fd3f547cc45f4700ce169f3f99641/bitcoin/merkle.py#L14-L40 | def _merkle_hash256(*args):
"""The default transform provided to merkle(), which calculates the hash
of its parameters, serializes and joins them together, then performs a
has256 of the resulting string. There are two special cases: no arguments,
which results in 0, and a single argument, whose hash val... | [
"def",
"_merkle_hash256",
"(",
"*",
"args",
")",
":",
"# Return zero-hash is no arguments are provided (the hash of an empty",
"# Merkle tree is defined to be zero).",
"if",
"not",
"args",
":",
"return",
"0",
"# This helper function extracts and returns the hash value of a parameter.",... | The default transform provided to merkle(), which calculates the hash
of its parameters, serializes and joins them together, then performs a
has256 of the resulting string. There are two special cases: no arguments,
which results in 0, and a single argument, whose hash value is returned
unmodified. | [
"The",
"default",
"transform",
"provided",
"to",
"merkle",
"()",
"which",
"calculates",
"the",
"hash",
"of",
"its",
"parameters",
"serializes",
"and",
"joins",
"them",
"together",
"then",
"performs",
"a",
"has256",
"of",
"the",
"resulting",
"string",
".",
"The... | python | train |
liip/taxi | taxi/plugins.py | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/plugins.py#L68-L72 | def get_backends_by_class(self, backend_class):
"""
Return a list of backends that are instances of the given `backend_class`.
"""
return [backend for backend in self._backends_registry.values() if isinstance(backend, backend_class)] | [
"def",
"get_backends_by_class",
"(",
"self",
",",
"backend_class",
")",
":",
"return",
"[",
"backend",
"for",
"backend",
"in",
"self",
".",
"_backends_registry",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"backend",
",",
"backend_class",
")",
"]"
] | Return a list of backends that are instances of the given `backend_class`. | [
"Return",
"a",
"list",
"of",
"backends",
"that",
"are",
"instances",
"of",
"the",
"given",
"backend_class",
"."
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_snackbar.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_snackbar.py#L181-L191 | def set_duration(self, duration):
""" Android for whatever stupid reason doesn't let you set the time
it only allows 1-long or 0-short. So we have to repeatedly call show
until the duration expires, hence this method does nothing see
`set_show`.
"""
if duration ... | [
"def",
"set_duration",
"(",
"self",
",",
"duration",
")",
":",
"if",
"duration",
"==",
"0",
":",
"self",
".",
"widget",
".",
"setDuration",
"(",
"-",
"2",
")",
"#: Infinite",
"else",
":",
"self",
".",
"widget",
".",
"setDuration",
"(",
"0",
")"
] | Android for whatever stupid reason doesn't let you set the time
it only allows 1-long or 0-short. So we have to repeatedly call show
until the duration expires, hence this method does nothing see
`set_show`. | [
"Android",
"for",
"whatever",
"stupid",
"reason",
"doesn",
"t",
"let",
"you",
"set",
"the",
"time",
"it",
"only",
"allows",
"1",
"-",
"long",
"or",
"0",
"-",
"short",
".",
"So",
"we",
"have",
"to",
"repeatedly",
"call",
"show",
"until",
"the",
"duratio... | python | train |
bapakode/OmMongo | ommongo/update_expression.py | https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/update_expression.py#L91-L106 | def inc(self, *args, **kwargs):
''' Atomically increment ``qfield`` by ``value`` '''
pairs = []
if len(args) == 1:
pairs.append((args[0], 1))
elif len(args) == 2:
pairs.append(args)
elif len(kwargs) != 0:
pairs.extend([(k, v) for k, v in kwargs... | [
"def",
"inc",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pairs",
"=",
"[",
"]",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"pairs",
".",
"append",
"(",
"(",
"args",
"[",
"0",
"]",
",",
"1",
")",
")",
"elif",
"l... | Atomically increment ``qfield`` by ``value`` | [
"Atomically",
"increment",
"qfield",
"by",
"value"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.