repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
angr/angr | angr/analyses/cfg/cfg_emulated.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_emulated.py#L2232-L2391 | def _try_resolving_indirect_jumps(self, sim_successors, cfg_node, func_addr, successors, exception_info, artifacts):
"""
Resolve indirect jumps specified by sim_successors.addr.
:param SimSuccessors sim_successors: The SimSuccessors instance.
:param CFGNode cfg_node: ... | [
"def",
"_try_resolving_indirect_jumps",
"(",
"self",
",",
"sim_successors",
",",
"cfg_node",
",",
"func_addr",
",",
"successors",
",",
"exception_info",
",",
"artifacts",
")",
":",
"# Try to resolve indirect jumps with advanced backward slicing (if enabled)",
"if",
"sim_succe... | Resolve indirect jumps specified by sim_successors.addr.
:param SimSuccessors sim_successors: The SimSuccessors instance.
:param CFGNode cfg_node: The CFGNode instance.
:param int func_addr: Current function address.
:param list successors: ... | [
"Resolve",
"indirect",
"jumps",
"specified",
"by",
"sim_successors",
".",
"addr",
"."
] | python | train | 57.2 |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/service_reflection.py#L269-L284 | def _StubMethod(self, stub, method_descriptor,
rpc_controller, request, callback):
"""The body of all service methods in the generated stub class.
Args:
stub: Stub instance.
method_descriptor: Descriptor of the invoked method.
rpc_controller: Rpc controller to execute the me... | [
"def",
"_StubMethod",
"(",
"self",
",",
"stub",
",",
"method_descriptor",
",",
"rpc_controller",
",",
"request",
",",
"callback",
")",
":",
"return",
"stub",
".",
"rpc_channel",
".",
"CallMethod",
"(",
"method_descriptor",
",",
"rpc_controller",
",",
"request",
... | The body of all service methods in the generated stub class.
Args:
stub: Stub instance.
method_descriptor: Descriptor of the invoked method.
rpc_controller: Rpc controller to execute the method.
request: Request protocol message.
callback: A callback to execute when the method finishe... | [
"The",
"body",
"of",
"all",
"service",
"methods",
"in",
"the",
"generated",
"stub",
"class",
"."
] | python | train | 40.25 |
epfl-idevelop/epfl-ldap | epflldap/utils.py | https://github.com/epfl-idevelop/epfl-ldap/blob/bebb94da3609d358bd83f31672eeaddcda872c5d/epflldap/utils.py#L11-L22 | def get_optional_env(key):
"""
Return the value of an optional environment variable, and use
the provided default if it's not set.
"""
environment_variable_value = os.environ.get(key)
if environment_variable_value:
return environment_variable_value
elif key in CONSTANTS:
retu... | [
"def",
"get_optional_env",
"(",
"key",
")",
":",
"environment_variable_value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"key",
")",
"if",
"environment_variable_value",
":",
"return",
"environment_variable_value",
"elif",
"key",
"in",
"CONSTANTS",
":",
"return",... | Return the value of an optional environment variable, and use
the provided default if it's not set. | [
"Return",
"the",
"value",
"of",
"an",
"optional",
"environment",
"variable",
"and",
"use",
"the",
"provided",
"default",
"if",
"it",
"s",
"not",
"set",
"."
] | python | train | 33.583333 |
edeposit/marcxml_parser | src/marcxml_parser/parser.py | https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/parser.py#L290-L312 | def get_i_name(self, num, is_oai=None):
"""
This method is used mainly internally, but it can be handy if you work
with with raw MARC XML object and not using getters.
Args:
num (int): Which indicator you need (1/2).
is_oai (bool/None): If None, :attr:`.oai_marc`... | [
"def",
"get_i_name",
"(",
"self",
",",
"num",
",",
"is_oai",
"=",
"None",
")",
":",
"if",
"num",
"not",
"in",
"(",
"1",
",",
"2",
")",
":",
"raise",
"ValueError",
"(",
"\"`num` parameter have to be 1 or 2!\"",
")",
"if",
"is_oai",
"is",
"None",
":",
"i... | This method is used mainly internally, but it can be handy if you work
with with raw MARC XML object and not using getters.
Args:
num (int): Which indicator you need (1/2).
is_oai (bool/None): If None, :attr:`.oai_marc` is
used.
Returns:
s... | [
"This",
"method",
"is",
"used",
"mainly",
"internally",
"but",
"it",
"can",
"be",
"handy",
"if",
"you",
"work",
"with",
"with",
"raw",
"MARC",
"XML",
"object",
"and",
"not",
"using",
"getters",
"."
] | python | valid | 30.913043 |
sarugaku/pipfile-cli | tasks.py | https://github.com/sarugaku/pipfile-cli/blob/ee9f8d1137e7423d2adc7e5748e8287b4402903d/tasks.py#L31-L43 | def upload(ctx, repo):
"""Upload the package to an index server.
This implies cleaning and re-building the package.
:param repo: Required. Name of the index server to upload to, as specifies
in your .pypirc configuration file.
"""
artifacts = ' '.join(
shlex.quote(str(n))
f... | [
"def",
"upload",
"(",
"ctx",
",",
"repo",
")",
":",
"artifacts",
"=",
"' '",
".",
"join",
"(",
"shlex",
".",
"quote",
"(",
"str",
"(",
"n",
")",
")",
"for",
"n",
"in",
"ROOT",
".",
"joinpath",
"(",
"'dist'",
")",
".",
"glob",
"(",
"'pipfile[-_]cl... | Upload the package to an index server.
This implies cleaning and re-building the package.
:param repo: Required. Name of the index server to upload to, as specifies
in your .pypirc configuration file. | [
"Upload",
"the",
"package",
"to",
"an",
"index",
"server",
"."
] | python | valid | 33.153846 |
senaite/senaite.jsonapi | src/senaite/jsonapi/fieldmanagers.py | https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/fieldmanagers.py#L362-L373 | def get_filename(self, instance):
"""Get the filename
"""
filename = self.field.getFilename(instance)
if filename:
return filename
fieldname = self.get_field_name()
content_type = self.get_content_type(instance)
extension = mimetypes.guess_extension(c... | [
"def",
"get_filename",
"(",
"self",
",",
"instance",
")",
":",
"filename",
"=",
"self",
".",
"field",
".",
"getFilename",
"(",
"instance",
")",
"if",
"filename",
":",
"return",
"filename",
"fieldname",
"=",
"self",
".",
"get_field_name",
"(",
")",
"content... | Get the filename | [
"Get",
"the",
"filename"
] | python | train | 29.916667 |
tradenity/python-sdk | tradenity/resources/country.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/country.py#L908-L929 | def update_country_by_id(cls, country_id, country, **kwargs):
"""Update Country
Update attributes of Country
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_country_by_id(country_id, co... | [
"def",
"update_country_by_id",
"(",
"cls",
",",
"country_id",
",",
"country",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_up... | Update Country
Update attributes of Country
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_country_by_id(country_id, country, async=True)
>>> result = thread.get()
:param asyn... | [
"Update",
"Country"
] | python | train | 43.727273 |
ionata/dj-core | dj_core/utils.py | https://github.com/ionata/dj-core/blob/7a3139fc433c17f27e7dc2cee8775db21e0b5c89/dj_core/utils.py#L70-L79 | def import_from_string(value):
"""Copy of rest_framework.settings.import_from_string"""
value = value.replace('-', '_')
try:
module_path, class_name = value.rsplit('.', 1)
module = import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) ... | [
"def",
"import_from_string",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"try",
":",
"module_path",
",",
"class_name",
"=",
"value",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"import_module... | Copy of rest_framework.settings.import_from_string | [
"Copy",
"of",
"rest_framework",
".",
"settings",
".",
"import_from_string"
] | python | train | 43.1 |
yyuu/botornado | boto/s3/bucketlistresultset.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/s3/bucketlistresultset.py#L58-L74 | def versioned_bucket_lister(bucket, prefix='', delimiter='',
key_marker='', version_id_marker='', headers=None):
"""
A generator function for listing versions in a bucket.
"""
more_results = True
k = None
while more_results:
rs = bucket.get_all_versions(prefix... | [
"def",
"versioned_bucket_lister",
"(",
"bucket",
",",
"prefix",
"=",
"''",
",",
"delimiter",
"=",
"''",
",",
"key_marker",
"=",
"''",
",",
"version_id_marker",
"=",
"''",
",",
"headers",
"=",
"None",
")",
":",
"more_results",
"=",
"True",
"k",
"=",
"None... | A generator function for listing versions in a bucket. | [
"A",
"generator",
"function",
"for",
"listing",
"versions",
"in",
"a",
"bucket",
"."
] | python | train | 41.647059 |
nicolargo/glances | glances/__init__.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/__init__.py#L86-L112 | def start(config, args):
"""Start Glances."""
# Load mode
global mode
if core.is_standalone():
from glances.standalone import GlancesStandalone as GlancesMode
elif core.is_client():
if core.is_client_browser():
from glances.client_browser import GlancesClientBrowser as ... | [
"def",
"start",
"(",
"config",
",",
"args",
")",
":",
"# Load mode",
"global",
"mode",
"if",
"core",
".",
"is_standalone",
"(",
")",
":",
"from",
"glances",
".",
"standalone",
"import",
"GlancesStandalone",
"as",
"GlancesMode",
"elif",
"core",
".",
"is_clien... | Start Glances. | [
"Start",
"Glances",
"."
] | python | train | 29.37037 |
carta/ldap_tools | src/ldap_tools/user.py | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L93-L117 | def __ldap_attr(self, fname, lname, type, group,
group_api): # pragma: no cover
"""User LDAP attributes."""
return {
'uid':
str(self.username).encode(),
'cn':
' '.join([fname, lname]).encode(),
'sn':
str(lname).... | [
"def",
"__ldap_attr",
"(",
"self",
",",
"fname",
",",
"lname",
",",
"type",
",",
"group",
",",
"group_api",
")",
":",
"# pragma: no cover",
"return",
"{",
"'uid'",
":",
"str",
"(",
"self",
".",
"username",
")",
".",
"encode",
"(",
")",
",",
"'cn'",
"... | User LDAP attributes. | [
"User",
"LDAP",
"attributes",
"."
] | python | train | 35.48 |
Turbo87/aerofiles | aerofiles/xcsoar/writer.py | https://github.com/Turbo87/aerofiles/blob/d8b7b04a1fcea5c98f89500de1164619a4ec7ef4/aerofiles/xcsoar/writer.py#L106-L129 | def write_point(self, **kw):
"""
Write a task point to the file::
with writer.write_point(type=PointType.TURN):
writer.write_waypoint(...)
writer.write_observation_zone(...)
# <Point type="Turn"> ... </Point>
Inside the with clause the
... | [
"def",
"write_point",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"assert",
"'type'",
"in",
"kw",
"self",
".",
"convert_bool",
"(",
"kw",
",",
"'score_exit'",
")",
"return",
"self",
".",
"write_tag_with_content",
"(",
"'Point'",
",",
"*",
"*",
"kw",
")... | Write a task point to the file::
with writer.write_point(type=PointType.TURN):
writer.write_waypoint(...)
writer.write_observation_zone(...)
# <Point type="Turn"> ... </Point>
Inside the with clause the
:meth:`~aerofiles.xcsoar.Writer.write_wayp... | [
"Write",
"a",
"task",
"point",
"to",
"the",
"file",
"::"
] | python | train | 31.791667 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavwp.py#L370-L378 | def polygon_list(self):
'''return a list of polygons for the waypoints'''
done = set()
ret = []
while len(done) != self.count():
p = self.polygon(done)
if len(p) > 0:
ret.append(p)
return ret | [
"def",
"polygon_list",
"(",
"self",
")",
":",
"done",
"=",
"set",
"(",
")",
"ret",
"=",
"[",
"]",
"while",
"len",
"(",
"done",
")",
"!=",
"self",
".",
"count",
"(",
")",
":",
"p",
"=",
"self",
".",
"polygon",
"(",
"done",
")",
"if",
"len",
"(... | return a list of polygons for the waypoints | [
"return",
"a",
"list",
"of",
"polygons",
"for",
"the",
"waypoints"
] | python | train | 29.222222 |
devopshq/artifactory | artifactory.py | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L260-L276 | def encode_matrix_parameters(parameters):
"""
Performs encoding of url matrix parameters from dictionary to
a string.
See http://www.w3.org/DesignIssues/MatrixURIs.html for specs.
"""
result = []
for param in iter(sorted(parameters)):
if isinstance(parameters[param], (list, tuple)):... | [
"def",
"encode_matrix_parameters",
"(",
"parameters",
")",
":",
"result",
"=",
"[",
"]",
"for",
"param",
"in",
"iter",
"(",
"sorted",
"(",
"parameters",
")",
")",
":",
"if",
"isinstance",
"(",
"parameters",
"[",
"param",
"]",
",",
"(",
"list",
",",
"tu... | Performs encoding of url matrix parameters from dictionary to
a string.
See http://www.w3.org/DesignIssues/MatrixURIs.html for specs. | [
"Performs",
"encoding",
"of",
"url",
"matrix",
"parameters",
"from",
"dictionary",
"to",
"a",
"string",
".",
"See",
"http",
":",
"//",
"www",
".",
"w3",
".",
"org",
"/",
"DesignIssues",
"/",
"MatrixURIs",
".",
"html",
"for",
"specs",
"."
] | python | train | 29.235294 |
saltstack/salt | salt/modules/mac_desktop.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_desktop.py#L135-L150 | def _check_cmd(call):
'''
Check the output of the cmd.run_all function call.
'''
if call['retcode'] != 0:
comment = ''
std_err = call.get('stderr')
std_out = call.get('stdout')
if std_err:
comment += std_err
if std_out:
comment += std_out
... | [
"def",
"_check_cmd",
"(",
"call",
")",
":",
"if",
"call",
"[",
"'retcode'",
"]",
"!=",
"0",
":",
"comment",
"=",
"''",
"std_err",
"=",
"call",
".",
"get",
"(",
"'stderr'",
")",
"std_out",
"=",
"call",
".",
"get",
"(",
"'stdout'",
")",
"if",
"std_er... | Check the output of the cmd.run_all function call. | [
"Check",
"the",
"output",
"of",
"the",
"cmd",
".",
"run_all",
"function",
"call",
"."
] | python | train | 25.1875 |
python-cmd2/cmd2 | tasks.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/tasks.py#L144-L154 | def eggs_clean(context):
"Remove egg directories"
#pylint: disable=unused-argument
dirs = set()
dirs.add('.eggs')
for name in os.listdir(os.curdir):
if name.endswith('.egg-info'):
dirs.add(name)
if name.endswith('.egg'):
dirs.add(name)
rmrf(dirs) | [
"def",
"eggs_clean",
"(",
"context",
")",
":",
"#pylint: disable=unused-argument",
"dirs",
"=",
"set",
"(",
")",
"dirs",
".",
"add",
"(",
"'.eggs'",
")",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"curdir",
")",
":",
"if",
"name",
".",
... | Remove egg directories | [
"Remove",
"egg",
"directories"
] | python | train | 27.272727 |
Clinical-Genomics/scout | scout/server/blueprints/login/controllers.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/login/controllers.py#L20-L34 | def users(store):
"""Display a list of all users and which institutes they belong to."""
user_objs = list(store.users())
total_events = store.user_events().count()
for user_obj in user_objs:
if user_obj.get('institutes'):
user_obj['institutes'] = [store.institute(inst_id) for inst_id... | [
"def",
"users",
"(",
"store",
")",
":",
"user_objs",
"=",
"list",
"(",
"store",
".",
"users",
"(",
")",
")",
"total_events",
"=",
"store",
".",
"user_events",
"(",
")",
".",
"count",
"(",
")",
"for",
"user_obj",
"in",
"user_objs",
":",
"if",
"user_ob... | Display a list of all users and which institutes they belong to. | [
"Display",
"a",
"list",
"of",
"all",
"users",
"and",
"which",
"institutes",
"they",
"belong",
"to",
"."
] | python | test | 43.066667 |
saltstack/salt | salt/cloud/clouds/nova.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/nova.py#L1096-L1147 | def list_nodes(call=None, **kwargs):
'''
Return a list of the VMs that in this location
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
conn = get_conn()
server_list = conn.server_list... | [
"def",
"list_nodes",
"(",
"call",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"conn",
"=",... | Return a list of the VMs that in this location | [
"Return",
"a",
"list",
"of",
"the",
"VMs",
"that",
"in",
"this",
"location"
] | python | train | 32.942308 |
keflavich/plfit | plfit/plfit.py | https://github.com/keflavich/plfit/blob/7dafa6302b427ba8c89651148e3e9d29add436c3/plfit/plfit.py#L455-L472 | def xminvsks(self, **kwargs):
"""
Plot xmin versus the ks value for derived alpha. This plot can be used
as a diagnostic of whether you have derived the 'best' fit: if there are
multiple local minima, your data set may be well suited to a broken
powerlaw or a different function.... | [
"def",
"xminvsks",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"pylab",
".",
"plot",
"(",
"self",
".",
"_xmins",
",",
"self",
".",
"_xmin_kstest",
",",
"'.'",
")",
"pylab",
".",
"plot",
"(",
"self",
".",
"_xmin",
",",
"self",
".",
"_ks",
",",... | Plot xmin versus the ks value for derived alpha. This plot can be used
as a diagnostic of whether you have derived the 'best' fit: if there are
multiple local minima, your data set may be well suited to a broken
powerlaw or a different function. | [
"Plot",
"xmin",
"versus",
"the",
"ks",
"value",
"for",
"derived",
"alpha",
".",
"This",
"plot",
"can",
"be",
"used",
"as",
"a",
"diagnostic",
"of",
"whether",
"you",
"have",
"derived",
"the",
"best",
"fit",
":",
"if",
"there",
"are",
"multiple",
"local",... | python | test | 34.666667 |
475Cumulus/TBone | tbone/resources/resources.py | https://github.com/475Cumulus/TBone/blob/5a6672d8bbac449a0ab9e99560609f671fe84d4d/tbone/resources/resources.py#L241-L243 | def as_detail(cls, protocol=Protocol.http, *args, **kwargs):
''' returns detail views '''
return cls.as_view('detail', protocol, *args, **kwargs) | [
"def",
"as_detail",
"(",
"cls",
",",
"protocol",
"=",
"Protocol",
".",
"http",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"as_view",
"(",
"'detail'",
",",
"protocol",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | returns detail views | [
"returns",
"detail",
"views"
] | python | train | 53 |
aichaos/rivescript-python | rivescript/rivescript.py | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L663-L676 | def set_substitution(self, what, rep):
"""Set a substitution.
Equivalent to ``! sub`` in RiveScript code.
:param str what: The original text to replace.
:param str rep: The text to replace it with.
Set this to ``None`` to delete the substitution.
"""
if rep ... | [
"def",
"set_substitution",
"(",
"self",
",",
"what",
",",
"rep",
")",
":",
"if",
"rep",
"is",
"None",
":",
"# Unset the variable.",
"if",
"what",
"in",
"self",
".",
"_subs",
":",
"del",
"self",
".",
"_subs",
"[",
"what",
"]",
"self",
".",
"_subs",
"[... | Set a substitution.
Equivalent to ``! sub`` in RiveScript code.
:param str what: The original text to replace.
:param str rep: The text to replace it with.
Set this to ``None`` to delete the substitution. | [
"Set",
"a",
"substitution",
"."
] | python | train | 32.285714 |
pyviz/holoviews | holoviews/ipython/display_hooks.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/ipython/display_hooks.py#L83-L87 | def first_frame(obj):
"Only display the first frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
plot.update(0)
return {'text/html': renderer.html(plot, fmt)} | [
"def",
"first_frame",
"(",
"obj",
")",
":",
"plot",
",",
"renderer",
",",
"fmt",
"=",
"single_frame_plot",
"(",
"obj",
")",
"plot",
".",
"update",
"(",
"0",
")",
"return",
"{",
"'text/html'",
":",
"renderer",
".",
"html",
"(",
"plot",
",",
"fmt",
")"... | Only display the first frame of an animated plot | [
"Only",
"display",
"the",
"first",
"frame",
"of",
"an",
"animated",
"plot"
] | python | train | 38.2 |
rigetti/pyquil | examples/meyer_penny_game.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/examples/meyer_penny_game.py#L26-L53 | def meyer_penny_program():
"""
Returns the program to simulate the Meyer-Penny Game
The full description is available in docs/source/examples.rst
:return: pyQuil Program
"""
prog = pq.Program()
ro = prog.declare('ro', memory_size=2)
picard_register = ro[1]
answer_register = ro[0]
... | [
"def",
"meyer_penny_program",
"(",
")",
":",
"prog",
"=",
"pq",
".",
"Program",
"(",
")",
"ro",
"=",
"prog",
".",
"declare",
"(",
"'ro'",
",",
"memory_size",
"=",
"2",
")",
"picard_register",
"=",
"ro",
"[",
"1",
"]",
"answer_register",
"=",
"ro",
"[... | Returns the program to simulate the Meyer-Penny Game
The full description is available in docs/source/examples.rst
:return: pyQuil Program | [
"Returns",
"the",
"program",
"to",
"simulate",
"the",
"Meyer",
"-",
"Penny",
"Game",
"The",
"full",
"description",
"is",
"available",
"in",
"docs",
"/",
"source",
"/",
"examples",
".",
"rst"
] | python | train | 29.928571 |
dwavesystems/dimod | dimod/sampleset.py | https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/sampleset.py#L1279-L1331 | def to_serializable(self, use_bytes=False, bytes_type=bytes):
"""Convert a :class:`SampleSet` to a serializable object.
Note that the contents of the :attr:`.SampleSet.info` field are assumed
to be serializable.
Args:
use_bytes (bool, optional, default=False):
... | [
"def",
"to_serializable",
"(",
"self",
",",
"use_bytes",
"=",
"False",
",",
"bytes_type",
"=",
"bytes",
")",
":",
"schema_version",
"=",
"\"2.0.0\"",
"record",
"=",
"{",
"name",
":",
"array2bytes",
"(",
"vector",
")",
"for",
"name",
",",
"vector",
"in",
... | Convert a :class:`SampleSet` to a serializable object.
Note that the contents of the :attr:`.SampleSet.info` field are assumed
to be serializable.
Args:
use_bytes (bool, optional, default=False):
If True, a compact representation representing the biases as bytes is ... | [
"Convert",
"a",
":",
"class",
":",
"SampleSet",
"to",
"a",
"serializable",
"object",
"."
] | python | train | 39.377358 |
yinkaisheng/Python-UIAutomation-for-Windows | uiautomation/uiautomation.py | https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2247-L2259 | def GetConsoleOriginalTitle() -> str:
"""
GetConsoleOriginalTitle from Win32.
Return str.
Only available on Windows Vista or higher.
"""
if IsNT6orHigher:
arrayType = ctypes.c_wchar * MAX_PATH
values = arrayType()
ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MA... | [
"def",
"GetConsoleOriginalTitle",
"(",
")",
"->",
"str",
":",
"if",
"IsNT6orHigher",
":",
"arrayType",
"=",
"ctypes",
".",
"c_wchar",
"*",
"MAX_PATH",
"values",
"=",
"arrayType",
"(",
")",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"GetConsoleOriginalTitle... | GetConsoleOriginalTitle from Win32.
Return str.
Only available on Windows Vista or higher. | [
"GetConsoleOriginalTitle",
"from",
"Win32",
".",
"Return",
"str",
".",
"Only",
"available",
"on",
"Windows",
"Vista",
"or",
"higher",
"."
] | python | valid | 34.461538 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/lxml/html/clean.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/lxml/html/clean.py#L651-L690 | def word_break(el, max_width=40,
avoid_elements=_avoid_word_break_elements,
avoid_classes=_avoid_word_break_classes,
break_character=unichr(0x200b)):
"""
Breaks any long words found in the body of the text (not attributes).
Doesn't effect any of the tags in avoi... | [
"def",
"word_break",
"(",
"el",
",",
"max_width",
"=",
"40",
",",
"avoid_elements",
"=",
"_avoid_word_break_elements",
",",
"avoid_classes",
"=",
"_avoid_word_break_classes",
",",
"break_character",
"=",
"unichr",
"(",
"0x200b",
")",
")",
":",
"# Character suggestio... | Breaks any long words found in the body of the text (not attributes).
Doesn't effect any of the tags in avoid_elements, by default
``<textarea>`` and ``<pre>``
Breaks words by inserting ​, which is a unicode character
for Zero Width Space character. This generally takes up no space
in rende... | [
"Breaks",
"any",
"long",
"words",
"found",
"in",
"the",
"body",
"of",
"the",
"text",
"(",
"not",
"attributes",
")",
"."
] | python | test | 37.65 |
saltstack/salt | salt/utils/docker/translate/helpers.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/docker/translate/helpers.py#L96-L127 | def map_vals(val, *names, **extra_opts):
'''
Many arguments come in as a list of VAL1:VAL2 pairs, but map to a list
of dicts in the format {NAME1: VAL1, NAME2: VAL2}. This function
provides common code to handle these instances.
'''
fill = extra_opts.pop('fill', NOTSET)
expected_num_elements... | [
"def",
"map_vals",
"(",
"val",
",",
"*",
"names",
",",
"*",
"*",
"extra_opts",
")",
":",
"fill",
"=",
"extra_opts",
".",
"pop",
"(",
"'fill'",
",",
"NOTSET",
")",
"expected_num_elements",
"=",
"len",
"(",
"names",
")",
"val",
"=",
"translate_stringlist",... | Many arguments come in as a list of VAL1:VAL2 pairs, but map to a list
of dicts in the format {NAME1: VAL1, NAME2: VAL2}. This function
provides common code to handle these instances. | [
"Many",
"arguments",
"come",
"in",
"as",
"a",
"list",
"of",
"VAL1",
":",
"VAL2",
"pairs",
"but",
"map",
"to",
"a",
"list",
"of",
"dicts",
"in",
"the",
"format",
"{",
"NAME1",
":",
"VAL1",
"NAME2",
":",
"VAL2",
"}",
".",
"This",
"function",
"provides"... | python | train | 44.15625 |
rocky/python-xdis | xdis/magics.py | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/magics.py#L42-L53 | def int2magic(magic_int):
"""Given a magic int like 62211, compute the corresponding magic byte string
b'\x03\xf3\r\n' using the conversion method that does this.
See also dictionary magic2nt2version which has precomputed these values
for knonwn magic_int's.
"""
if (sys.version_info >= (3, 0)... | [
"def",
"int2magic",
"(",
"magic_int",
")",
":",
"if",
"(",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"'<Hcc'",
",",
"magic_int",
",",
"bytes",
"(",
"'\\r'",
",",
"'utf-8'",
")",
",",
... | Given a magic int like 62211, compute the corresponding magic byte string
b'\x03\xf3\r\n' using the conversion method that does this.
See also dictionary magic2nt2version which has precomputed these values
for knonwn magic_int's. | [
"Given",
"a",
"magic",
"int",
"like",
"62211",
"compute",
"the",
"corresponding",
"magic",
"byte",
"string",
"b",
"\\",
"x03",
"\\",
"xf3",
"\\",
"r",
"\\",
"n",
"using",
"the",
"conversion",
"method",
"that",
"does",
"this",
"."
] | python | train | 39.083333 |
cons3rt/pycons3rt | pycons3rt/bash.py | https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L1115-L1149 | def get_remote_host_environment_variable(host, environment_variable):
"""Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param environment_variable: (str) variable to query
:return: (str) value of the environment variable
:raises: TypeE... | [
"def",
"get_remote_host_environment_variable",
"(",
"host",
",",
"environment_variable",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_remote_host_environment_variable'",
")",
"if",
"not",
"isinstance",
"(",
"host",
",",
"basestring... | Retrieves the value of an environment variable of a
remote host over SSH
:param host: (str) host to query
:param environment_variable: (str) variable to query
:return: (str) value of the environment variable
:raises: TypeError, CommandError | [
"Retrieves",
"the",
"value",
"of",
"an",
"environment",
"variable",
"of",
"a",
"remote",
"host",
"over",
"SSH"
] | python | train | 41.2 |
PyCQA/pylint | pylint/checkers/imports.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L644-L652 | def _check_position(self, node):
"""Check `node` import or importfrom node position is correct
Send a message if `node` comes before another instruction
"""
# if a first non-import instruction has already been encountered,
# it means the import comes after it and therefore is n... | [
"def",
"_check_position",
"(",
"self",
",",
"node",
")",
":",
"# if a first non-import instruction has already been encountered,",
"# it means the import comes after it and therefore is not well placed",
"if",
"self",
".",
"_first_non_import_node",
":",
"self",
".",
"add_message",
... | Check `node` import or importfrom node position is correct
Send a message if `node` comes before another instruction | [
"Check",
"node",
"import",
"or",
"importfrom",
"node",
"position",
"is",
"correct"
] | python | test | 50.444444 |
Kozea/cairocffi | cairocffi/context.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1086-L1113 | def arc_negative(self, xc, yc, radius, angle1, angle2):
"""Adds a circular arc of the given radius to the current path.
The arc is centered at ``(xc, yc)``,
begins at :obj:`angle1`
and proceeds in the direction of decreasing angles
to end at :obj:`angle2`.
If :obj:`angle2... | [
"def",
"arc_negative",
"(",
"self",
",",
"xc",
",",
"yc",
",",
"radius",
",",
"angle1",
",",
"angle2",
")",
":",
"cairo",
".",
"cairo_arc_negative",
"(",
"self",
".",
"_pointer",
",",
"xc",
",",
"yc",
",",
"radius",
",",
"angle1",
",",
"angle2",
")",... | Adds a circular arc of the given radius to the current path.
The arc is centered at ``(xc, yc)``,
begins at :obj:`angle1`
and proceeds in the direction of decreasing angles
to end at :obj:`angle2`.
If :obj:`angle2` is greater than :obj:`angle1`
it will be progressively de... | [
"Adds",
"a",
"circular",
"arc",
"of",
"the",
"given",
"radius",
"to",
"the",
"current",
"path",
".",
"The",
"arc",
"is",
"centered",
"at",
"(",
"xc",
"yc",
")",
"begins",
"at",
":",
"obj",
":",
"angle1",
"and",
"proceeds",
"in",
"the",
"direction",
"... | python | train | 38.571429 |
chaoss/grimoirelab-sortinghat | sortinghat/cmd/init.py | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/init.py#L133-L144 | def __read_countries_file(self):
"""Read countries from a CSV file"""
import csv
import pkg_resources
filename = pkg_resources.resource_filename('sortinghat', 'data/countries.csv')
with open(filename, 'r') as f:
reader = csv.DictReader(f, fieldnames=['name', 'code',... | [
"def",
"__read_countries_file",
"(",
"self",
")",
":",
"import",
"csv",
"import",
"pkg_resources",
"filename",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"'sortinghat'",
",",
"'data/countries.csv'",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
... | Read countries from a CSV file | [
"Read",
"countries",
"from",
"a",
"CSV",
"file"
] | python | train | 33.416667 |
aleju/imgaug | imgaug/augmentables/segmaps.py | https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/segmaps.py#L505-L541 | def from_heatmaps(heatmaps, class_indices=None, nb_classes=None):
"""
Convert heatmaps to segmentation map.
Assumes that each class is represented as a single heatmap channel.
Parameters
----------
heatmaps : imgaug.HeatmapsOnImage
Heatmaps to convert.
... | [
"def",
"from_heatmaps",
"(",
"heatmaps",
",",
"class_indices",
"=",
"None",
",",
"nb_classes",
"=",
"None",
")",
":",
"if",
"class_indices",
"is",
"None",
":",
"return",
"SegmentationMapOnImage",
"(",
"heatmaps",
".",
"arr_0to1",
",",
"shape",
"=",
"heatmaps",... | Convert heatmaps to segmentation map.
Assumes that each class is represented as a single heatmap channel.
Parameters
----------
heatmaps : imgaug.HeatmapsOnImage
Heatmaps to convert.
class_indices : None or list of int, optional
List of class indices re... | [
"Convert",
"heatmaps",
"to",
"segmentation",
"map",
"."
] | python | valid | 43.297297 |
daler/metaseq | metaseq/minibrowser.py | https://github.com/daler/metaseq/blob/fa875d1f72317aa7ef95cb128b739956b16eef9f/metaseq/minibrowser.py#L475-L481 | def panels(self):
"""
Add 2 panels to the figure, top for signal and bottom for gene models
"""
ax1 = self.fig.add_subplot(211)
ax2 = self.fig.add_subplot(212, sharex=ax1)
return (ax2, self.gene_panel), (ax1, self.signal_panel) | [
"def",
"panels",
"(",
"self",
")",
":",
"ax1",
"=",
"self",
".",
"fig",
".",
"add_subplot",
"(",
"211",
")",
"ax2",
"=",
"self",
".",
"fig",
".",
"add_subplot",
"(",
"212",
",",
"sharex",
"=",
"ax1",
")",
"return",
"(",
"ax2",
",",
"self",
".",
... | Add 2 panels to the figure, top for signal and bottom for gene models | [
"Add",
"2",
"panels",
"to",
"the",
"figure",
"top",
"for",
"signal",
"and",
"bottom",
"for",
"gene",
"models"
] | python | train | 38.428571 |
usc-isi-i2/etk | etk/knowledge_graph.py | https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/knowledge_graph.py#L28-L43 | def validate_field(self, field_name: str) -> bool:
"""
Complain if a field in not in the schema
Args:
field_name:
Returns: True if the field is present.
"""
if field_name in {"@id", "@type"}:
return True
result = self.schema.has_field(fie... | [
"def",
"validate_field",
"(",
"self",
",",
"field_name",
":",
"str",
")",
"->",
"bool",
":",
"if",
"field_name",
"in",
"{",
"\"@id\"",
",",
"\"@type\"",
"}",
":",
"return",
"True",
"result",
"=",
"self",
".",
"schema",
".",
"has_field",
"(",
"field_name"... | Complain if a field in not in the schema
Args:
field_name:
Returns: True if the field is present. | [
"Complain",
"if",
"a",
"field",
"in",
"not",
"in",
"the",
"schema",
"Args",
":",
"field_name",
":"
] | python | train | 33.75 |
saltstack/salt | salt/modules/parallels.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parallels.py#L423-L501 | def snapshot_id_to_name(name, snap_id, strict=False, runas=None):
'''
Attempt to convert a snapshot ID to a snapshot name. If the snapshot has
no name or if the ID is not found or invalid, an empty string will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param... | [
"def",
"snapshot_id_to_name",
"(",
"name",
",",
"snap_id",
",",
"strict",
"=",
"False",
",",
"runas",
"=",
"None",
")",
":",
"# Validate VM name and snapshot ID",
"name",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"name",
")",
"if",
"not",... | Attempt to convert a snapshot ID to a snapshot name. If the snapshot has
no name or if the ID is not found or invalid, an empty string will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param str snap_id:
ID of the snapshot
:param bool strict:
Rais... | [
"Attempt",
"to",
"convert",
"a",
"snapshot",
"ID",
"to",
"a",
"snapshot",
"name",
".",
"If",
"the",
"snapshot",
"has",
"no",
"name",
"or",
"if",
"the",
"ID",
"is",
"not",
"found",
"or",
"invalid",
"an",
"empty",
"string",
"will",
"be",
"returned"
] | python | train | 30.708861 |
loftylabs/django-developer-panel | djdev_panel/middleware.py | https://github.com/loftylabs/django-developer-panel/blob/52fd2666a158b197fdd643d3c2c4d9bbc5ba230a/djdev_panel/middleware.py#L191-L217 | def process_response(self, request, response):
"""Let's handle old-style response processing here, as usual."""
# For debug only.
if not settings.DEBUG:
return response
# Check for responses where the data can't be inserted.
content_encoding = response.get('Content-... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"# For debug only.",
"if",
"not",
"settings",
".",
"DEBUG",
":",
"return",
"response",
"# Check for responses where the data can't be inserted.",
"content_encoding",
"=",
"response",
".",... | Let's handle old-style response processing here, as usual. | [
"Let",
"s",
"handle",
"old",
"-",
"style",
"response",
"processing",
"here",
"as",
"usual",
"."
] | python | train | 38.481481 |
minhhoit/yacms | yacms/core/fields.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/fields.py#L29-L47 | def formfield(self, **kwargs):
"""
Apply the widget class defined by the
``RICHTEXT_WIDGET_CLASS`` setting.
"""
default = kwargs.get("widget", None) or AdminTextareaWidget
if default is AdminTextareaWidget:
from yacms.conf import settings
richtext_... | [
"def",
"formfield",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"default",
"=",
"kwargs",
".",
"get",
"(",
"\"widget\"",
",",
"None",
")",
"or",
"AdminTextareaWidget",
"if",
"default",
"is",
"AdminTextareaWidget",
":",
"from",
"yacms",
".",
"conf",
"... | Apply the widget class defined by the
``RICHTEXT_WIDGET_CLASS`` setting. | [
"Apply",
"the",
"widget",
"class",
"defined",
"by",
"the",
"RICHTEXT_WIDGET_CLASS",
"setting",
"."
] | python | train | 46.473684 |
honzamach/pynspect | pynspect/rules.py | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/rules.py#L547-L560 | def traverse(self, traverser, **kwargs):
"""
Implementation of mandatory interface for traversing the whole rule tree.
This method will call the implementation of :py:func:`pynspect.rules.RuleTreeTraverser.binary_operation_logical`
method with reference to ``self`` instance as first argu... | [
"def",
"traverse",
"(",
"self",
",",
"traverser",
",",
"*",
"*",
"kwargs",
")",
":",
"rrt",
"=",
"self",
".",
"right",
".",
"traverse",
"(",
"traverser",
",",
"*",
"*",
"kwargs",
")",
"return",
"traverser",
".",
"unary_operation",
"(",
"self",
",",
"... | Implementation of mandatory interface for traversing the whole rule tree.
This method will call the implementation of :py:func:`pynspect.rules.RuleTreeTraverser.binary_operation_logical`
method with reference to ``self`` instance as first argument and with the
result of traversing left subtree a... | [
"Implementation",
"of",
"mandatory",
"interface",
"for",
"traversing",
"the",
"whole",
"rule",
"tree",
".",
"This",
"method",
"will",
"call",
"the",
"implementation",
"of",
":",
"py",
":",
"func",
":",
"pynspect",
".",
"rules",
".",
"RuleTreeTraverser",
".",
... | python | train | 63.5 |
calve/prof | prof/tools.py | https://github.com/calve/prof/blob/c6e034f45ab60908dea661e8271bc44758aeedcf/prof/tools.py#L9-L17 | def check_update():
"""
Return True if an update is available on pypi
"""
r = requests.get("https://pypi.python.org/pypi/prof/json")
data = r.json()
if versiontuple(data['info']['version']) > versiontuple(__version__):
return True
return False | [
"def",
"check_update",
"(",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"\"https://pypi.python.org/pypi/prof/json\"",
")",
"data",
"=",
"r",
".",
"json",
"(",
")",
"if",
"versiontuple",
"(",
"data",
"[",
"'info'",
"]",
"[",
"'version'",
"]",
")",
">... | Return True if an update is available on pypi | [
"Return",
"True",
"if",
"an",
"update",
"is",
"available",
"on",
"pypi"
] | python | train | 30.111111 |
Peter-Slump/django-dynamic-fixtures | src/dynamic_fixtures/fixtures/runner.py | https://github.com/Peter-Slump/django-dynamic-fixtures/blob/da99b4b12b11be28ea4b36b6cf2896ca449c73c1/src/dynamic_fixtures/fixtures/runner.py#L53-L77 | def get_fixture_node(self, app_label, fixture_prefix):
"""
Get all fixtures in given app with given prefix.
:param str app_label: App label
:param str fixture_prefix: first part of the fixture name
:return: list of found fixtures.
"""
app_nodes = self.get_app_node... | [
"def",
"get_fixture_node",
"(",
"self",
",",
"app_label",
",",
"fixture_prefix",
")",
":",
"app_nodes",
"=",
"self",
".",
"get_app_nodes",
"(",
"app_label",
"=",
"app_label",
")",
"nodes",
"=",
"[",
"node",
"for",
"node",
"in",
"app_nodes",
"if",
"node",
"... | Get all fixtures in given app with given prefix.
:param str app_label: App label
:param str fixture_prefix: first part of the fixture name
:return: list of found fixtures. | [
"Get",
"all",
"fixtures",
"in",
"given",
"app",
"with",
"given",
"prefix",
".",
":",
"param",
"str",
"app_label",
":",
"App",
"label",
":",
"param",
"str",
"fixture_prefix",
":",
"first",
"part",
"of",
"the",
"fixture",
"name",
":",
"return",
":",
"list"... | python | train | 38.76 |
tBuLi/symfit | symfit/contrib/interactive_guess/interactive_guess.py | https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/contrib/interactive_guess/interactive_guess.py#L117-L156 | def _set_up_figure(self, x_mins, x_maxs, y_mins, y_maxs):
"""
Prepare the matplotlib figure: make all the subplots; adjust their
x and y range; plot the data; and plot an putative function.
"""
self.fig = plt.figure()
# Make room for the sliders:
bot = 0.1 + 0.05... | [
"def",
"_set_up_figure",
"(",
"self",
",",
"x_mins",
",",
"x_maxs",
",",
"y_mins",
",",
"y_maxs",
")",
":",
"self",
".",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"# Make room for the sliders:",
"bot",
"=",
"0.1",
"+",
"0.05",
"*",
"len",
"(",
"self"... | Prepare the matplotlib figure: make all the subplots; adjust their
x and y range; plot the data; and plot an putative function. | [
"Prepare",
"the",
"matplotlib",
"figure",
":",
"make",
"all",
"the",
"subplots",
";",
"adjust",
"their",
"x",
"and",
"y",
"range",
";",
"plot",
"the",
"data",
";",
"and",
"plot",
"an",
"putative",
"function",
"."
] | python | train | 42.925 |
mgoral/subconvert | src/subconvert/gui/DataModel.py | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/DataModel.py#L90-L103 | def execute(self, cmd):
"""Execute a command to modify storage[cmd.filePath]"""
if not cmd.filePath in self._history.keys():
self._history[cmd.filePath] = SubtitleUndoStack(self)
try:
self._history[cmd.filePath].push(cmd)
except:
self._... | [
"def",
"execute",
"(",
"self",
",",
"cmd",
")",
":",
"if",
"not",
"cmd",
".",
"filePath",
"in",
"self",
".",
"_history",
".",
"keys",
"(",
")",
":",
"self",
".",
"_history",
"[",
"cmd",
".",
"filePath",
"]",
"=",
"SubtitleUndoStack",
"(",
"self",
"... | Execute a command to modify storage[cmd.filePath] | [
"Execute",
"a",
"command",
"to",
"modify",
"storage",
"[",
"cmd",
".",
"filePath",
"]"
] | python | train | 39 |
danilobellini/audiolazy | audiolazy/lazy_synth.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L301-L321 | def ones(dur=None):
"""
Ones stream generator.
You may multiply your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "1.0" during a given time duration (if any) or
endlessly.
... | [
"def",
"ones",
"(",
"dur",
"=",
"None",
")",
":",
"if",
"dur",
"is",
"None",
"or",
"(",
"isinf",
"(",
"dur",
")",
"and",
"dur",
">",
"0",
")",
":",
"while",
"True",
":",
"yield",
"1.0",
"for",
"x",
"in",
"xrange",
"(",
"int",
"(",
".5",
"+",
... | Ones stream generator.
You may multiply your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "1.0" during a given time duration (if any) or
endlessly. | [
"Ones",
"stream",
"generator",
".",
"You",
"may",
"multiply",
"your",
"endless",
"stream",
"by",
"this",
"to",
"enforce",
"an",
"end",
"to",
"it",
"."
] | python | train | 20.52381 |
AirtestProject/Poco | poco/proxy.py | https://github.com/AirtestProject/Poco/blob/2c559a586adf3fd11ee81cabc446d4d3f6f2d119/poco/proxy.py#L597-L629 | def get_position(self, focus=None):
"""
Get the position of the UI elements.
Args:
focus: focus point of UI proxy, see :py:meth:`.focus() <poco.proxy.UIObjectProxy.focus>` for more details
Returns:
2-list/2-tuple: coordinates (x, y) in NormalizedCoordinate syst... | [
"def",
"get_position",
"(",
"self",
",",
"focus",
"=",
"None",
")",
":",
"focus",
"=",
"focus",
"or",
"self",
".",
"_focus",
"or",
"'anchor'",
"if",
"focus",
"==",
"'anchor'",
":",
"pos",
"=",
"self",
".",
"attr",
"(",
"'pos'",
")",
"elif",
"focus",
... | Get the position of the UI elements.
Args:
focus: focus point of UI proxy, see :py:meth:`.focus() <poco.proxy.UIObjectProxy.focus>` for more details
Returns:
2-list/2-tuple: coordinates (x, y) in NormalizedCoordinate system
Raises:
TypeError: raised when u... | [
"Get",
"the",
"position",
"of",
"the",
"UI",
"elements",
"."
] | python | train | 36.151515 |
byt3bl33d3r/CrackMapExec | cme/modules/bloodhound.py | https://github.com/byt3bl33d3r/CrackMapExec/blob/333f1c4e06884e85b2776459963ef85d182aba8e/cme/modules/bloodhound.py#L23-L58 | def options(self, context, module_options):
'''
THREADS Max numbers of threads to execute on target (defaults to 20)
COLLECTIONMETHOD Method used by BloodHound ingestor to collect data (defaults to 'Default')
CSVPATH (optional) Path where csv files will be writ... | [
"def",
"options",
"(",
"self",
",",
"context",
",",
"module_options",
")",
":",
"self",
".",
"threads",
"=",
"3",
"self",
".",
"csv_path",
"=",
"'C:\\\\'",
"self",
".",
"collection_method",
"=",
"'Default'",
"self",
".",
"neo4j_URI",
"=",
"\"\"",
"self",
... | THREADS Max numbers of threads to execute on target (defaults to 20)
COLLECTIONMETHOD Method used by BloodHound ingestor to collect data (defaults to 'Default')
CSVPATH (optional) Path where csv files will be written on target (defaults to C:\)
NEO4JURI (opt... | [
"THREADS",
"Max",
"numbers",
"of",
"threads",
"to",
"execute",
"on",
"target",
"(",
"defaults",
"to",
"20",
")",
"COLLECTIONMETHOD",
"Method",
"used",
"by",
"BloodHound",
"ingestor",
"to",
"collect",
"data",
"(",
"defaults",
"to",
"Default",
")",
"CSVPATH",
... | python | train | 48.361111 |
ybrs/pydisque | pydisque/client.py | https://github.com/ybrs/pydisque/blob/ea5ce1576b66398c1cce32cad0f15709b1ea8df8/pydisque/client.py#L333-L349 | def qstat(self, queue_name, return_dict=False):
"""
Return the status of the queue (currently unimplemented).
Future support / testing of QSTAT support in Disque
QSTAT <qname>
Return produced ... consumed ... idle ... sources [...] ctime ...
"""
rtn = self.exec... | [
"def",
"qstat",
"(",
"self",
",",
"queue_name",
",",
"return_dict",
"=",
"False",
")",
":",
"rtn",
"=",
"self",
".",
"execute_command",
"(",
"'QSTAT'",
",",
"queue_name",
")",
"if",
"return_dict",
":",
"grouped",
"=",
"self",
".",
"_grouper",
"(",
"rtn",... | Return the status of the queue (currently unimplemented).
Future support / testing of QSTAT support in Disque
QSTAT <qname>
Return produced ... consumed ... idle ... sources [...] ctime ... | [
"Return",
"the",
"status",
"of",
"the",
"queue",
"(",
"currently",
"unimplemented",
")",
"."
] | python | train | 28 |
common-workflow-language/cwltool | cwltool/main.py | https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/main.py#L394-L411 | def printdeps(obj, # type: Mapping[Text, Any]
document_loader, # type: Loader
stdout, # type: Union[TextIO, StreamWriter]
relative_deps, # type: bool
uri, # type: Text
basedir=None, # type: Text
... | [
"def",
"printdeps",
"(",
"obj",
",",
"# type: Mapping[Text, Any]",
"document_loader",
",",
"# type: Loader",
"stdout",
",",
"# type: Union[TextIO, StreamWriter]",
"relative_deps",
",",
"# type: bool",
"uri",
",",
"# type: Text",
"basedir",
"=",
"None",
",",
"# type: Text"... | Print a JSON representation of the dependencies of the CWL document. | [
"Print",
"a",
"JSON",
"representation",
"of",
"the",
"dependencies",
"of",
"the",
"CWL",
"document",
"."
] | python | train | 48.5 |
uploadcare/pyuploadcare | pyuploadcare/api_resources.py | https://github.com/uploadcare/pyuploadcare/blob/cefddc0306133a71e37b18e8700df5948ef49b37/pyuploadcare/api_resources.py#L150-L157 | def datetime_stored(self):
"""Returns file's store aware *datetime* in UTC format.
It might do API request once because it depends on ``info()``.
"""
if self.info().get('datetime_stored'):
return dateutil.parser.parse(self.info()['datetime_stored']) | [
"def",
"datetime_stored",
"(",
"self",
")",
":",
"if",
"self",
".",
"info",
"(",
")",
".",
"get",
"(",
"'datetime_stored'",
")",
":",
"return",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"self",
".",
"info",
"(",
")",
"[",
"'datetime_stored'",
"]",
... | Returns file's store aware *datetime* in UTC format.
It might do API request once because it depends on ``info()``. | [
"Returns",
"file",
"s",
"store",
"aware",
"*",
"datetime",
"*",
"in",
"UTC",
"format",
"."
] | python | test | 36 |
binux/pyspider | pyspider/scheduler/task_queue.py | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/task_queue.py#L227-L242 | def get(self):
'''Get a task from queue when bucket available'''
if self.bucket.get() < 1:
return None
now = time.time()
self.mutex.acquire()
try:
task = self.priority_queue.get_nowait()
self.bucket.desc()
except Queue.Empty:
... | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"bucket",
".",
"get",
"(",
")",
"<",
"1",
":",
"return",
"None",
"now",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"mutex",
".",
"acquire",
"(",
")",
"try",
":",
"task",
"=",
"self... | Get a task from queue when bucket available | [
"Get",
"a",
"task",
"from",
"queue",
"when",
"bucket",
"available"
] | python | train | 30.875 |
Lucretiel/autocommand | src/autocommand/autoparse.py | https://github.com/Lucretiel/autocommand/blob/bd3c58a210fdfcc943c729cc5579033add68d0b3/src/autocommand/autoparse.py#L232-L308 | def autoparse(
func=None, *,
description=None,
epilog=None,
add_nos=False,
parser=None):
'''
This decorator converts a function that takes normal arguments into a
function which takes a single optional argument, argv, parses it using an
argparse.ArgumentParser, an... | [
"def",
"autoparse",
"(",
"func",
"=",
"None",
",",
"*",
",",
"description",
"=",
"None",
",",
"epilog",
"=",
"None",
",",
"add_nos",
"=",
"False",
",",
"parser",
"=",
"None",
")",
":",
"# If @autoparse(...) is used instead of @autoparse",
"if",
"func",
"is",... | This decorator converts a function that takes normal arguments into a
function which takes a single optional argument, argv, parses it using an
argparse.ArgumentParser, and calls the underlying function with the parsed
arguments. If it is not given, sys.argv[1:] is used. This is so that the
function can... | [
"This",
"decorator",
"converts",
"a",
"function",
"that",
"takes",
"normal",
"arguments",
"into",
"a",
"function",
"which",
"takes",
"a",
"single",
"optional",
"argument",
"argv",
"parses",
"it",
"using",
"an",
"argparse",
".",
"ArgumentParser",
"and",
"calls",
... | python | train | 40.61039 |
michael-lazar/rtv | rtv/terminal.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/terminal.py#L863-L875 | def prompt_y_or_n(self, prompt):
"""
Wrapper around prompt_input for simple yes/no queries.
"""
ch = self.prompt_input(prompt, key=True)
if ch in (ord('Y'), ord('y')):
return True
elif ch in (ord('N'), ord('n'), None):
return False
else:
... | [
"def",
"prompt_y_or_n",
"(",
"self",
",",
"prompt",
")",
":",
"ch",
"=",
"self",
".",
"prompt_input",
"(",
"prompt",
",",
"key",
"=",
"True",
")",
"if",
"ch",
"in",
"(",
"ord",
"(",
"'Y'",
")",
",",
"ord",
"(",
"'y'",
")",
")",
":",
"return",
"... | Wrapper around prompt_input for simple yes/no queries. | [
"Wrapper",
"around",
"prompt_input",
"for",
"simple",
"yes",
"/",
"no",
"queries",
"."
] | python | train | 27.384615 |
MisterY/gnucash-portfolio | gnucash_portfolio/lib/settings.py | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/settings.py#L67-L74 | def database_path(self):
"""
Full database path. Includes the default location + the database filename.
"""
filename = self.database_filename
db_path = ":memory:" if filename == ":memory:" else (
path.abspath(path.join(__file__, "../..", "..", "data", filename)))
... | [
"def",
"database_path",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"database_filename",
"db_path",
"=",
"\":memory:\"",
"if",
"filename",
"==",
"\":memory:\"",
"else",
"(",
"path",
".",
"abspath",
"(",
"path",
".",
"join",
"(",
"__file__",
",",
"... | Full database path. Includes the default location + the database filename. | [
"Full",
"database",
"path",
".",
"Includes",
"the",
"default",
"location",
"+",
"the",
"database",
"filename",
"."
] | python | train | 41.375 |
Kozea/pygal | pygal/graph/graph.py | https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/graph.py#L360-L469 | def _legend(self):
"""Make the legend box"""
if not self.show_legend:
return
truncation = self.truncate_legend
if self.legend_at_bottom:
x = self.margin_box.left + self.spacing
y = (
self.margin_box.top + self.view.height + self._x_titl... | [
"def",
"_legend",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"show_legend",
":",
"return",
"truncation",
"=",
"self",
".",
"truncate_legend",
"if",
"self",
".",
"legend_at_bottom",
":",
"x",
"=",
"self",
".",
"margin_box",
".",
"left",
"+",
"self",... | Make the legend box | [
"Make",
"the",
"legend",
"box"
] | python | train | 34.618182 |
anchore/anchore | anchore/cli/logs.py | https://github.com/anchore/anchore/blob/8a4d5b9708e27856312d303aae3f04f3c72039d6/anchore/cli/logs.py#L105-L160 | def init_output_formatters(output_verbosity='normal', stderr=sys.stderr, logfile=None, debug_logfile=None):
"""
Initialize the CLI logging scheme.
:param output_verbosity: 'quiet','normal','verbose', or 'debug' controls the output to stdout and its format
:param stderr: stream for stderr output, defaul... | [
"def",
"init_output_formatters",
"(",
"output_verbosity",
"=",
"'normal'",
",",
"stderr",
"=",
"sys",
".",
"stderr",
",",
"logfile",
"=",
"None",
",",
"debug_logfile",
"=",
"None",
")",
":",
"if",
"output_verbosity",
"not",
"in",
"console_verbosity_options",
":"... | Initialize the CLI logging scheme.
:param output_verbosity: 'quiet','normal','verbose', or 'debug' controls the output to stdout and its format
:param stderr: stream for stderr output, default=stderr, pass a file path/string to have stderr in a file
:return: | [
"Initialize",
"the",
"CLI",
"logging",
"scheme",
"."
] | python | train | 45.017857 |
javipalanca/spade | spade/behaviour.py | https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L490-L498 | def add_transition(self, source: str, dest: str):
""" Adds a transition from one state to another.
Args:
source (str): the name of the state from where the transition starts
dest (str): the name of the state where the transition ends
"""
self._transitions[source].ap... | [
"def",
"add_transition",
"(",
"self",
",",
"source",
":",
"str",
",",
"dest",
":",
"str",
")",
":",
"self",
".",
"_transitions",
"[",
"source",
"]",
".",
"append",
"(",
"dest",
")"
] | Adds a transition from one state to another.
Args:
source (str): the name of the state from where the transition starts
dest (str): the name of the state where the transition ends | [
"Adds",
"a",
"transition",
"from",
"one",
"state",
"to",
"another",
"."
] | python | train | 35.777778 |
calmjs/nunja | src/nunja/engine.py | https://github.com/calmjs/nunja/blob/37ba114ca2239322718fd9994bb078c037682c33/src/nunja/engine.py#L71-L79 | def fetch_path(self, name):
"""
Fetch contents from the path retrieved via lookup_path.
No caching will be done.
"""
with codecs.open(self.lookup_path(name), encoding='utf-8') as fd:
return fd.read() | [
"def",
"fetch_path",
"(",
"self",
",",
"name",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"lookup_path",
"(",
"name",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fd",
":",
"return",
"fd",
".",
"read",
"(",
")"
] | Fetch contents from the path retrieved via lookup_path.
No caching will be done. | [
"Fetch",
"contents",
"from",
"the",
"path",
"retrieved",
"via",
"lookup_path",
"."
] | python | train | 27.222222 |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L858-L869 | def set_main_fan(self, main_fan):
"""Set the main fan config.
:param main_fan: Value to set the main fan
:type main_fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(main_fan) != int and main_fan not in range(0, 11):
raise InvalidInput(... | [
"def",
"set_main_fan",
"(",
"self",
",",
"main_fan",
")",
":",
"if",
"type",
"(",
"main_fan",
")",
"!=",
"int",
"and",
"main_fan",
"not",
"in",
"range",
"(",
"0",
",",
"11",
")",
":",
"raise",
"InvalidInput",
"(",
"\"Main fan value must be int between 0-10\"... | Set the main fan config.
:param main_fan: Value to set the main fan
:type main_fan: int [0-10]
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"main",
"fan",
"config",
"."
] | python | train | 35.75 |
codelv/enaml-web | examples/dataframe_viewer/app.py | https://github.com/codelv/enaml-web/blob/88f1131a7b3ba9e83467b4f44bc3bab6f0de7559/examples/dataframe_viewer/app.py#L69-L95 | def on_message(self, message):
""" When we get an event from js, lookup the node and invoke the
action on the enaml node.
"""
change = json.loads(message)
log.debug(f'Update from js: {change}')
# Lookup the node
ref = change.get('ref')
if not ref:
... | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"change",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"log",
".",
"debug",
"(",
"f'Update from js: {change}'",
")",
"# Lookup the node",
"ref",
"=",
"change",
".",
"get",
"(",
"'ref'",
")",
... | When we get an event from js, lookup the node and invoke the
action on the enaml node. | [
"When",
"we",
"get",
"an",
"event",
"from",
"js",
"lookup",
"the",
"node",
"and",
"invoke",
"the",
"action",
"on",
"the",
"enaml",
"node",
"."
] | python | test | 33.37037 |
latchset/custodia | src/custodia/message/kem.py | https://github.com/latchset/custodia/blob/5ad4cd7a2f40babc6b8b5d16215b7e27ca993b6d/src/custodia/message/kem.py#L133-L183 | def parse(self, msg, name):
"""Parses the message.
We check that the message is properly formatted.
:param msg: a json-encoded value containing a JWS or JWE+JWS token
:raises InvalidMessage: if the message cannot be parsed or validated
:returns: A verified payload
"""... | [
"def",
"parse",
"(",
"self",
",",
"msg",
",",
"name",
")",
":",
"try",
":",
"jtok",
"=",
"JWT",
"(",
"jwt",
"=",
"msg",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"InvalidMessage",
"(",
"'Failed to parse message: %s'",
"%",
"str",
"(",
"e",
... | Parses the message.
We check that the message is properly formatted.
:param msg: a json-encoded value containing a JWS or JWE+JWS token
:raises InvalidMessage: if the message cannot be parsed or validated
:returns: A verified payload | [
"Parses",
"the",
"message",
"."
] | python | train | 36.196078 |
inveniosoftware/invenio-collections | invenio_collections/views.py | https://github.com/inveniosoftware/invenio-collections/blob/f3adca45c6d00a4dbf1f48fd501e8a68fe347f2f/invenio_collections/views.py#L44-L63 | def collection(name=None):
"""Render the collection page.
It renders it either with a collection specific template (aka
collection_{collection_name}.html) or with the default collection
template (collection.html).
"""
if name is None:
collection = Collection.query.get_or_404(1)
else... | [
"def",
"collection",
"(",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"collection",
"=",
"Collection",
".",
"query",
".",
"get_or_404",
"(",
"1",
")",
"else",
":",
"collection",
"=",
"Collection",
".",
"query",
".",
"filter",
"(",
... | Render the collection page.
It renders it either with a collection specific template (aka
collection_{collection_name}.html) or with the default collection
template (collection.html). | [
"Render",
"the",
"collection",
"page",
"."
] | python | train | 38.75 |
saltstack/salt | salt/modules/win_system.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L1199-L1233 | def set_system_date(newdate):
'''
Set the Windows system date. Use <mm-dd-yy> format for the date.
Args:
newdate (str):
The date to set. Can be any of the following formats
- YYYY-MM-DD
- MM-DD-YYYY
- MM-DD-YY
- MM/DD/YYYY
- M... | [
"def",
"set_system_date",
"(",
"newdate",
")",
":",
"fmts",
"=",
"[",
"'%Y-%m-%d'",
",",
"'%m-%d-%Y'",
",",
"'%m-%d-%y'",
",",
"'%m/%d/%Y'",
",",
"'%m/%d/%y'",
",",
"'%Y/%m/%d'",
"]",
"# Get date/time object from newdate",
"dt_obj",
"=",
"_try_parse_datetime",
"(",
... | Set the Windows system date. Use <mm-dd-yy> format for the date.
Args:
newdate (str):
The date to set. Can be any of the following formats
- YYYY-MM-DD
- MM-DD-YYYY
- MM-DD-YY
- MM/DD/YYYY
- MM/DD/YY
- YYYY/MM/DD
Retu... | [
"Set",
"the",
"Windows",
"system",
"date",
".",
"Use",
"<mm",
"-",
"dd",
"-",
"yy",
">",
"format",
"for",
"the",
"date",
"."
] | python | train | 26.285714 |
nilp0inter/cpe | cpe/comp/cpecomp2_3_uri_edpacked.py | https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/comp/cpecomp2_3_uri_edpacked.py#L91-L103 | def set_value(self, comp_str):
"""
Set the value of component.
:param string comp_str: value of component
:returns: None
:exception: ValueError - incorrect value of component
"""
self._is_negated = False
self._encoded_value = comp_str
self._stand... | [
"def",
"set_value",
"(",
"self",
",",
"comp_str",
")",
":",
"self",
".",
"_is_negated",
"=",
"False",
"self",
".",
"_encoded_value",
"=",
"comp_str",
"self",
".",
"_standard_value",
"=",
"super",
"(",
"CPEComponent2_3_URI_edpacked",
",",
"self",
")",
".",
"_... | Set the value of component.
:param string comp_str: value of component
:returns: None
:exception: ValueError - incorrect value of component | [
"Set",
"the",
"value",
"of",
"component",
"."
] | python | train | 29.538462 |
goerz/clusterjob | clusterjob/__init__.py | https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/__init__.py#L1032-L1038 | def successful(self):
"""Return True if the job finished with a COMPLETED status, False if it
finished with a CANCELLED or FAILED status. Raise an `AssertionError`
if the job has not completed"""
status = self.status
assert status >= COMPLETED, "status is %s" % status
ret... | [
"def",
"successful",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"status",
"assert",
"status",
">=",
"COMPLETED",
",",
"\"status is %s\"",
"%",
"status",
"return",
"(",
"self",
".",
"status",
"==",
"COMPLETED",
")"
] | Return True if the job finished with a COMPLETED status, False if it
finished with a CANCELLED or FAILED status. Raise an `AssertionError`
if the job has not completed | [
"Return",
"True",
"if",
"the",
"job",
"finished",
"with",
"a",
"COMPLETED",
"status",
"False",
"if",
"it",
"finished",
"with",
"a",
"CANCELLED",
"or",
"FAILED",
"status",
".",
"Raise",
"an",
"AssertionError",
"if",
"the",
"job",
"has",
"not",
"completed"
] | python | train | 49.142857 |
lionheart/django-pyodbc | django_pyodbc/operations.py | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L431-L444 | def adapt_datetimefield_value(self, value):
"""
Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.
"""
if value is None:
return None
if self.connection._DJANGO_VERSION >= 14 and settings.USE_TZ:... | [
"def",
"adapt_datetimefield_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"connection",
".",
"_DJANGO_VERSION",
">=",
"14",
"and",
"settings",
".",
"USE_TZ",
":",
"if",
"timezone",
".",
... | Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns. | [
"Transform",
"a",
"datetime",
"value",
"to",
"an",
"object",
"compatible",
"with",
"what",
"is",
"expected",
"by",
"the",
"backend",
"driver",
"for",
"datetime",
"columns",
"."
] | python | train | 43 |
fedora-python/pyp2rpm | pyp2rpm/archive.py | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/archive.py#L170-L181 | def extract_file(self, name, full_path=False, directory="."):
"""Extract a member from the archive to the specified working directory.
Behaviour of name and pull_path is the same as in function
get_content_of_file.
"""
if self.handle:
for member in self.handle.getmemb... | [
"def",
"extract_file",
"(",
"self",
",",
"name",
",",
"full_path",
"=",
"False",
",",
"directory",
"=",
"\".\"",
")",
":",
"if",
"self",
".",
"handle",
":",
"for",
"member",
"in",
"self",
".",
"handle",
".",
"getmembers",
"(",
")",
":",
"if",
"(",
... | Extract a member from the archive to the specified working directory.
Behaviour of name and pull_path is the same as in function
get_content_of_file. | [
"Extract",
"a",
"member",
"from",
"the",
"archive",
"to",
"the",
"specified",
"working",
"directory",
".",
"Behaviour",
"of",
"name",
"and",
"pull_path",
"is",
"the",
"same",
"as",
"in",
"function",
"get_content_of_file",
"."
] | python | train | 50 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/scene/widgets/console.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/widgets/console.py#L319-L338 | def _do_pending_writes(self):
"""Do any pending text writes"""
for text, wrap in self._pending_writes:
# truncate in case of *really* long messages
text = text[-self._n_cols*self._n_rows:]
text = text.split('\n')
text = [t if len(t) > 0 else '' for t in te... | [
"def",
"_do_pending_writes",
"(",
"self",
")",
":",
"for",
"text",
",",
"wrap",
"in",
"self",
".",
"_pending_writes",
":",
"# truncate in case of *really* long messages",
"text",
"=",
"text",
"[",
"-",
"self",
".",
"_n_cols",
"*",
"self",
".",
"_n_rows",
":",
... | Do any pending text writes | [
"Do",
"any",
"pending",
"text",
"writes"
] | python | train | 49.5 |
OnroerendErfgoed/crabpy_pyramid | crabpy_pyramid/renderers/capakey.py | https://github.com/OnroerendErfgoed/crabpy_pyramid/blob/b727ea55838d71575db96e987b536a0bac9f6a7a/crabpy_pyramid/renderers/capakey.py#L80-L94 | def item_afdeling_adapter(obj, request):
"""
Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Afdeling` to json.
"""
return {
'id': obj.id,
'naam': obj.naam,
'gemeente': {
'id': obj.gemeente.id,
'naam': obj.gemeente.naam
},
... | [
"def",
"item_afdeling_adapter",
"(",
"obj",
",",
"request",
")",
":",
"return",
"{",
"'id'",
":",
"obj",
".",
"id",
",",
"'naam'",
":",
"obj",
".",
"naam",
",",
"'gemeente'",
":",
"{",
"'id'",
":",
"obj",
".",
"gemeente",
".",
"id",
",",
"'naam'",
... | Adapter for rendering an object of
:class: `crabpy.gateway.capakey.Afdeling` to json. | [
"Adapter",
"for",
"rendering",
"an",
"object",
"of",
":",
"class",
":",
"crabpy",
".",
"gateway",
".",
"capakey",
".",
"Afdeling",
"to",
"json",
"."
] | python | train | 25.6 |
tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L2448-L2537 | def dot_product_unmasked_attention_local_2d_tpu(
q, k, v, bias, max_relative_position=None, query_shape=(8, 8),
dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=False,
dropout_broadcast_dims=None):
"""Calculate unmasked dot-product local self-attention 2d on tpu.
Args:
q: a Tensor... | [
"def",
"dot_product_unmasked_attention_local_2d_tpu",
"(",
"q",
",",
"k",
",",
"v",
",",
"bias",
",",
"max_relative_position",
"=",
"None",
",",
"query_shape",
"=",
"(",
"8",
",",
"8",
")",
",",
"dropout_rate",
"=",
"0.0",
",",
"image_shapes",
"=",
"None",
... | Calculate unmasked dot-product local self-attention 2d on tpu.
Args:
q: a Tensor with shape [batch, heads, height, width, depth].
k: a Tensor with shape [batch, heads, height, width, depth].
v: a Tensor with shape [batch, heads, height, width, depth].
bias: bias Tensor.
max_relative_position: an ... | [
"Calculate",
"unmasked",
"dot",
"-",
"product",
"local",
"self",
"-",
"attention",
"2d",
"on",
"tpu",
"."
] | python | train | 46.566667 |
sorgerlab/indra | indra/assemblers/graph/assembler.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/graph/assembler.py#L191-L212 | def _add_node(self, agent):
"""Add an Agent as a node to the graph."""
if agent is None:
return
node_label = _get_node_label(agent)
if isinstance(agent, Agent) and agent.bound_conditions:
bound_agents = [bc.agent for bc in agent.bound_conditions if
... | [
"def",
"_add_node",
"(",
"self",
",",
"agent",
")",
":",
"if",
"agent",
"is",
"None",
":",
"return",
"node_label",
"=",
"_get_node_label",
"(",
"agent",
")",
"if",
"isinstance",
"(",
"agent",
",",
"Agent",
")",
"and",
"agent",
".",
"bound_conditions",
":... | Add an Agent as a node to the graph. | [
"Add",
"an",
"Agent",
"as",
"a",
"node",
"to",
"the",
"graph",
"."
] | python | train | 43.636364 |
pywbem/pywbem | pywbem/tupleparse.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L757-L783 | def parse_localnamespacepath(self, tup_tree):
"""
Parse a LOCALNAMESPACEPATH element and return the namespace it
represents as a unicode string.
The namespace is formed by joining the namespace components (one from
each NAMESPACE child element) with a slash (e.g. to "root/cimv2"... | [
"def",
"parse_localnamespacepath",
"(",
"self",
",",
"tup_tree",
")",
":",
"self",
".",
"check_node",
"(",
"tup_tree",
",",
"'LOCALNAMESPACEPATH'",
",",
"(",
")",
",",
"(",
")",
",",
"(",
"'NAMESPACE'",
",",
")",
")",
"if",
"not",
"kids",
"(",
"tup_tree"... | Parse a LOCALNAMESPACEPATH element and return the namespace it
represents as a unicode string.
The namespace is formed by joining the namespace components (one from
each NAMESPACE child element) with a slash (e.g. to "root/cimv2").
::
<!ELEMENT LOCALNAMESPACEPATH (NAMESP... | [
"Parse",
"a",
"LOCALNAMESPACEPATH",
"element",
"and",
"return",
"the",
"namespace",
"it",
"represents",
"as",
"a",
"unicode",
"string",
"."
] | python | train | 36.740741 |
inspirehep/refextract | refextract/references/record.py | https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/record.py#L71-L161 | def build_reference_fields(citation_elements, line_marker, raw_ref,
reference_format):
"""Create the final representation of the reference information.
@param citation_elements: (list) an ordered list of dictionary elements,
with each element correspondi... | [
"def",
"build_reference_fields",
"(",
"citation_elements",
",",
"line_marker",
",",
"raw_ref",
",",
"reference_format",
")",
":",
"# Begin the datafield element",
"current_field",
"=",
"create_reference_field",
"(",
"line_marker",
")",
"current_field",
"[",
"'raw_ref'",
"... | Create the final representation of the reference information.
@param citation_elements: (list) an ordered list of dictionary elements,
with each element corresponding to a found
piece of information from a reference line.
@param line_marker: (string) ... | [
"Create",
"the",
"final",
"representation",
"of",
"the",
"reference",
"information",
"."
] | python | train | 39.571429 |
PrefPy/prefpy | prefpy/profile.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/profile.py#L121-L161 | def getWmg(self, normalize = False):
"""
Generate a weighted majority graph that represents the whole profile. The function will
return a two-dimensional dictionary that associates integer representations of each pair of
candidates, cand1 and cand2, with the number of times cand1 is rank... | [
"def",
"getWmg",
"(",
"self",
",",
"normalize",
"=",
"False",
")",
":",
"# Initialize a new dictionary for our final weighted majority graph.",
"wmgMap",
"=",
"dict",
"(",
")",
"for",
"cand",
"in",
"self",
".",
"candMap",
".",
"keys",
"(",
")",
":",
"wmgMap",
... | Generate a weighted majority graph that represents the whole profile. The function will
return a two-dimensional dictionary that associates integer representations of each pair of
candidates, cand1 and cand2, with the number of times cand1 is ranked above cand2 minus the
number of times cand2 is... | [
"Generate",
"a",
"weighted",
"majority",
"graph",
"that",
"represents",
"the",
"whole",
"profile",
".",
"The",
"function",
"will",
"return",
"a",
"two",
"-",
"dimensional",
"dictionary",
"that",
"associates",
"integer",
"representations",
"of",
"each",
"pair",
"... | python | train | 52.04878 |
bcbio/bcbio-nextgen | bcbio/structural/purple.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purple.py#L43-L53 | def _get_jvm_opts(out_file, data):
"""Retrieve Java options, adjusting memory for available cores.
"""
resources = config_utils.get_resources("purple", data["config"])
jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx3500m"])
jvm_opts = config_utils.adjust_opts(jvm_opts, {"algorithm": {"memory... | [
"def",
"_get_jvm_opts",
"(",
"out_file",
",",
"data",
")",
":",
"resources",
"=",
"config_utils",
".",
"get_resources",
"(",
"\"purple\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
"jvm_opts",
"=",
"resources",
".",
"get",
"(",
"\"jvm_opts\"",
",",
"[",
"\... | Retrieve Java options, adjusting memory for available cores. | [
"Retrieve",
"Java",
"options",
"adjusting",
"memory",
"for",
"available",
"cores",
"."
] | python | train | 62.636364 |
cloudtools/stacker | stacker/blueprints/raw.py | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/blueprints/raw.py#L194-L215 | def rendered(self):
"""Return (generating first if needed) rendered template."""
if not self._rendered:
template_path = get_template_path(self.raw_template_path)
if template_path:
with open(template_path, 'r') as template:
if len(os.path.splite... | [
"def",
"rendered",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_rendered",
":",
"template_path",
"=",
"get_template_path",
"(",
"self",
".",
"raw_template_path",
")",
"if",
"template_path",
":",
"with",
"open",
"(",
"template_path",
",",
"'r'",
")",
... | Return (generating first if needed) rendered template. | [
"Return",
"(",
"generating",
"first",
"if",
"needed",
")",
"rendered",
"template",
"."
] | python | train | 44.181818 |
twilio/twilio-python | twilio/rest/api/v2010/account/message/media.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/message/media.py#L149-L163 | def get(self, sid):
"""
Constructs a MediaContext
:param sid: The unique string that identifies this resource
:returns: twilio.rest.api.v2010.account.message.media.MediaContext
:rtype: twilio.rest.api.v2010.account.message.media.MediaContext
"""
return MediaCont... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"MediaContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"message_sid",
"=",
"self",
".",
"_solution",
"[",
"'message_sid'",
... | Constructs a MediaContext
:param sid: The unique string that identifies this resource
:returns: twilio.rest.api.v2010.account.message.media.MediaContext
:rtype: twilio.rest.api.v2010.account.message.media.MediaContext | [
"Constructs",
"a",
"MediaContext"
] | python | train | 31.866667 |
titusjan/argos | argos/collect/collector.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/collect/collector.py#L193-L204 | def _setAxesNames(self, axisNames):
""" Sets the axesnames, combobox lables and updates the headers. Removes old values first.
The comboLables is the axes name + '-axis'
"""
for col, _ in enumerate(self._fullAxisNames, self.COL_FIRST_COMBO):
self._setHeaderLabel(col, '')
... | [
"def",
"_setAxesNames",
"(",
"self",
",",
"axisNames",
")",
":",
"for",
"col",
",",
"_",
"in",
"enumerate",
"(",
"self",
".",
"_fullAxisNames",
",",
"self",
".",
"COL_FIRST_COMBO",
")",
":",
"self",
".",
"_setHeaderLabel",
"(",
"col",
",",
"''",
")",
"... | Sets the axesnames, combobox lables and updates the headers. Removes old values first.
The comboLables is the axes name + '-axis' | [
"Sets",
"the",
"axesnames",
"combobox",
"lables",
"and",
"updates",
"the",
"headers",
".",
"Removes",
"old",
"values",
"first",
".",
"The",
"comboLables",
"is",
"the",
"axes",
"name",
"+",
"-",
"axis"
] | python | train | 47.416667 |
inveniosoftware/invenio-records | invenio_records/admin.py | https://github.com/inveniosoftware/invenio-records/blob/b0b1481d04012e45cb71b5ae4019e91dde88d1e2/invenio_records/admin.py#L49-L63 | def delete_model(self, model):
"""Delete a record."""
try:
if model.json is None:
return True
record = Record(model.json, model=model)
record.delete()
db.session.commit()
except SQLAlchemyError as e:
if not self.handle_v... | [
"def",
"delete_model",
"(",
"self",
",",
"model",
")",
":",
"try",
":",
"if",
"model",
".",
"json",
"is",
"None",
":",
"return",
"True",
"record",
"=",
"Record",
"(",
"model",
".",
"json",
",",
"model",
"=",
"model",
")",
"record",
".",
"delete",
"... | Delete a record. | [
"Delete",
"a",
"record",
"."
] | python | train | 34.6 |
PmagPy/PmagPy | programs/demag_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L4497-L4630 | def get_data_info(self):
"""
imports er tables and places data into Data_info data structure
outlined bellow:
Data_info - {er_samples: {er_samples.txt info}
er_sites: {er_sites.txt info}
er_locations: {er_locations.txt info}
... | [
"def",
"get_data_info",
"(",
"self",
")",
":",
"Data_info",
"=",
"{",
"}",
"data_er_samples",
"=",
"{",
"}",
"data_er_sites",
"=",
"{",
"}",
"data_er_locations",
"=",
"{",
"}",
"data_er_ages",
"=",
"{",
"}",
"if",
"self",
".",
"data_model",
"==",
"3.0",
... | imports er tables and places data into Data_info data structure
outlined bellow:
Data_info - {er_samples: {er_samples.txt info}
er_sites: {er_sites.txt info}
er_locations: {er_locations.txt info}
er_ages: {er_ages.txt info}} | [
"imports",
"er",
"tables",
"and",
"places",
"data",
"into",
"Data_info",
"data",
"structure",
"outlined",
"bellow",
":",
"Data_info",
"-",
"{",
"er_samples",
":",
"{",
"er_samples",
".",
"txt",
"info",
"}",
"er_sites",
":",
"{",
"er_sites",
".",
"txt",
"in... | python | train | 46.298507 |
pyroscope/pyrobase | pavement.py | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/pavement.py#L167-L197 | def release():
"check release before upload to PyPI"
sh("paver bdist_wheel")
wheels = path("dist").files("*.whl")
if not wheels:
error("\n*** ERROR: No release wheel was built!")
sys.exit(1)
if any(".dev" in i for i in wheels):
error("\n*** ERROR: You're still using a 'dev' v... | [
"def",
"release",
"(",
")",
":",
"sh",
"(",
"\"paver bdist_wheel\"",
")",
"wheels",
"=",
"path",
"(",
"\"dist\"",
")",
".",
"files",
"(",
"\"*.whl\"",
")",
"if",
"not",
"wheels",
":",
"error",
"(",
"\"\\n*** ERROR: No release wheel was built!\"",
")",
"sys",
... | check release before upload to PyPI | [
"check",
"release",
"before",
"upload",
"to",
"PyPI"
] | python | train | 40.709677 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/util/bottle3.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/util/bottle3.py#L1239-L1264 | def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080,
interval=1, reloader=False, **kargs):
""" Runs bottle as a web server. """
app = app if app else default_app()
quiet = bool(kargs.get('quiet', False))
# Instantiate server, if it is a class instead of an instance
if isinsta... | [
"def",
"run",
"(",
"app",
"=",
"None",
",",
"server",
"=",
"WSGIRefServer",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8080",
",",
"interval",
"=",
"1",
",",
"reloader",
"=",
"False",
",",
"*",
"*",
"kargs",
")",
":",
"app",
"=",
"app",
... | Runs bottle as a web server. | [
"Runs",
"bottle",
"as",
"a",
"web",
"server",
"."
] | python | train | 44.461538 |
xolox/python-qpass | qpass/__init__.py | https://github.com/xolox/python-qpass/blob/43ce447b0904ff42a54b8f1dd4d2479f950f258f/qpass/__init__.py#L244-L272 | def context(self):
"""
An execution context created using :mod:`executor.contexts`.
The value of :attr:`context` defaults to a
:class:`~executor.contexts.LocalContext` object with the following
characteristics:
- The working directory of the execution context is set to ... | [
"def",
"context",
"(",
"self",
")",
":",
"# Make sure the directory exists.",
"self",
".",
"ensure_directory_exists",
"(",
")",
"# Prepare the environment variables.",
"environment",
"=",
"{",
"DIRECTORY_VARIABLE",
":",
"self",
".",
"directory",
"}",
"try",
":",
"# Tr... | An execution context created using :mod:`executor.contexts`.
The value of :attr:`context` defaults to a
:class:`~executor.contexts.LocalContext` object with the following
characteristics:
- The working directory of the execution context is set to the
value of :attr:`directory... | [
"An",
"execution",
"context",
"created",
"using",
":",
"mod",
":",
"executor",
".",
"contexts",
"."
] | python | train | 42.344828 |
jaredLunde/redis_structures | redis_structures/__init__.py | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L248-L254 | def _dumps(self, obj):
""" If :prop:serialized is True, @obj will be serialized
using :prop:serializer
"""
if not self.serialized:
return obj
return self.serializer.dumps(obj) | [
"def",
"_dumps",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"self",
".",
"serialized",
":",
"return",
"obj",
"return",
"self",
".",
"serializer",
".",
"dumps",
"(",
"obj",
")"
] | If :prop:serialized is True, @obj will be serialized
using :prop:serializer | [
"If",
":",
"prop",
":",
"serialized",
"is",
"True"
] | python | train | 32.142857 |
Unidata/MetPy | metpy/plots/skewt.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/plots/skewt.py#L59-L62 | def gridOn(self): # noqa: N802
"""Control whether the gridline is drawn for this tick."""
return (self._gridOn and (self._has_default_loc()
or transforms.interval_contains(self.get_view_interval(), self.get_loc()))) | [
"def",
"gridOn",
"(",
"self",
")",
":",
"# noqa: N802",
"return",
"(",
"self",
".",
"_gridOn",
"and",
"(",
"self",
".",
"_has_default_loc",
"(",
")",
"or",
"transforms",
".",
"interval_contains",
"(",
"self",
".",
"get_view_interval",
"(",
")",
",",
"self"... | Control whether the gridline is drawn for this tick. | [
"Control",
"whether",
"the",
"gridline",
"is",
"drawn",
"for",
"this",
"tick",
"."
] | python | train | 61.25 |
NASA-AMMOS/AIT-Core | ait/core/dtype.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dtype.py#L362-L382 | def decode(self, bytes, index=None, raw=False):
"""decode(bytes[[, index], raw=False]) -> value1, ..., valueN
Decodes the given sequence of bytes according to this Array's
element type.
If the optional `index` parameter is an integer or slice, then
only the element(s) at the sp... | [
"def",
"decode",
"(",
"self",
",",
"bytes",
",",
"index",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"slice",
"(",
"0",
",",
"self",
".",
"nelems",
")",
"if",
"type",
"(",
"index",
")",
"is"... | decode(bytes[[, index], raw=False]) -> value1, ..., valueN
Decodes the given sequence of bytes according to this Array's
element type.
If the optional `index` parameter is an integer or slice, then
only the element(s) at the specified position(s) will be
decoded and returned. | [
"decode",
"(",
"bytes",
"[[",
"index",
"]",
"raw",
"=",
"False",
"]",
")",
"-",
">",
"value1",
"...",
"valueN"
] | python | train | 36.190476 |
IzunaDevs/SnekChek | snekchek/config_gen.py | https://github.com/IzunaDevs/SnekChek/blob/fdb01bdf1ec8e79d9aae2a11d96bfb27e53a97a9/snekchek/config_gen.py#L87-L94 | def ask_bool(question: str, default: bool = True) -> bool:
"""Asks a question yes no style"""
default_q = "Y/n" if default else "y/N"
answer = input("{0} [{1}]: ".format(question, default_q))
lower = answer.lower()
if not lower:
return default
return lower == "y" | [
"def",
"ask_bool",
"(",
"question",
":",
"str",
",",
"default",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"default_q",
"=",
"\"Y/n\"",
"if",
"default",
"else",
"\"y/N\"",
"answer",
"=",
"input",
"(",
"\"{0} [{1}]: \"",
".",
"format",
"(",
"questi... | Asks a question yes no style | [
"Asks",
"a",
"question",
"yes",
"no",
"style"
] | python | train | 36 |
tgsmith61591/pmdarima | pmdarima/utils/array.py | https://github.com/tgsmith61591/pmdarima/blob/a133de78ba5bd68da9785b061f519ba28cd514cc/pmdarima/utils/array.py#L66-L135 | def c(*args):
r"""Imitates the ``c`` function from R.
Since this whole library is aimed at re-creating in
Python what R has already done so well, the ``c`` function was created to
wrap ``numpy.concatenate`` and mimic the R functionality. Similar to R,
this works with scalars, iterables, and any mix... | [
"def",
"c",
"(",
"*",
"args",
")",
":",
"# R returns NULL for this",
"if",
"not",
"args",
":",
"return",
"None",
"# just an array of len 1",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"element",
"=",
"args",
"[",
"0",
"]",
"# if it's iterable, make it an... | r"""Imitates the ``c`` function from R.
Since this whole library is aimed at re-creating in
Python what R has already done so well, the ``c`` function was created to
wrap ``numpy.concatenate`` and mimic the R functionality. Similar to R,
this works with scalars, iterables, and any mix therein.
Not... | [
"r",
"Imitates",
"the",
"c",
"function",
"from",
"R",
"."
] | python | train | 34.4 |
Alignak-monitoring/alignak | alignak/objects/realm.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/realm.py#L474-L519 | def get_links_for_a_scheduler(self, pollers, reactionners, brokers):
"""Get a configuration dictionary with pollers, reactionners and brokers links
for a scheduler
:return: dict containing pollers, reactionners and brokers links (key is satellite id)
:rtype: dict
"""
# ... | [
"def",
"get_links_for_a_scheduler",
"(",
"self",
",",
"pollers",
",",
"reactionners",
",",
"brokers",
")",
":",
"# Create void satellite links",
"cfg",
"=",
"{",
"'pollers'",
":",
"{",
"}",
",",
"'reactionners'",
":",
"{",
"}",
",",
"'brokers'",
":",
"{",
"}... | Get a configuration dictionary with pollers, reactionners and brokers links
for a scheduler
:return: dict containing pollers, reactionners and brokers links (key is satellite id)
:rtype: dict | [
"Get",
"a",
"configuration",
"dictionary",
"with",
"pollers",
"reactionners",
"and",
"brokers",
"links",
"for",
"a",
"scheduler"
] | python | train | 46.195652 |
sosy-lab/benchexec | benchexec/runexecutor.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/runexecutor.py#L452-L458 | def _listdir(self, path):
"""Return the list of files in a directory, assuming that our user can read it."""
if self._user is None:
return os.listdir(path)
else:
args = self._build_cmdline(['/bin/ls', '-1A', path])
return subprocess.check_output(args, stderr=D... | [
"def",
"_listdir",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"_user",
"is",
"None",
":",
"return",
"os",
".",
"listdir",
"(",
"path",
")",
"else",
":",
"args",
"=",
"self",
".",
"_build_cmdline",
"(",
"[",
"'/bin/ls'",
",",
"'-1A'",
",... | Return the list of files in a directory, assuming that our user can read it. | [
"Return",
"the",
"list",
"of",
"files",
"in",
"a",
"directory",
"assuming",
"that",
"our",
"user",
"can",
"read",
"it",
"."
] | python | train | 52.285714 |
robdmc/crontabs | crontabs/processes.py | https://github.com/robdmc/crontabs/blob/3a347f9309eb1b4c7c222363ede338a158f5072c/crontabs/processes.py#L85-L107 | def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs): # pragma: no cover
"""
Wraps a target with queues replacing stdout and stderr
"""
import sys
sys.stdout = IOQueue(q_stdout)
sys.stderr = IOQueue(q_stderr)
try:
target(*args, **kwargs)
except... | [
"def",
"wrapped_target",
"(",
"target",
",",
"q_stdout",
",",
"q_stderr",
",",
"q_error",
",",
"robust",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover",
"import",
"sys",
"sys",
".",
"stdout",
"=",
"IOQueue",
"(",
... | Wraps a target with queues replacing stdout and stderr | [
"Wraps",
"a",
"target",
"with",
"queues",
"replacing",
"stdout",
"and",
"stderr"
] | python | train | 24.173913 |
hz-inova/run_jnb | run_jnb/util.py | https://github.com/hz-inova/run_jnb/blob/55e63de33b0643161948864d2c1ec998f02815bf/run_jnb/util.py#L239-L266 | def group_dict_by_value(d: dict) -> dict:
"""
Group a dictionary by values.
Parameters
----------
d : dict
Input dictionary
Returns
-------
dict
Output dictionary. The keys are the values of the initial dictionary
and the values ae given by a list of keys corre... | [
"def",
"group_dict_by_value",
"(",
"d",
":",
"dict",
")",
"->",
"dict",
":",
"d_out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"v",
"in",
"d_out",
":",
"d_out",
"[",
"v",
"]",
".",
"append",
"(",
"k",... | Group a dictionary by values.
Parameters
----------
d : dict
Input dictionary
Returns
-------
dict
Output dictionary. The keys are the values of the initial dictionary
and the values ae given by a list of keys corresponding to the value.
>>> group_dict_by_value({2... | [
"Group",
"a",
"dictionary",
"by",
"values",
"."
] | python | train | 23.321429 |
MisterY/price-database | pricedb/app.py | https://github.com/MisterY/price-database/blob/b4fd366b7763891c690fe3000b8840e656da023e/pricedb/app.py#L152-L172 | def get_prices(self, date: str, currency: str) -> List[PriceModel]:
""" Fetches all the prices for the given arguments """
from .repositories import PriceRepository
session = self.session
repo = PriceRepository(session)
query = repo.query
if date:
query = que... | [
"def",
"get_prices",
"(",
"self",
",",
"date",
":",
"str",
",",
"currency",
":",
"str",
")",
"->",
"List",
"[",
"PriceModel",
"]",
":",
"from",
".",
"repositories",
"import",
"PriceRepository",
"session",
"=",
"self",
".",
"session",
"repo",
"=",
"PriceR... | Fetches all the prices for the given arguments | [
"Fetches",
"all",
"the",
"prices",
"for",
"the",
"given",
"arguments"
] | python | test | 35.761905 |
Azure/azure-cli-extensions | src/interactive/azext_interactive/azclishell/frequency_heuristic.py | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/frequency_heuristic.py#L41-L50 | def frequency_measurement(shell_ctx):
""" measures how many times a user has used this program in the last calendar week """
freq = update_frequency(shell_ctx)
count = 0
base = datetime.datetime.utcnow()
date_list = [base - datetime.timedelta(days=x) for x in range(0, DAYS_AGO)]
for day in date_... | [
"def",
"frequency_measurement",
"(",
"shell_ctx",
")",
":",
"freq",
"=",
"update_frequency",
"(",
"shell_ctx",
")",
"count",
"=",
"0",
"base",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"date_list",
"=",
"[",
"base",
"-",
"datetime",
".",
... | measures how many times a user has used this program in the last calendar week | [
"measures",
"how",
"many",
"times",
"a",
"user",
"has",
"used",
"this",
"program",
"in",
"the",
"last",
"calendar",
"week"
] | python | train | 39.6 |
KelSolaar/Umbra | umbra/ui/widgets/codeEditor_QPlainTextEdit.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/codeEditor_QPlainTextEdit.py#L986-L1006 | def set_highlighter(self, highlighter):
"""
Sets given highlighter as the current document highlighter.
:param highlighter: Highlighter.
:type highlighter: QSyntaxHighlighter
:return: Method success.
:rtype: bool
"""
if not issubclass(highlighter.__class... | [
"def",
"set_highlighter",
"(",
"self",
",",
"highlighter",
")",
":",
"if",
"not",
"issubclass",
"(",
"highlighter",
".",
"__class__",
",",
"QSyntaxHighlighter",
")",
":",
"raise",
"foundations",
".",
"exceptions",
".",
"ProgrammingError",
"(",
"\"{0} | '{1}' is no... | Sets given highlighter as the current document highlighter.
:param highlighter: Highlighter.
:type highlighter: QSyntaxHighlighter
:return: Method success.
:rtype: bool | [
"Sets",
"given",
"highlighter",
"as",
"the",
"current",
"document",
"highlighter",
"."
] | python | train | 33.571429 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/f2n.py | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/f2n.py#L670-L673 | def loadlabelfont(self):
"""Auxiliary method to load font if not yet done."""
if self.labelfont == None:
self.labelfont = imft.load_path(os.path.join(fontsdir, "courR10.pil")) | [
"def",
"loadlabelfont",
"(",
"self",
")",
":",
"if",
"self",
".",
"labelfont",
"==",
"None",
":",
"self",
".",
"labelfont",
"=",
"imft",
".",
"load_path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fontsdir",
",",
"\"courR10.pil\"",
")",
")"
] | Auxiliary method to load font if not yet done. | [
"Auxiliary",
"method",
"to",
"load",
"font",
"if",
"not",
"yet",
"done",
"."
] | python | train | 50 |
jbarlow83/OCRmyPDF | src/ocrmypdf/exec/tesseract.py | https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/exec/tesseract.py#L70-L85 | def has_textonly_pdf():
"""Does Tesseract have textonly_pdf capability?
Available in v4.00.00alpha since January 2017. Best to
parse the parameter list
"""
args_tess = ['tesseract', '--print-parameters', 'pdf']
params = ''
try:
params = check_output(args_tess, universal_newlines=Tru... | [
"def",
"has_textonly_pdf",
"(",
")",
":",
"args_tess",
"=",
"[",
"'tesseract'",
",",
"'--print-parameters'",
",",
"'pdf'",
"]",
"params",
"=",
"''",
"try",
":",
"params",
"=",
"check_output",
"(",
"args_tess",
",",
"universal_newlines",
"=",
"True",
",",
"st... | Does Tesseract have textonly_pdf capability?
Available in v4.00.00alpha since January 2017. Best to
parse the parameter list | [
"Does",
"Tesseract",
"have",
"textonly_pdf",
"capability?"
] | python | train | 34.375 |
RobersonLab/motif_scraper | motif_scraper/__init__.py | https://github.com/RobersonLab/motif_scraper/blob/382dcb5932d9750282906c356ca35e802bd68bd0/motif_scraper/__init__.py#L147-L219 | def fasta_motif_scan( fasta_fname, input_tuples, regex_ready=False, allow_overlaps=True, file_buffer=False, molecule='dna' ):
"""
fasta_fname = string path to FASTA file
input_tuples = tuple containing (1) motif sequence, (2) contig name, (3) start position*, (4) end position, (5) strand to search
*start is expec... | [
"def",
"fasta_motif_scan",
"(",
"fasta_fname",
",",
"input_tuples",
",",
"regex_ready",
"=",
"False",
",",
"allow_overlaps",
"=",
"True",
",",
"file_buffer",
"=",
"False",
",",
"molecule",
"=",
"'dna'",
")",
":",
"###################",
"# validity checks #",
"####... | fasta_fname = string path to FASTA file
input_tuples = tuple containing (1) motif sequence, (2) contig name, (3) start position*, (4) end position, (5) strand to search
*start is expected to be 0-base, end is expected to be 1-base | [
"fasta_fname",
"=",
"string",
"path",
"to",
"FASTA",
"file",
"input_tuples",
"=",
"tuple",
"containing",
"(",
"1",
")",
"motif",
"sequence",
"(",
"2",
")",
"contig",
"name",
"(",
"3",
")",
"start",
"position",
"*",
"(",
"4",
")",
"end",
"position",
"("... | python | train | 34.547945 |
BlueBrain/NeuroM | neurom/fst/_neuritefunc.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuritefunc.py#L407-L415 | def principal_direction_extents(neurites, neurite_type=NeuriteType.all, direction=0):
'''Principal direction extent of neurites in neurons'''
def _pde(neurite):
'''Get the PDE of a single neurite'''
# Get the X, Y,Z coordinates of the points in each section
points = neurite.points[:, :3]... | [
"def",
"principal_direction_extents",
"(",
"neurites",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
",",
"direction",
"=",
"0",
")",
":",
"def",
"_pde",
"(",
"neurite",
")",
":",
"'''Get the PDE of a single neurite'''",
"# Get the X, Y,Z coordinates of the point... | Principal direction extent of neurites in neurons | [
"Principal",
"direction",
"extent",
"of",
"neurites",
"in",
"neurons"
] | python | train | 50.888889 |
mlavin/django-all-access | allaccess/clients.py | https://github.com/mlavin/django-all-access/blob/4b15b6c9dedf8080a7c477e0af1142c609ec5598/allaccess/clients.py#L188-L200 | def get_redirect_args(self, request, callback):
"Get request parameters for redirect url."
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.provider.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
st... | [
"def",
"get_redirect_args",
"(",
"self",
",",
"request",
",",
"callback",
")",
":",
"callback",
"=",
"request",
".",
"build_absolute_uri",
"(",
"callback",
")",
"args",
"=",
"{",
"'client_id'",
":",
"self",
".",
"provider",
".",
"consumer_key",
",",
"'redire... | Get request parameters for redirect url. | [
"Get",
"request",
"parameters",
"for",
"redirect",
"url",
"."
] | python | train | 38.230769 |
benley/butcher | butcher/rubygems.py | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/rubygems.py#L99-L113 | def is_installed(gemname, version=None):
"""Check if a gem is installed."""
cmdline = ['gem', 'list', '-i', gemname]
if version:
cmdline.extend(['-v', version])
try:
subprocess.check_output(cmdline, shell=False)
return True
except (OSError, subprocess.CalledProcessError) as e... | [
"def",
"is_installed",
"(",
"gemname",
",",
"version",
"=",
"None",
")",
":",
"cmdline",
"=",
"[",
"'gem'",
",",
"'list'",
",",
"'-i'",
",",
"gemname",
"]",
"if",
"version",
":",
"cmdline",
".",
"extend",
"(",
"[",
"'-v'",
",",
"version",
"]",
")",
... | Check if a gem is installed. | [
"Check",
"if",
"a",
"gem",
"is",
"installed",
"."
] | python | train | 34.466667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.