repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
angr/claripy | claripy/backends/__init__.py | https://github.com/angr/claripy/blob/4ed61924880af1ea8fb778047d896ec0156412a6/claripy/backends/__init__.py#L630-L639 | def satisfiable(self, extra_constraints=(), solver=None, model_callback=None):
"""
This function does a constraint check and checks if the solver is in a sat state.
:param solver: The backend solver object.
:param extra_constraints: Extra constraints (as ASTs) to add to s... | [
"def",
"satisfiable",
"(",
"self",
",",
"extra_constraints",
"=",
"(",
")",
",",
"solver",
"=",
"None",
",",
"model_callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_satisfiable",
"(",
"extra_constraints",
"=",
"self",
".",
"convert_list",
"(",
"e... | This function does a constraint check and checks if the solver is in a sat state.
:param solver: The backend solver object.
:param extra_constraints: Extra constraints (as ASTs) to add to s for this solve
:param model_callback: a function that will be executed with recovered... | [
"This",
"function",
"does",
"a",
"constraint",
"check",
"and",
"checks",
"if",
"the",
"solver",
"is",
"in",
"a",
"sat",
"state",
"."
] | python | train |
trp07/messages | messages/email_.py | https://github.com/trp07/messages/blob/7789ebc960335a59ea5d319fceed3dd349023648/messages/email_.py#L185-L190 | def _generate_email(self):
"""Put the parts of the email together."""
self.message = MIMEMultipart()
self._add_header()
self._add_body()
self._add_attachments() | [
"def",
"_generate_email",
"(",
"self",
")",
":",
"self",
".",
"message",
"=",
"MIMEMultipart",
"(",
")",
"self",
".",
"_add_header",
"(",
")",
"self",
".",
"_add_body",
"(",
")",
"self",
".",
"_add_attachments",
"(",
")"
] | Put the parts of the email together. | [
"Put",
"the",
"parts",
"of",
"the",
"email",
"together",
"."
] | python | test |
doakey3/DashTable | dashtable/simple2data/truncate_empty_lines.py | https://github.com/doakey3/DashTable/blob/744cfb6a717fa75a8092c83ebcd49b2668023681/dashtable/simple2data/truncate_empty_lines.py#L1-L21 | def truncate_empty_lines(lines):
"""
Removes all empty lines from above and below the text.
We can't just use text.strip() because that would remove the leading
space for the table.
Parameters
----------
lines : list of str
Returns
-------
lines : list of str
The text ... | [
"def",
"truncate_empty_lines",
"(",
"lines",
")",
":",
"while",
"lines",
"[",
"0",
"]",
".",
"rstrip",
"(",
")",
"==",
"''",
":",
"lines",
".",
"pop",
"(",
"0",
")",
"while",
"lines",
"[",
"len",
"(",
"lines",
")",
"-",
"1",
"]",
".",
"rstrip",
... | Removes all empty lines from above and below the text.
We can't just use text.strip() because that would remove the leading
space for the table.
Parameters
----------
lines : list of str
Returns
-------
lines : list of str
The text lines without empty lines above or below | [
"Removes",
"all",
"empty",
"lines",
"from",
"above",
"and",
"below",
"the",
"text",
"."
] | python | train |
garnaat/placebo | placebo/pill.py | https://github.com/garnaat/placebo/blob/1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7/placebo/pill.py#L233-L259 | def get_next_file_path(self, service, operation):
"""
Returns a tuple with the next file to read and the serializer
format used
"""
base_name = '{0}.{1}'.format(service, operation)
if self.prefix:
base_name = '{0}.{1}'.format(self.prefix, base_name)
LO... | [
"def",
"get_next_file_path",
"(",
"self",
",",
"service",
",",
"operation",
")",
":",
"base_name",
"=",
"'{0}.{1}'",
".",
"format",
"(",
"service",
",",
"operation",
")",
"if",
"self",
".",
"prefix",
":",
"base_name",
"=",
"'{0}.{1}'",
".",
"format",
"(",
... | Returns a tuple with the next file to read and the serializer
format used | [
"Returns",
"a",
"tuple",
"with",
"the",
"next",
"file",
"to",
"read",
"and",
"the",
"serializer",
"format",
"used"
] | python | train |
jobovy/galpy | galpy/actionAngle/actionAngleAxi.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleAxi.py#L220-L241 | def JR(self,**kwargs):
"""
NAME:
JR
PURPOSE:
Calculate the radial action
INPUT:
+scipy.integrate.quad keywords
OUTPUT:
J_R(R,vT,vT)/ro/vc + estimate of the error
HISTORY:
2010-12-01 - Written - Bovy (NYU)
"""
... | [
"def",
"JR",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_JR'",
")",
":",
"#pragma: no cover",
"return",
"self",
".",
"_JR",
"(",
"rperi",
",",
"rap",
")",
"=",
"self",
".",
"calcRapRperi",
"(",
"*",
"*",
... | NAME:
JR
PURPOSE:
Calculate the radial action
INPUT:
+scipy.integrate.quad keywords
OUTPUT:
J_R(R,vT,vT)/ro/vc + estimate of the error
HISTORY:
2010-12-01 - Written - Bovy (NYU) | [
"NAME",
":",
"JR",
"PURPOSE",
":",
"Calculate",
"the",
"radial",
"action",
"INPUT",
":",
"+",
"scipy",
".",
"integrate",
".",
"quad",
"keywords",
"OUTPUT",
":",
"J_R",
"(",
"R",
"vT",
"vT",
")",
"/",
"ro",
"/",
"vc",
"+",
"estimate",
"of",
"the",
"... | python | train |
galaxyproject/pulsar | pulsar/managers/base/base_drmaa.py | https://github.com/galaxyproject/pulsar/blob/9ab6683802884324652da0a9f0808c7eb59d3ab4/pulsar/managers/base/base_drmaa.py#L31-L37 | def shutdown(self, timeout=None):
"""Cleanup DRMAA session and call shutdown of parent."""
try:
super(BaseDrmaaManager, self).shutdown(timeout)
except Exception:
pass
self.drmaa_session.close() | [
"def",
"shutdown",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"super",
"(",
"BaseDrmaaManager",
",",
"self",
")",
".",
"shutdown",
"(",
"timeout",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"drmaa_session",
".",
"close",
... | Cleanup DRMAA session and call shutdown of parent. | [
"Cleanup",
"DRMAA",
"session",
"and",
"call",
"shutdown",
"of",
"parent",
"."
] | python | train |
quodlibet/mutagen | mutagen/id3/_file.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_file.py#L378-L395 | def add_tags(self, ID3=None):
"""Add an empty ID3 tag to the file.
Args:
ID3 (ID3): An ID3 subclass to use or `None` to use the one
that used when loading.
A custom tag reader may be used in instead of the default
`ID3` object, e.g. an `mutagen.easyid3.EasyI... | [
"def",
"add_tags",
"(",
"self",
",",
"ID3",
"=",
"None",
")",
":",
"if",
"ID3",
"is",
"None",
":",
"ID3",
"=",
"self",
".",
"ID3",
"if",
"self",
".",
"tags",
"is",
"None",
":",
"self",
".",
"ID3",
"=",
"ID3",
"self",
".",
"tags",
"=",
"ID3",
... | Add an empty ID3 tag to the file.
Args:
ID3 (ID3): An ID3 subclass to use or `None` to use the one
that used when loading.
A custom tag reader may be used in instead of the default
`ID3` object, e.g. an `mutagen.easyid3.EasyID3` reader. | [
"Add",
"an",
"empty",
"ID3",
"tag",
"to",
"the",
"file",
"."
] | python | train |
philklei/tahoma-api | tahoma_api/tahoma_api.py | https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L529-L560 | def launch_action_group(self, action_id):
"""Start action group."""
header = BASE_HEADERS.copy()
header['Cookie'] = self.__cookie
request = requests.get(
BASE_URL + 'launchActionGroup?oid=' +
action_id,
headers=header,
timeout=10)
... | [
"def",
"launch_action_group",
"(",
"self",
",",
"action_id",
")",
":",
"header",
"=",
"BASE_HEADERS",
".",
"copy",
"(",
")",
"header",
"[",
"'Cookie'",
"]",
"=",
"self",
".",
"__cookie",
"request",
"=",
"requests",
".",
"get",
"(",
"BASE_URL",
"+",
"'lau... | Start action group. | [
"Start",
"action",
"group",
"."
] | python | train |
yatiml/yatiml | yatiml/recognizer.py | https://github.com/yatiml/yatiml/blob/4f55c058b72388350f0af3076ac3ea9bc1c142b0/yatiml/recognizer.py#L34-L51 | def __recognize_scalar(self, node: yaml.Node,
expected_type: Type) -> RecResult:
"""Recognize a node that we expect to be a scalar.
Args:
node: The node to recognize.
expected_type: The type it is expected to be.
Returns:
A list of... | [
"def",
"__recognize_scalar",
"(",
"self",
",",
"node",
":",
"yaml",
".",
"Node",
",",
"expected_type",
":",
"Type",
")",
"->",
"RecResult",
":",
"logger",
".",
"debug",
"(",
"'Recognizing as a scalar'",
")",
"if",
"(",
"isinstance",
"(",
"node",
",",
"yaml... | Recognize a node that we expect to be a scalar.
Args:
node: The node to recognize.
expected_type: The type it is expected to be.
Returns:
A list of recognized types and an error message | [
"Recognize",
"a",
"node",
"that",
"we",
"expect",
"to",
"be",
"a",
"scalar",
"."
] | python | train |
InfoAgeTech/django-core | django_core/forms/fields.py | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/forms/fields.py#L162-L172 | def to_python(self, value):
"""Validates that the input can be converted to a list of decimals."""
if not value:
return None
if isinstance(value, list):
for index, position_val in enumerate(value):
val = super(MultipleDecimalField, self).to_python(positio... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"for",
"index",
",",
"position_val",
"in",
"enumerate",
"(",
"value",
")",
":",
"val",
"=",... | Validates that the input can be converted to a list of decimals. | [
"Validates",
"that",
"the",
"input",
"can",
"be",
"converted",
"to",
"a",
"list",
"of",
"decimals",
"."
] | python | train |
singularityhub/singularity-cli | spython/main/parse/singularity.py | https://github.com/singularityhub/singularity-cli/blob/cb36b4504812ca87e29c6a40b222a545d1865799/spython/main/parse/singularity.py#L38-L61 | def _setup(self, lines):
'''setup required adding content from the host to the rootfs,
so we try to capture with with ADD.
'''
bot.warning('SETUP is error prone, please check output.')
for line in lines:
# For all lines, replace rootfs with actual root /
... | [
"def",
"_setup",
"(",
"self",
",",
"lines",
")",
":",
"bot",
".",
"warning",
"(",
"'SETUP is error prone, please check output.'",
")",
"for",
"line",
"in",
"lines",
":",
"# For all lines, replace rootfs with actual root /",
"line",
"=",
"re",
".",
"sub",
"(",
"'[$... | setup required adding content from the host to the rootfs,
so we try to capture with with ADD. | [
"setup",
"required",
"adding",
"content",
"from",
"the",
"host",
"to",
"the",
"rootfs",
"so",
"we",
"try",
"to",
"capture",
"with",
"with",
"ADD",
"."
] | python | train |
dankelley/nota | nota/notaclass.py | https://github.com/dankelley/nota/blob/245cd575db60daaea6eebd5edc1d048c5fe23c9b/nota/notaclass.py#L289-L297 | def list_books(self):
''' Return the list of book names '''
names = []
try:
for n in self.cur.execute("SELECT name FROM book;").fetchall():
names.extend(n)
except:
self.error("ERROR: cannot find database table 'book'")
return(names) | [
"def",
"list_books",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"try",
":",
"for",
"n",
"in",
"self",
".",
"cur",
".",
"execute",
"(",
"\"SELECT name FROM book;\"",
")",
".",
"fetchall",
"(",
")",
":",
"names",
".",
"extend",
"(",
"n",
")",
"ex... | Return the list of book names | [
"Return",
"the",
"list",
"of",
"book",
"names"
] | python | train |
nats-io/python-nats | nats/io/client.py | https://github.com/nats-io/python-nats/blob/4a409319c409e7e55ce8377b64b406375c5f455b/nats/io/client.py#L909-L981 | def _process_connect_init(self):
"""
Handles the initial part of the NATS protocol, moving from
the (RE)CONNECTING to CONNECTED states when establishing
a connection with the server.
"""
# INFO {...}
line = yield self.io.read_until(_CRLF_, max_bytes=None)
... | [
"def",
"_process_connect_init",
"(",
"self",
")",
":",
"# INFO {...}",
"line",
"=",
"yield",
"self",
".",
"io",
".",
"read_until",
"(",
"_CRLF_",
",",
"max_bytes",
"=",
"None",
")",
"_",
",",
"args",
"=",
"line",
".",
"split",
"(",
"INFO_OP",
"+",
"_SP... | Handles the initial part of the NATS protocol, moving from
the (RE)CONNECTING to CONNECTED states when establishing
a connection with the server. | [
"Handles",
"the",
"initial",
"part",
"of",
"the",
"NATS",
"protocol",
"moving",
"from",
"the",
"(",
"RE",
")",
"CONNECTING",
"to",
"CONNECTED",
"states",
"when",
"establishing",
"a",
"connection",
"with",
"the",
"server",
"."
] | python | train |
ajenhl/tacl | tacl/results.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L88-L116 | def add_label_work_count(self):
"""Adds to each result row a count of the number of works within the
label contain that n-gram.
This counts works that have at least one witness carrying the
n-gram.
This correctly handles cases where an n-gram has only zero
counts for a ... | [
"def",
"add_label_work_count",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Adding label work count'",
")",
"def",
"add_label_text_count",
"(",
"df",
")",
":",
"work_maxima",
"=",
"df",
".",
"groupby",
"(",
"constants",
".",
"WORK_FIELDNA... | Adds to each result row a count of the number of works within the
label contain that n-gram.
This counts works that have at least one witness carrying the
n-gram.
This correctly handles cases where an n-gram has only zero
counts for a given work (possible with zero-fill followe... | [
"Adds",
"to",
"each",
"result",
"row",
"a",
"count",
"of",
"the",
"number",
"of",
"works",
"within",
"the",
"label",
"contain",
"that",
"n",
"-",
"gram",
"."
] | python | train |
hydraplatform/hydra-base | hydra_base/db/model.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1702-L1710 | def is_admin(self):
"""
Check that the user has a role with the code 'admin'
"""
for ur in self.roleusers:
if ur.role.code == 'admin':
return True
return False | [
"def",
"is_admin",
"(",
"self",
")",
":",
"for",
"ur",
"in",
"self",
".",
"roleusers",
":",
"if",
"ur",
".",
"role",
".",
"code",
"==",
"'admin'",
":",
"return",
"True",
"return",
"False"
] | Check that the user has a role with the code 'admin' | [
"Check",
"that",
"the",
"user",
"has",
"a",
"role",
"with",
"the",
"code",
"admin"
] | python | train |
saltstack/salt | salt/modules/boto_ec2.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L150-L194 | def get_unassociated_eip_address(domain='standard', region=None, key=None,
keyid=None, profile=None):
'''
Return the first unassociated EIP
domain
Indicates whether the address is an EC2 address or a VPC address
(standard|vpc).
CLI Example:
.. code... | [
"def",
"get_unassociated_eip_address",
"(",
"domain",
"=",
"'standard'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"eip",
"=",
"None",
"for",
"address",
"in",
"get_all_eip_address... | Return the first unassociated EIP
domain
Indicates whether the address is an EC2 address or a VPC address
(standard|vpc).
CLI Example:
.. code-block:: bash
salt-call boto_ec2.get_unassociated_eip_address
.. versionadded:: 2016.3.0 | [
"Return",
"the",
"first",
"unassociated",
"EIP"
] | python | train |
jborean93/ntlm-auth | ntlm_auth/compute_keys.py | https://github.com/jborean93/ntlm-auth/blob/2c7cd81516d9bfd42e8ff473a534d876b21ebb38/ntlm_auth/compute_keys.py#L11-L52 | def _get_exchange_key_ntlm_v1(negotiate_flags, session_base_key,
server_challenge, lm_challenge_response,
lm_hash):
"""
[MS-NLMP] v28.0 2016-07-14
3.4.5.1 KXKEY
Calculates the Key Exchange Key for NTLMv1 authentication. Used for signing
an... | [
"def",
"_get_exchange_key_ntlm_v1",
"(",
"negotiate_flags",
",",
"session_base_key",
",",
"server_challenge",
",",
"lm_challenge_response",
",",
"lm_hash",
")",
":",
"if",
"negotiate_flags",
"&",
"NegotiateFlags",
".",
"NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY",
":",
"key... | [MS-NLMP] v28.0 2016-07-14
3.4.5.1 KXKEY
Calculates the Key Exchange Key for NTLMv1 authentication. Used for signing
and sealing messages
:param negotiate_flags: The negotiated NTLM flags
:param session_base_key: A session key calculated from the user password
challenge
:param server_c... | [
"[",
"MS",
"-",
"NLMP",
"]",
"v28",
".",
"0",
"2016",
"-",
"07",
"-",
"14"
] | python | train |
openstax/cnx-archive | cnxarchive/views/legacy_redirect.py | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/legacy_redirect.py#L72-L119 | def redirect_legacy_content(request):
"""Redirect from legacy /content/id/version to new /contents/uuid@version.
Handles collection context (book) as well.
"""
routing_args = request.matchdict
objid = routing_args['objid']
objver = routing_args.get('objver')
filename = routing_args.get('fil... | [
"def",
"redirect_legacy_content",
"(",
"request",
")",
":",
"routing_args",
"=",
"request",
".",
"matchdict",
"objid",
"=",
"routing_args",
"[",
"'objid'",
"]",
"objver",
"=",
"routing_args",
".",
"get",
"(",
"'objver'",
")",
"filename",
"=",
"routing_args",
"... | Redirect from legacy /content/id/version to new /contents/uuid@version.
Handles collection context (book) as well. | [
"Redirect",
"from",
"legacy",
"/",
"content",
"/",
"id",
"/",
"version",
"to",
"new",
"/",
"contents",
"/",
"uuid@version",
"."
] | python | train |
DataBiosphere/dsub | dsub/providers/google_v2.py | https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2.py#L872-L931 | def submit_job(self, job_descriptor, skip_if_output_present):
"""Submit the job (or tasks) to be executed.
Args:
job_descriptor: all parameters needed to launch all job tasks
skip_if_output_present: (boolean) if true, skip tasks whose output
is present (see --skip flag for more explanation)... | [
"def",
"submit_job",
"(",
"self",
",",
"job_descriptor",
",",
"skip_if_output_present",
")",
":",
"# Validate task data and resources.",
"param_util",
".",
"validate_submit_args_or_fail",
"(",
"job_descriptor",
",",
"provider_name",
"=",
"_PROVIDER_NAME",
",",
"input_provid... | Submit the job (or tasks) to be executed.
Args:
job_descriptor: all parameters needed to launch all job tasks
skip_if_output_present: (boolean) if true, skip tasks whose output
is present (see --skip flag for more explanation).
Returns:
A dictionary containing the 'user-id', 'job-id'... | [
"Submit",
"the",
"job",
"(",
"or",
"tasks",
")",
"to",
"be",
"executed",
"."
] | python | valid |
relekang/python-semantic-release | semantic_release/cli.py | https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/cli.py#L96-L129 | def changelog(**kwargs):
"""
Generates the changelog since the last release.
:raises ImproperConfigurationError: if there is no current version
"""
current_version = get_current_version()
debug('changelog got current_version', current_version)
if current_version is None:
raise Impro... | [
"def",
"changelog",
"(",
"*",
"*",
"kwargs",
")",
":",
"current_version",
"=",
"get_current_version",
"(",
")",
"debug",
"(",
"'changelog got current_version'",
",",
"current_version",
")",
"if",
"current_version",
"is",
"None",
":",
"raise",
"ImproperConfigurationE... | Generates the changelog since the last release.
:raises ImproperConfigurationError: if there is no current version | [
"Generates",
"the",
"changelog",
"since",
"the",
"last",
"release",
".",
":",
"raises",
"ImproperConfigurationError",
":",
"if",
"there",
"is",
"no",
"current",
"version"
] | python | train |
dade-ai/snipy | snipy/io/fileutil.py | https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/io/fileutil.py#L334-L345 | def findfolder(toppath, match='*', exclude=''):
"""
recursively find folder path from toppath.
patterns to decide to walk folder path or not
:type toppath: str
:type match: str or list(str)
:type exclude: str or list(str)
:rtype: generator for path str
"""
pred = _pred_pattern(match,... | [
"def",
"findfolder",
"(",
"toppath",
",",
"match",
"=",
"'*'",
",",
"exclude",
"=",
"''",
")",
":",
"pred",
"=",
"_pred_pattern",
"(",
"match",
",",
"exclude",
")",
"return",
"(",
"p",
"for",
"p",
"in",
"walkfolder",
"(",
"toppath",
",",
"pred",
")",... | recursively find folder path from toppath.
patterns to decide to walk folder path or not
:type toppath: str
:type match: str or list(str)
:type exclude: str or list(str)
:rtype: generator for path str | [
"recursively",
"find",
"folder",
"path",
"from",
"toppath",
".",
"patterns",
"to",
"decide",
"to",
"walk",
"folder",
"path",
"or",
"not",
":",
"type",
"toppath",
":",
"str",
":",
"type",
"match",
":",
"str",
"or",
"list",
"(",
"str",
")",
":",
"type",
... | python | valid |
googledatalab/pydatalab | google/datalab/bigquery/_query.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_query.py#L122-L167 | def _expanded_sql(self, sampling=None):
"""Get the expanded SQL of this object, including all subqueries, UDFs, and external datasources
Returns:
The expanded SQL string of this object
"""
# use lists to preserve the order of subqueries, bigquery will not like listing subqueries
# out of ord... | [
"def",
"_expanded_sql",
"(",
"self",
",",
"sampling",
"=",
"None",
")",
":",
"# use lists to preserve the order of subqueries, bigquery will not like listing subqueries",
"# out of order if they depend on each other. for example. the following will be rejected:",
"# WITH q2 as (SELECT * FROM... | Get the expanded SQL of this object, including all subqueries, UDFs, and external datasources
Returns:
The expanded SQL string of this object | [
"Get",
"the",
"expanded",
"SQL",
"of",
"this",
"object",
"including",
"all",
"subqueries",
"UDFs",
"and",
"external",
"datasources"
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/controllers/execution_ticker.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/execution_ticker.py#L72-L82 | def on_config_value_changed(self, config_m, prop_name, info):
"""Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config ... | [
"def",
"on_config_value_changed",
"(",
"self",
",",
"config_m",
",",
"prop_name",
",",
"info",
")",
":",
"config_key",
"=",
"info",
"[",
"'args'",
"]",
"[",
"1",
"]",
"if",
"config_key",
"in",
"[",
"\"EXECUTION_TICKER_ENABLED\"",
"]",
":",
"self",
".",
"ch... | Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config key | [
"Callback",
"when",
"a",
"config",
"value",
"has",
"been",
"changed"
] | python | train |
erdc/RAPIDpy | RAPIDpy/helper_functions.py | https://github.com/erdc/RAPIDpy/blob/50e14e130554b254a00ff23b226cd7e4c6cfe91a/RAPIDpy/helper_functions.py#L108-L112 | def compare_csv_timeseries_files(file1, file2, header=True):
"""
This function compares two csv files
"""
return compare_csv_decimal_files(file1, file2, header, True) | [
"def",
"compare_csv_timeseries_files",
"(",
"file1",
",",
"file2",
",",
"header",
"=",
"True",
")",
":",
"return",
"compare_csv_decimal_files",
"(",
"file1",
",",
"file2",
",",
"header",
",",
"True",
")"
] | This function compares two csv files | [
"This",
"function",
"compares",
"two",
"csv",
"files"
] | python | train |
raiden-network/raiden-contracts | raiden_contracts/deploy/__main__.py | https://github.com/raiden-network/raiden-contracts/blob/a7e72a9477f2204b03f3706360ea8d9c0a8e7063/raiden_contracts/deploy/__main__.py#L49-L84 | def common_options(func):
"""A decorator that combines commonly appearing @click.option decorators."""
@click.option(
'--private-key',
required=True,
help='Path to a private key store.',
)
@click.option(
'--rpc-provider',
default='http://127.0.0.1:8545',
h... | [
"def",
"common_options",
"(",
"func",
")",
":",
"@",
"click",
".",
"option",
"(",
"'--private-key'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'Path to a private key store.'",
",",
")",
"@",
"click",
".",
"option",
"(",
"'--rpc-provider'",
",",
"defau... | A decorator that combines commonly appearing @click.option decorators. | [
"A",
"decorator",
"that",
"combines",
"commonly",
"appearing"
] | python | train |
thelabnyc/wagtail_blog | blog/wp_xml_parser.py | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L155-L178 | def translate_item(self, item_dict):
"""cleanup item keys to match API json format"""
if not item_dict.get('title'):
return None
# Skip attachments
if item_dict.get('{wp}post_type', None) == 'attachment':
return None
ret_dict = {}
# slugify post ti... | [
"def",
"translate_item",
"(",
"self",
",",
"item_dict",
")",
":",
"if",
"not",
"item_dict",
".",
"get",
"(",
"'title'",
")",
":",
"return",
"None",
"# Skip attachments",
"if",
"item_dict",
".",
"get",
"(",
"'{wp}post_type'",
",",
"None",
")",
"==",
"'attac... | cleanup item keys to match API json format | [
"cleanup",
"item",
"keys",
"to",
"match",
"API",
"json",
"format"
] | python | train |
JoeVirtual/KonFoo | konfoo/core.py | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L1105-L1121 | def read_from(self, provider, **options):
""" All :class:`Pointer` fields in the `Sequence` read the necessary
number of bytes from the data :class:`Provider` for their referenced
:attr:`~Pointer.data` object. Null pointer are ignored.
:param Provider provider: data :class:`Provider`.
... | [
"def",
"read_from",
"(",
"self",
",",
"provider",
",",
"*",
"*",
"options",
")",
":",
"for",
"item",
"in",
"iter",
"(",
"self",
")",
":",
"# Container or Pointer",
"if",
"is_mixin",
"(",
"item",
")",
":",
"item",
".",
"read_from",
"(",
"provider",
",",... | All :class:`Pointer` fields in the `Sequence` read the necessary
number of bytes from the data :class:`Provider` for their referenced
:attr:`~Pointer.data` object. Null pointer are ignored.
:param Provider provider: data :class:`Provider`.
:keyword bool nested: if ``True`` all :class:`P... | [
"All",
":",
"class",
":",
"Pointer",
"fields",
"in",
"the",
"Sequence",
"read",
"the",
"necessary",
"number",
"of",
"bytes",
"from",
"the",
"data",
":",
"class",
":",
"Provider",
"for",
"their",
"referenced",
":",
"attr",
":",
"~Pointer",
".",
"data",
"o... | python | train |
trec-kba/streamcorpus-pipeline | streamcorpus_pipeline/_pipeline.py | https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_pipeline.py#L514-L650 | def run(self, i_str, start_count=0, start_chunk_time=None):
'''Run the pipeline.
This runs all of the steps described in the pipeline constructor,
reading from some input and writing to some output.
:param str i_str: name of the input file, or other reader-specific
descriptio... | [
"def",
"run",
"(",
"self",
",",
"i_str",
",",
"start_count",
"=",
"0",
",",
"start_chunk_time",
"=",
"None",
")",
":",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"tmp_dir_path",
")",
":",
"os",
".",
"makedirs",
"("... | Run the pipeline.
This runs all of the steps described in the pipeline constructor,
reading from some input and writing to some output.
:param str i_str: name of the input file, or other reader-specific
description of where to get input
:param int start_count: index of the fi... | [
"Run",
"the",
"pipeline",
"."
] | python | test |
tonysimpson/nanomsg-python | nanomsg/__init__.py | https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L94-L127 | def poll(in_sockets, out_sockets, timeout=-1):
"""
Poll a list of sockets
:param in_sockets: sockets for reading
:param out_sockets: sockets for writing
:param timeout: poll timeout in seconds, -1 is infinite wait
:return: tuple (read socket list, write socket list)
"""
sockets = {}
... | [
"def",
"poll",
"(",
"in_sockets",
",",
"out_sockets",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"sockets",
"=",
"{",
"}",
"# reverse map fd => socket",
"fd_sockets",
"=",
"{",
"}",
"for",
"s",
"in",
"in_sockets",
":",
"sockets",
"[",
"s",
".",
"fd",
"]"... | Poll a list of sockets
:param in_sockets: sockets for reading
:param out_sockets: sockets for writing
:param timeout: poll timeout in seconds, -1 is infinite wait
:return: tuple (read socket list, write socket list) | [
"Poll",
"a",
"list",
"of",
"sockets",
":",
"param",
"in_sockets",
":",
"sockets",
"for",
"reading",
":",
"param",
"out_sockets",
":",
"sockets",
"for",
"writing",
":",
"param",
"timeout",
":",
"poll",
"timeout",
"in",
"seconds",
"-",
"1",
"is",
"infinite",... | python | train |
sernst/cauldron | cauldron/session/writing/components/definitions.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/writing/components/definitions.py#L61-L84 | def combine_lists_reducer(
key: str,
merged_list: list,
component: COMPONENT
) -> list:
"""
Reducer function to combine the lists for the specified key into a
single, flat list
:param key:
The key on the COMPONENT instances to operate upon
:param merged_list:
... | [
"def",
"combine_lists_reducer",
"(",
"key",
":",
"str",
",",
"merged_list",
":",
"list",
",",
"component",
":",
"COMPONENT",
")",
"->",
"list",
":",
"merged_list",
".",
"extend",
"(",
"getattr",
"(",
"component",
",",
"key",
")",
")",
"return",
"merged_lis... | Reducer function to combine the lists for the specified key into a
single, flat list
:param key:
The key on the COMPONENT instances to operate upon
:param merged_list:
The accumulated list of values populated by previous calls to this
reducer function
:param component:
T... | [
"Reducer",
"function",
"to",
"combine",
"the",
"lists",
"for",
"the",
"specified",
"key",
"into",
"a",
"single",
"flat",
"list"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py#L716-L722 | def demix2(servo1, servo2, gain=0.5):
'''de-mix a mixed servo output'''
s1 = servo1 - 1500
s2 = servo2 - 1500
out1 = (s1+s2)*gain
out2 = (s1-s2)*gain
return out2+1500 | [
"def",
"demix2",
"(",
"servo1",
",",
"servo2",
",",
"gain",
"=",
"0.5",
")",
":",
"s1",
"=",
"servo1",
"-",
"1500",
"s2",
"=",
"servo2",
"-",
"1500",
"out1",
"=",
"(",
"s1",
"+",
"s2",
")",
"*",
"gain",
"out2",
"=",
"(",
"s1",
"-",
"s2",
")",... | de-mix a mixed servo output | [
"de",
"-",
"mix",
"a",
"mixed",
"servo",
"output"
] | python | train |
saltstack/salt | salt/modules/lxd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxd.py#L2492-L2539 | def image_list(list_aliases=False, remote_addr=None,
cert=None, key=None, verify_cert=True):
''' Lists all images from the LXD.
list_aliases :
Return a dict with the fingerprint as key and
a list of aliases as value instead.
remote_addr :
An URL ... | [
"def",
"image_list",
"(",
"list_aliases",
"=",
"False",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
"client",
"=",
"pylxd_client_get",
"(",
"remote_addr",
",",
"cert",
","... | Lists all images from the LXD.
list_aliases :
Return a dict with the fingerprint as key and
a list of aliases as value instead.
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!... | [
"Lists",
"all",
"images",
"from",
"the",
"LXD",
"."
] | python | train |
adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L241-L274 | def _read_frame(self, length):
"""Read a response frame from the PN532 of at most length bytes in size.
Returns the data inside the frame if found, otherwise raises an exception
if there is an error parsing the frame. Note that less than length bytes
might be returned!
"""
... | [
"def",
"_read_frame",
"(",
"self",
",",
"length",
")",
":",
"# Read frame with expected length of data.",
"response",
"=",
"self",
".",
"_read_data",
"(",
"length",
"+",
"8",
")",
"logger",
".",
"debug",
"(",
"'Read frame: 0x{0}'",
".",
"format",
"(",
"binascii"... | Read a response frame from the PN532 of at most length bytes in size.
Returns the data inside the frame if found, otherwise raises an exception
if there is an error parsing the frame. Note that less than length bytes
might be returned! | [
"Read",
"a",
"response",
"frame",
"from",
"the",
"PN532",
"of",
"at",
"most",
"length",
"bytes",
"in",
"size",
".",
"Returns",
"the",
"data",
"inside",
"the",
"frame",
"if",
"found",
"otherwise",
"raises",
"an",
"exception",
"if",
"there",
"is",
"an",
"e... | python | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L78-L84 | def Unpack(self, msg):
"""Unpacks the current Any message into specified message."""
descriptor = msg.DESCRIPTOR
if not self.Is(descriptor):
return False
msg.ParseFromString(self.value)
return True | [
"def",
"Unpack",
"(",
"self",
",",
"msg",
")",
":",
"descriptor",
"=",
"msg",
".",
"DESCRIPTOR",
"if",
"not",
"self",
".",
"Is",
"(",
"descriptor",
")",
":",
"return",
"False",
"msg",
".",
"ParseFromString",
"(",
"self",
".",
"value",
")",
"return",
... | Unpacks the current Any message into specified message. | [
"Unpacks",
"the",
"current",
"Any",
"message",
"into",
"specified",
"message",
"."
] | python | train |
quantopian/pyfolio | pyfolio/plotting.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L1114-L1194 | def show_and_plot_top_positions(returns, positions_alloc,
show_and_plot=2, hide_positions=False,
legend_loc='real_best', ax=None,
**kwargs):
"""
Prints and/or plots the exposures of the top 10 held positions of
a... | [
"def",
"show_and_plot_top_positions",
"(",
"returns",
",",
"positions_alloc",
",",
"show_and_plot",
"=",
"2",
",",
"hide_positions",
"=",
"False",
",",
"legend_loc",
"=",
"'real_best'",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"positions_allo... | Prints and/or plots the exposures of the top 10 held positions of
all time.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
positions_alloc : pd.DataFrame
Portfolio allocation of... | [
"Prints",
"and",
"/",
"or",
"plots",
"the",
"exposures",
"of",
"the",
"top",
"10",
"held",
"positions",
"of",
"all",
"time",
"."
] | python | valid |
maxpumperla/elephas | elephas/spark_model.py | https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L156-L197 | def _fit(self, rdd, epochs, batch_size, verbose, validation_split):
"""Protected train method to make wrapping of modes easier
"""
self._master_network.compile(optimizer=self.master_optimizer,
loss=self.master_loss,
metric... | [
"def",
"_fit",
"(",
"self",
",",
"rdd",
",",
"epochs",
",",
"batch_size",
",",
"verbose",
",",
"validation_split",
")",
":",
"self",
".",
"_master_network",
".",
"compile",
"(",
"optimizer",
"=",
"self",
".",
"master_optimizer",
",",
"loss",
"=",
"self",
... | Protected train method to make wrapping of modes easier | [
"Protected",
"train",
"method",
"to",
"make",
"wrapping",
"of",
"modes",
"easier"
] | python | train |
Grk0/python-libconf | libconf.py | https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L476-L498 | def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load... | [
"def",
"load",
"(",
"f",
",",
"filename",
"=",
"None",
",",
"includedir",
"=",
"''",
")",
":",
"if",
"isinstance",
"(",
"f",
".",
"read",
"(",
"0",
")",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"libconf.load() input file must by unicode\"",
"... | Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
... | [
"Load",
"the",
"contents",
"of",
"f",
"(",
"a",
"file",
"-",
"like",
"object",
")",
"to",
"a",
"Python",
"object"
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/FortranCommon.py#L234-L248 | def add_f03_to_env(env):
"""Add Builders and construction variables for f03 to an Environment."""
try:
F03Suffixes = env['F03FILESUFFIXES']
except KeyError:
F03Suffixes = ['.f03']
#print("Adding %s to f95 suffixes" % F95Suffixes)
try:
F03PPSuffixes = env['F03PPFILESUFFIXES']... | [
"def",
"add_f03_to_env",
"(",
"env",
")",
":",
"try",
":",
"F03Suffixes",
"=",
"env",
"[",
"'F03FILESUFFIXES'",
"]",
"except",
"KeyError",
":",
"F03Suffixes",
"=",
"[",
"'.f03'",
"]",
"#print(\"Adding %s to f95 suffixes\" % F95Suffixes)",
"try",
":",
"F03PPSuffixes"... | Add Builders and construction variables for f03 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"f03",
"to",
"an",
"Environment",
"."
] | python | train |
sixty-north/cosmic-ray | src/cosmic_ray/commands/execute.py | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/commands/execute.py#L33-L61 | def execute(db_name):
"""Execute any pending work in the database stored in `db_name`,
recording the results.
This looks for any work in `db_name` which has no results, schedules it to
be executed, and records any results that arrive.
"""
try:
with use_db(db_name, mode=WorkDB.Mode.open)... | [
"def",
"execute",
"(",
"db_name",
")",
":",
"try",
":",
"with",
"use_db",
"(",
"db_name",
",",
"mode",
"=",
"WorkDB",
".",
"Mode",
".",
"open",
")",
"as",
"work_db",
":",
"_update_progress",
"(",
"work_db",
")",
"config",
"=",
"work_db",
".",
"get_conf... | Execute any pending work in the database stored in `db_name`,
recording the results.
This looks for any work in `db_name` which has no results, schedules it to
be executed, and records any results that arrive. | [
"Execute",
"any",
"pending",
"work",
"in",
"the",
"database",
"stored",
"in",
"db_name",
"recording",
"the",
"results",
"."
] | python | train |
Yelp/kafka-utils | kafka_utils/util/offsets.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/offsets.py#L234-L320 | def get_topics_watermarks(kafka_client, topics, raise_on_error=True):
""" Get current topic watermarks.
NOTE: This method does not refresh client metadata. It is up to the caller
to use avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics... | [
"def",
"get_topics_watermarks",
"(",
"kafka_client",
",",
"topics",
",",
"raise_on_error",
"=",
"True",
")",
":",
"topics",
"=",
"_verify_topics_and_partitions",
"(",
"kafka_client",
",",
"topics",
",",
"raise_on_error",
",",
")",
"highmark_offset_reqs",
"=",
"[",
... | Get current topic watermarks.
NOTE: This method does not refresh client metadata. It is up to the caller
to use avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save bot... | [
"Get",
"current",
"topic",
"watermarks",
"."
] | python | train |
zartstrom/snaptime | snaptime/main.py | https://github.com/zartstrom/snaptime/blob/b05ae09d4dccb1b5c8c4ace9c1937b8139672a3c/snaptime/main.py#L119-L131 | def apply_to_with_tz(self, dttm, timezone):
"""We make sure that after truncating we use the correct timezone,
even if we 'jump' over a daylight saving time switch.
I.e. if we apply "@d" to `Sun Oct 30 04:30:00 CET 2016` (1477798200)
we want to have `Sun Oct 30 00:00:00 CEST 2016` (1477... | [
"def",
"apply_to_with_tz",
"(",
"self",
",",
"dttm",
",",
"timezone",
")",
":",
"result",
"=",
"self",
".",
"apply_to",
"(",
"dttm",
")",
"if",
"self",
".",
"unit",
"in",
"[",
"DAYS",
",",
"WEEKS",
",",
"MONTHS",
",",
"YEARS",
"]",
":",
"naive_dttm",... | We make sure that after truncating we use the correct timezone,
even if we 'jump' over a daylight saving time switch.
I.e. if we apply "@d" to `Sun Oct 30 04:30:00 CET 2016` (1477798200)
we want to have `Sun Oct 30 00:00:00 CEST 2016` (1477778400)
but not `Sun Oct 30 00:00:00 CET 2016` ... | [
"We",
"make",
"sure",
"that",
"after",
"truncating",
"we",
"use",
"the",
"correct",
"timezone",
"even",
"if",
"we",
"jump",
"over",
"a",
"daylight",
"saving",
"time",
"switch",
"."
] | python | test |
Chilipp/psyplot | psyplot/project.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1103-L1126 | def from_dataset(cls, *args, **kwargs):
"""Construct an ArrayList instance from an existing base dataset
Parameters
----------
%(ArrayList.from_dataset.parameters)s
main: Project
The main project that this project corresponds to
Other Parameters
----... | [
"def",
"from_dataset",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"main",
"=",
"kwargs",
".",
"pop",
"(",
"'main'",
",",
"None",
")",
"ret",
"=",
"super",
"(",
"Project",
",",
"cls",
")",
".",
"from_dataset",
"(",
"*",
"args... | Construct an ArrayList instance from an existing base dataset
Parameters
----------
%(ArrayList.from_dataset.parameters)s
main: Project
The main project that this project corresponds to
Other Parameters
----------------
%(ArrayList.from_dataset.other... | [
"Construct",
"an",
"ArrayList",
"instance",
"from",
"an",
"existing",
"base",
"dataset"
] | python | train |
srevenant/onetimejwt | onetimejwt/__init__.py | https://github.com/srevenant/onetimejwt/blob/f3ed561253eb4a8e1522c64f59bf64d275e9d315/onetimejwt/__init__.py#L140-L174 | def valid(self, token):
"""is this token valid?"""
now = time.time()
if 'Bearer ' in token:
token = token[7:]
data = None
for secret in self.secrets:
try:
data = jwt.decode(token, secret)
break
except jwt.Decod... | [
"def",
"valid",
"(",
"self",
",",
"token",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"'Bearer '",
"in",
"token",
":",
"token",
"=",
"token",
"[",
"7",
":",
"]",
"data",
"=",
"None",
"for",
"secret",
"in",
"self",
".",
"secrets",
... | is this token valid? | [
"is",
"this",
"token",
"valid?"
] | python | test |
gawel/panoramisk | panoramisk/utils.py | https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/utils.py#L137-L141 | def get_instances(self):
"""Mostly used for debugging"""
return ["<%s prefix:%s (uid:%s)>" % (self.__class__.__name__,
i.prefix, self.uid)
for i in self.instances] | [
"def",
"get_instances",
"(",
"self",
")",
":",
"return",
"[",
"\"<%s prefix:%s (uid:%s)>\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"i",
".",
"prefix",
",",
"self",
".",
"uid",
")",
"for",
"i",
"in",
"self",
".",
"instances",
"]"
] | Mostly used for debugging | [
"Mostly",
"used",
"for",
"debugging"
] | python | test |
BernardFW/bernard | src/bernard/engine/fsm.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/fsm.py#L159-L169 | def _make_allowed_states(self) -> Iterator[Text]:
"""
Sometimes we load states from the database. In order to avoid loading
an arbitrary class, we list here the state classes that are allowed.
"""
for trans in self.transitions:
yield trans.dest.name()
if... | [
"def",
"_make_allowed_states",
"(",
"self",
")",
"->",
"Iterator",
"[",
"Text",
"]",
":",
"for",
"trans",
"in",
"self",
".",
"transitions",
":",
"yield",
"trans",
".",
"dest",
".",
"name",
"(",
")",
"if",
"trans",
".",
"origin",
":",
"yield",
"trans",
... | Sometimes we load states from the database. In order to avoid loading
an arbitrary class, we list here the state classes that are allowed. | [
"Sometimes",
"we",
"load",
"states",
"from",
"the",
"database",
".",
"In",
"order",
"to",
"avoid",
"loading",
"an",
"arbitrary",
"class",
"we",
"list",
"here",
"the",
"state",
"classes",
"that",
"are",
"allowed",
"."
] | python | train |
mdickinson/bigfloat | bigfloat/core.py | https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L2117-L2129 | def jn(n, x, context=None):
"""
Return the value of the first kind Bessel function of order ``n`` at ``x``.
``n`` should be a Python integer.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_jn,
(n, BigFloat._implicit_convert(x)),
context,
) | [
"def",
"jn",
"(",
"n",
",",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_jn",
",",
"(",
"n",
",",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
")",
",",
"co... | Return the value of the first kind Bessel function of order ``n`` at ``x``.
``n`` should be a Python integer. | [
"Return",
"the",
"value",
"of",
"the",
"first",
"kind",
"Bessel",
"function",
"of",
"order",
"n",
"at",
"x",
"."
] | python | train |
vsoch/helpme | helpme/main/discourse/__init__.py | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/discourse/__init__.py#L65-L77 | def check_env(self, envar, value):
'''ensure that variable envar is set to some value,
otherwise exit on error.
Parameters
==========
envar: the environment variable name
value: the setting that shouldn't be None
'''
if value is No... | [
"def",
"check_env",
"(",
"self",
",",
"envar",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"bot",
".",
"error",
"(",
"'You must export %s to use Discourse'",
"%",
"envar",
")",
"print",
"(",
"'https://vsoch.github.io/helpme/helper-discourse'",
")",
... | ensure that variable envar is set to some value,
otherwise exit on error.
Parameters
==========
envar: the environment variable name
value: the setting that shouldn't be None | [
"ensure",
"that",
"variable",
"envar",
"is",
"set",
"to",
"some",
"value",
"otherwise",
"exit",
"on",
"error",
".",
"Parameters",
"==========",
"envar",
":",
"the",
"environment",
"variable",
"name",
"value",
":",
"the",
"setting",
"that",
"shouldn",
"t",
"b... | python | train |
kurtbrose/faststat | faststat/faststat.py | https://github.com/kurtbrose/faststat/blob/5060c0e10acaafd4a48de3f16869bfccc1deb44a/faststat/faststat.py#L310-L323 | def _commit(self, ref):
'commit a walkers data after it is collected'
path_times = self._weakref_path_map[ref]
path_times.append(nanotime())
del self._weakref_path_map[ref]
path = tuple(path_times[1::2])
times = path_times[::2]
if path not in self.path_stat... | [
"def",
"_commit",
"(",
"self",
",",
"ref",
")",
":",
"path_times",
"=",
"self",
".",
"_weakref_path_map",
"[",
"ref",
"]",
"path_times",
".",
"append",
"(",
"nanotime",
"(",
")",
")",
"del",
"self",
".",
"_weakref_path_map",
"[",
"ref",
"]",
"path",
"=... | commit a walkers data after it is collected | [
"commit",
"a",
"walkers",
"data",
"after",
"it",
"is",
"collected"
] | python | train |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2745-L2756 | def addFreetextAnnot(self, rect, text, fontsize=12, fontname=None, color=None, rotate=0):
"""Add a 'FreeText' annotation in rectangle 'rect'."""
CheckParent(self)
val = _fitz.Page_addFreetextAnnot(self, rect, text, fontsize, fontname, color, rotate)
if not val: return
val.thiso... | [
"def",
"addFreetextAnnot",
"(",
"self",
",",
"rect",
",",
"text",
",",
"fontsize",
"=",
"12",
",",
"fontname",
"=",
"None",
",",
"color",
"=",
"None",
",",
"rotate",
"=",
"0",
")",
":",
"CheckParent",
"(",
"self",
")",
"val",
"=",
"_fitz",
".",
"Pa... | Add a 'FreeText' annotation in rectangle 'rect'. | [
"Add",
"a",
"FreeText",
"annotation",
"in",
"rectangle",
"rect",
"."
] | python | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L831-L846 | def on_result(self, type, task, result):
'''Called after task fetched'''
status_code = result.get('status_code', 599)
if status_code != 599:
status_code = (int(status_code) / 100 * 100)
self._cnt['5m'].event((task.get('project'), status_code), +1)
self._cnt['1h'].even... | [
"def",
"on_result",
"(",
"self",
",",
"type",
",",
"task",
",",
"result",
")",
":",
"status_code",
"=",
"result",
".",
"get",
"(",
"'status_code'",
",",
"599",
")",
"if",
"status_code",
"!=",
"599",
":",
"status_code",
"=",
"(",
"int",
"(",
"status_cod... | Called after task fetched | [
"Called",
"after",
"task",
"fetched"
] | python | train |
tanghaibao/jcvi | jcvi/annotation/maker.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/maker.py#L425-L479 | def split(args):
"""
%prog split split.bed evidences.bed predictor1.gff predictor2.gff fastafile
Split MAKER models by checking against predictors (such as AUGUSTUS and
FGENESH). For each region covered by a working model. Find out the
combination of predictors that gives the best accuracy against ... | [
"def",
"split",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"bed",
"import",
"Bed",
"p",
"=",
"OptionParser",
"(",
"split",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--key\"",
",",
"default",
"=",
"\"Name\"",
",",
"help",
"... | %prog split split.bed evidences.bed predictor1.gff predictor2.gff fastafile
Split MAKER models by checking against predictors (such as AUGUSTUS and
FGENESH). For each region covered by a working model. Find out the
combination of predictors that gives the best accuracy against evidences
(such as PASA).... | [
"%prog",
"split",
"split",
".",
"bed",
"evidences",
".",
"bed",
"predictor1",
".",
"gff",
"predictor2",
".",
"gff",
"fastafile"
] | python | train |
saltstack/salt | salt/modules/sqlite3.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sqlite3.py#L77-L94 | def fetch(db=None, sql=None):
'''
Retrieve data from an sqlite3 db (returns all rows, be careful!)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;'
'''
cur = _connect(db)
if not cur:
return False
cur.execute(sql)
rows =... | [
"def",
"fetch",
"(",
"db",
"=",
"None",
",",
"sql",
"=",
"None",
")",
":",
"cur",
"=",
"_connect",
"(",
"db",
")",
"if",
"not",
"cur",
":",
"return",
"False",
"cur",
".",
"execute",
"(",
"sql",
")",
"rows",
"=",
"cur",
".",
"fetchall",
"(",
")"... | Retrieve data from an sqlite3 db (returns all rows, be careful!)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.fetch /root/test.db 'SELECT * FROM test;' | [
"Retrieve",
"data",
"from",
"an",
"sqlite3",
"db",
"(",
"returns",
"all",
"rows",
"be",
"careful!",
")"
] | python | train |
newville/wxmplot | wxmplot/basepanel.py | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/basepanel.py#L268-L275 | def onLeftUp(self, event=None):
""" left button up"""
if event is None:
return
self.cursor_mode_action('leftup', event=event)
self.canvas.draw_idle()
self.canvas.draw()
self.ForwardEvent(event=event.guiEvent) | [
"def",
"onLeftUp",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"event",
"is",
"None",
":",
"return",
"self",
".",
"cursor_mode_action",
"(",
"'leftup'",
",",
"event",
"=",
"event",
")",
"self",
".",
"canvas",
".",
"draw_idle",
"(",
")",
"... | left button up | [
"left",
"button",
"up"
] | python | train |
uw-it-aca/uw-restclients-canvas | uw_canvas/terms.py | https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/terms.py#L7-L23 | def get_all_terms(self):
"""
Return all of the terms in the account.
https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index
"""
if not self._canvas_account_id:
raise MissingAccountID()
params = {"workflow_state": 'all', 'per_page'... | [
"def",
"get_all_terms",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_canvas_account_id",
":",
"raise",
"MissingAccountID",
"(",
")",
"params",
"=",
"{",
"\"workflow_state\"",
":",
"'all'",
",",
"'per_page'",
":",
"500",
"}",
"url",
"=",
"ACCOUNTS_API",... | Return all of the terms in the account.
https://canvas.instructure.com/doc/api/enrollment_terms.html#method.terms_api.index | [
"Return",
"all",
"of",
"the",
"terms",
"in",
"the",
"account",
".",
"https",
":",
"//",
"canvas",
".",
"instructure",
".",
"com",
"/",
"doc",
"/",
"api",
"/",
"enrollment_terms",
".",
"html#method",
".",
"terms_api",
".",
"index"
] | python | test |
iotaledger/iota.lib.py | examples/address_generator.py | https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/examples/address_generator.py#L59-L80 | def output_seed(seed):
# type: (Seed) -> None
"""
Outputs the user's seed to stdout, along with lots of warnings
about security.
"""
print(
'WARNING: Anyone who has your seed can spend your IOTAs! '
'Clear the screen after recording your seed!'
)
compat.input('')
prin... | [
"def",
"output_seed",
"(",
"seed",
")",
":",
"# type: (Seed) -> None",
"print",
"(",
"'WARNING: Anyone who has your seed can spend your IOTAs! '",
"'Clear the screen after recording your seed!'",
")",
"compat",
".",
"input",
"(",
"''",
")",
"print",
"(",
"'Your seed is:'",
... | Outputs the user's seed to stdout, along with lots of warnings
about security. | [
"Outputs",
"the",
"user",
"s",
"seed",
"to",
"stdout",
"along",
"with",
"lots",
"of",
"warnings",
"about",
"security",
"."
] | python | test |
google/grr | grr/server/grr_response_server/check_lib/triggers.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/check_lib/triggers.py#L88-L101 | def Artifacts(self, os_name=None, cpe=None, label=None):
"""Whether the conditions applies, modulo host data.
Args:
os_name: An OS string.
cpe: A CPE string.
label: A label string.
Returns:
True if os_name, cpe or labels match. Empty values are ignored.
"""
hit = lambda x: ... | [
"def",
"Artifacts",
"(",
"self",
",",
"os_name",
"=",
"None",
",",
"cpe",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"hit",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
"==",
"x",
"[",
"1",
"]",
"or",
"not",
"x",
"[",
"0",
"]",
"seq"... | Whether the conditions applies, modulo host data.
Args:
os_name: An OS string.
cpe: A CPE string.
label: A label string.
Returns:
True if os_name, cpe or labels match. Empty values are ignored. | [
"Whether",
"the",
"conditions",
"applies",
"modulo",
"host",
"data",
"."
] | python | train |
osrg/ryu | ryu/lib/igmplib.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/igmplib.py#L297-L308 | def packet_in_handler(self, req_igmp, msg):
"""the process when the querier received IGMP."""
ofproto = msg.datapath.ofproto
if ofproto.OFP_VERSION == ofproto_v1_0.OFP_VERSION:
in_port = msg.in_port
else:
in_port = msg.match['in_port']
if (igmp.IGMP_TYPE_R... | [
"def",
"packet_in_handler",
"(",
"self",
",",
"req_igmp",
",",
"msg",
")",
":",
"ofproto",
"=",
"msg",
".",
"datapath",
".",
"ofproto",
"if",
"ofproto",
".",
"OFP_VERSION",
"==",
"ofproto_v1_0",
".",
"OFP_VERSION",
":",
"in_port",
"=",
"msg",
".",
"in_port... | the process when the querier received IGMP. | [
"the",
"process",
"when",
"the",
"querier",
"received",
"IGMP",
"."
] | python | train |
bear/ronkyuu | ronkyuu/webmention.py | https://github.com/bear/ronkyuu/blob/91a05fbe220b661760467b7b3d3d780a9ba28afa/ronkyuu/webmention.py#L41-L112 | def findMentions(sourceURL, targetURL=None, exclude_domains=[], content=None, test_urls=True, headers={}, timeout=None):
"""Find all <a /> elements in the given html for a post. Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
If an... | [
"def",
"findMentions",
"(",
"sourceURL",
",",
"targetURL",
"=",
"None",
",",
"exclude_domains",
"=",
"[",
"]",
",",
"content",
"=",
"None",
",",
"test_urls",
"=",
"True",
",",
"headers",
"=",
"{",
"}",
",",
"timeout",
"=",
"None",
")",
":",
"__doc__",
... | Find all <a /> elements in the given html for a post. Only scan html element matching all criteria in look_in.
optionally the content to be scanned can be given as an argument.
If any have an href attribute that is not from the
one of the items in exclude_domains, append it to our lists.
:param sourc... | [
"Find",
"all",
"<a",
"/",
">",
"elements",
"in",
"the",
"given",
"html",
"for",
"a",
"post",
".",
"Only",
"scan",
"html",
"element",
"matching",
"all",
"criteria",
"in",
"look_in",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/resource/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/sessions.py#L1476-L1493 | def get_bins_by_resource(self, resource_id):
"""Gets the list of ``Bin`` objects mapped to a ``Resource``.
arg: resource_id (osid.id.Id): ``Id`` of a ``Resource``
return: (osid.resource.BinList) - list of bins
raise: NotFound - ``resource_id`` is not found
raise: NullArgume... | [
"def",
"get_bins_by_resource",
"(",
"self",
",",
"resource_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_bins_by_resource",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'RESOURCE'",
",",
"local",
"=",
"True",
")",
"lo... | Gets the list of ``Bin`` objects mapped to a ``Resource``.
arg: resource_id (osid.id.Id): ``Id`` of a ``Resource``
return: (osid.resource.BinList) - list of bins
raise: NotFound - ``resource_id`` is not found
raise: NullArgument - ``resource_id`` is ``null``
raise: Operati... | [
"Gets",
"the",
"list",
"of",
"Bin",
"objects",
"mapped",
"to",
"a",
"Resource",
"."
] | python | train |
numenta/htmresearch | projects/sequence_prediction/continuous_sequence/run_lstm_suite.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sequence_prediction/continuous_sequence/run_lstm_suite.py#L39-L66 | def readDataSet(dataSet, noise=0):
"""
:param dataSet: dataset name
:param noise: amount of noise added to the dataset
:return:
"""
filePath = 'data/'+dataSet+'.csv'
if dataSet == 'nyc_taxi' or dataSet == 'nyc_taxi_perturb' or dataSet == 'nyc_taxi_perturb_baseline':
seq = pd.read_csv(filePath, header... | [
"def",
"readDataSet",
"(",
"dataSet",
",",
"noise",
"=",
"0",
")",
":",
"filePath",
"=",
"'data/'",
"+",
"dataSet",
"+",
"'.csv'",
"if",
"dataSet",
"==",
"'nyc_taxi'",
"or",
"dataSet",
"==",
"'nyc_taxi_perturb'",
"or",
"dataSet",
"==",
"'nyc_taxi_perturb_basel... | :param dataSet: dataset name
:param noise: amount of noise added to the dataset
:return: | [
":",
"param",
"dataSet",
":",
"dataset",
"name",
":",
"param",
"noise",
":",
"amount",
"of",
"noise",
"added",
"to",
"the",
"dataset",
":",
"return",
":"
] | python | train |
mkouhei/bootstrap-py | bootstrap_py/update.py | https://github.com/mkouhei/bootstrap-py/blob/95d56ed98ef409fd9f019dc352fd1c3711533275/bootstrap_py/update.py#L37-L43 | def show_message(self):
"""Show message updatable."""
print(
'current version: {current_version}\n'
'latest version : {latest_version}'.format(
current_version=self.current_version,
latest_version=self.latest_version)) | [
"def",
"show_message",
"(",
"self",
")",
":",
"print",
"(",
"'current version: {current_version}\\n'",
"'latest version : {latest_version}'",
".",
"format",
"(",
"current_version",
"=",
"self",
".",
"current_version",
",",
"latest_version",
"=",
"self",
".",
"latest_ver... | Show message updatable. | [
"Show",
"message",
"updatable",
"."
] | python | train |
OpenAssets/openassets | openassets/transactions.py | https://github.com/OpenAssets/openassets/blob/e8eb5b80b9703c80980cb275dd85f17d50e39c60/openassets/transactions.py#L66-L115 | def transfer(self, asset_transfer_specs, btc_transfer_spec, fees):
"""
Creates a transaction for sending assets and bitcoins.
:param list[(bytes, TransferParameters)] asset_transfer_specs: A list of tuples. In each tuple:
- The first element is the ID of an asset.
- The ... | [
"def",
"transfer",
"(",
"self",
",",
"asset_transfer_specs",
",",
"btc_transfer_spec",
",",
"fees",
")",
":",
"inputs",
"=",
"[",
"]",
"outputs",
"=",
"[",
"]",
"asset_quantities",
"=",
"[",
"]",
"for",
"asset_id",
",",
"transfer_spec",
"in",
"asset_transfer... | Creates a transaction for sending assets and bitcoins.
:param list[(bytes, TransferParameters)] asset_transfer_specs: A list of tuples. In each tuple:
- The first element is the ID of an asset.
- The second element is the parameters of the transfer.
:param TransferParameters btc... | [
"Creates",
"a",
"transaction",
"for",
"sending",
"assets",
"and",
"bitcoins",
"."
] | python | train |
SFDO-Tooling/CumulusCI | cumulusci/core/keychain/BaseProjectKeychain.py | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/keychain/BaseProjectKeychain.py#L184-L190 | def set_service(self, name, service_config, project=False):
""" Store a ServiceConfig in the keychain """
if not self.project_config.services or name not in self.project_config.services:
self._raise_service_not_valid(name)
self._validate_service(name, service_config)
self._se... | [
"def",
"set_service",
"(",
"self",
",",
"name",
",",
"service_config",
",",
"project",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"project_config",
".",
"services",
"or",
"name",
"not",
"in",
"self",
".",
"project_config",
".",
"services",
":",
"s... | Store a ServiceConfig in the keychain | [
"Store",
"a",
"ServiceConfig",
"in",
"the",
"keychain"
] | python | train |
spyder-ide/spyder | spyder/plugins/editor/utils/editor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/editor.py#L1007-L1021 | def set_collapsed(block, val):
"""
Sets the fold trigger state (collapsed or expanded).
:param block: The block to modify
:param val: The new trigger state (True=collapsed, False=expanded)
"""
if block is None:
return
state = block.userState()
... | [
"def",
"set_collapsed",
"(",
"block",
",",
"val",
")",
":",
"if",
"block",
"is",
"None",
":",
"return",
"state",
"=",
"block",
".",
"userState",
"(",
")",
"if",
"state",
"==",
"-",
"1",
":",
"state",
"=",
"0",
"state",
"&=",
"0x77FFFFFF",
"state",
... | Sets the fold trigger state (collapsed or expanded).
:param block: The block to modify
:param val: The new trigger state (True=collapsed, False=expanded) | [
"Sets",
"the",
"fold",
"trigger",
"state",
"(",
"collapsed",
"or",
"expanded",
")",
"."
] | python | train |
mesbahamin/chronophore | chronophore/qtview.py | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/qtview.py#L159-L228 | def _sign_button_press(self):
"""Validate input from ent_id, then sign in to the Timesheet."""
user_id = self.ent_id.text().strip()
try:
status = controller.sign(user_id)
# ERROR: User type is unknown (!student and !tutor)
except ValueError as e:
logger.... | [
"def",
"_sign_button_press",
"(",
"self",
")",
":",
"user_id",
"=",
"self",
".",
"ent_id",
".",
"text",
"(",
")",
".",
"strip",
"(",
")",
"try",
":",
"status",
"=",
"controller",
".",
"sign",
"(",
"user_id",
")",
"# ERROR: User type is unknown (!student and ... | Validate input from ent_id, then sign in to the Timesheet. | [
"Validate",
"input",
"from",
"ent_id",
"then",
"sign",
"in",
"to",
"the",
"Timesheet",
"."
] | python | train |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3195-L3237 | def config_collection(self):
"""Collect core config from config files for all seen modules.
"""
shutit_global.shutit_global_object.yield_to_draw()
self.log('In config_collection',level=logging.DEBUG)
cfg = self.cfg
for module_id in self.module_ids():
# Default to None so we can interpret as ifneeded
s... | [
"def",
"config_collection",
"(",
"self",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"self",
".",
"log",
"(",
"'In config_collection'",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"cfg",
"=",
"self",
".",
"cfg... | Collect core config from config files for all seen modules. | [
"Collect",
"core",
"config",
"from",
"config",
"files",
"for",
"all",
"seen",
"modules",
"."
] | python | train |
dls-controls/pymalcolm | malcolm/core/notifier.py | https://github.com/dls-controls/pymalcolm/blob/80ea667e4da26365a6cebc0249f52fdc744bd983/malcolm/core/notifier.py#L193-L215 | def _update_data(self, data):
# type: (Any) -> Dict[str, List]
"""Set our data and notify any subscribers of children what has changed
Args:
data (object): The new data
Returns:
dict: {child_name: [path_list, optional child_data]} of the change
t... | [
"def",
"_update_data",
"(",
"self",
",",
"data",
")",
":",
"# type: (Any) -> Dict[str, List]",
"self",
".",
"data",
"=",
"data",
"child_change_dict",
"=",
"{",
"}",
"# Reflect change of data to children",
"for",
"name",
"in",
"self",
".",
"children",
":",
"child_d... | Set our data and notify any subscribers of children what has changed
Args:
data (object): The new data
Returns:
dict: {child_name: [path_list, optional child_data]} of the change
that needs to be passed to a child as a result of this | [
"Set",
"our",
"data",
"and",
"notify",
"any",
"subscribers",
"of",
"children",
"what",
"has",
"changed"
] | python | train |
OpenGov/carpenter | carpenter/blocks/block.py | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/block.py#L365-L392 | def _validate_rows(self):
'''
Checks for any missing data row by row. It also checks for changes in cell type and flags
multiple switches as an error.
'''
for row_index in range(self.start[0], self.end[0]):
table_row = self.table[row_index]
used_row = self... | [
"def",
"_validate_rows",
"(",
"self",
")",
":",
"for",
"row_index",
"in",
"range",
"(",
"self",
".",
"start",
"[",
"0",
"]",
",",
"self",
".",
"end",
"[",
"0",
"]",
")",
":",
"table_row",
"=",
"self",
".",
"table",
"[",
"row_index",
"]",
"used_row"... | Checks for any missing data row by row. It also checks for changes in cell type and flags
multiple switches as an error. | [
"Checks",
"for",
"any",
"missing",
"data",
"row",
"by",
"row",
".",
"It",
"also",
"checks",
"for",
"changes",
"in",
"cell",
"type",
"and",
"flags",
"multiple",
"switches",
"as",
"an",
"error",
"."
] | python | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAFetch/QATdx.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L336-L409 | def QA_fetch_get_stock_day(code, start_date, end_date, if_fq='00', frequence='day', ip=None, port=None):
"""获取日线及以上级别的数据
Arguments:
code {str:6} -- code 是一个单独的code 6位长度的str
start_date {str:10} -- 10位长度的日期 比如'2017-01-01'
end_date {str:10} -- 10位长度的日期 比如'2018-01-01'
Keyword Argument... | [
"def",
"QA_fetch_get_stock_day",
"(",
"code",
",",
"start_date",
",",
"end_date",
",",
"if_fq",
"=",
"'00'",
",",
"frequence",
"=",
"'day'",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"ip",
",",
"port",
"=",
"get_mainmarket_ip",
"(",
"... | 获取日线及以上级别的数据
Arguments:
code {str:6} -- code 是一个单独的code 6位长度的str
start_date {str:10} -- 10位长度的日期 比如'2017-01-01'
end_date {str:10} -- 10位长度的日期 比如'2018-01-01'
Keyword Arguments:
if_fq {str} -- '00'/'bfq' -- 不复权 '01'/'qfq' -- 前复权 '02'/'hfq' -- 后复权 '03'/'ddqfq' -- 定点前复权 '04'/'ddhf... | [
"获取日线及以上级别的数据"
] | python | train |
rossant/ipymd | ipymd/formats/markdown.py | https://github.com/rossant/ipymd/blob/d87c9ebc59d67fe78b0139ee00e0e5307682e303/ipymd/formats/markdown.py#L201-L206 | def _code_cell(self, source):
"""Split the source into input and output."""
input, output = self._prompt.to_cell(source)
return {'cell_type': 'code',
'input': input,
'output': output} | [
"def",
"_code_cell",
"(",
"self",
",",
"source",
")",
":",
"input",
",",
"output",
"=",
"self",
".",
"_prompt",
".",
"to_cell",
"(",
"source",
")",
"return",
"{",
"'cell_type'",
":",
"'code'",
",",
"'input'",
":",
"input",
",",
"'output'",
":",
"output... | Split the source into input and output. | [
"Split",
"the",
"source",
"into",
"input",
"and",
"output",
"."
] | python | train |
spyder-ide/spyder-kernels | spyder_kernels/utils/nsview.py | https://github.com/spyder-ide/spyder-kernels/blob/2c5b36cdb797b8aba77bc406ca96f5e079c4aaca/spyder_kernels/utils/nsview.py#L580-L597 | def globalsfilter(input_dict, check_all=False, filters=None,
exclude_private=None, exclude_capitalized=None,
exclude_uppercase=None, exclude_unsupported=None,
excluded_names=None):
"""Keep only objects that can be pickled"""
output_dict = {}
for key, val... | [
"def",
"globalsfilter",
"(",
"input_dict",
",",
"check_all",
"=",
"False",
",",
"filters",
"=",
"None",
",",
"exclude_private",
"=",
"None",
",",
"exclude_capitalized",
"=",
"None",
",",
"exclude_uppercase",
"=",
"None",
",",
"exclude_unsupported",
"=",
"None",
... | Keep only objects that can be pickled | [
"Keep",
"only",
"objects",
"that",
"can",
"be",
"pickled"
] | python | train |
coreGreenberet/homematicip-rest-api | homematicip/home.py | https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/home.py#L403-L415 | def search_device_by_id(self, deviceID) -> Device:
""" searches a device by given id
Args:
deviceID(str): the device to search for
Returns
the Device object or None if it couldn't find a device
"""
for d in self.devices:
... | [
"def",
"search_device_by_id",
"(",
"self",
",",
"deviceID",
")",
"->",
"Device",
":",
"for",
"d",
"in",
"self",
".",
"devices",
":",
"if",
"d",
".",
"id",
"==",
"deviceID",
":",
"return",
"d",
"return",
"None"
] | searches a device by given id
Args:
deviceID(str): the device to search for
Returns
the Device object or None if it couldn't find a device | [
"searches",
"a",
"device",
"by",
"given",
"id",
"Args",
":",
"deviceID",
"(",
"str",
")",
":",
"the",
"device",
"to",
"search",
"for",
"Returns",
"the",
"Device",
"object",
"or",
"None",
"if",
"it",
"couldn",
"t",
"find",
"a",
"device"
] | python | train |
rochacbruno/flasgger | flasgger/base.py | https://github.com/rochacbruno/flasgger/blob/fef154f61d7afca548067be0c758c3dd71cc4c97/flasgger/base.py#L246-L255 | def get_def_models(self, definition_filter=None):
"""
Used for class based definitions
"""
model_filter = definition_filter or (lambda tag: True)
return {
definition.name: definition.obj
for definition in self.definition_models
if model_filter(... | [
"def",
"get_def_models",
"(",
"self",
",",
"definition_filter",
"=",
"None",
")",
":",
"model_filter",
"=",
"definition_filter",
"or",
"(",
"lambda",
"tag",
":",
"True",
")",
"return",
"{",
"definition",
".",
"name",
":",
"definition",
".",
"obj",
"for",
"... | Used for class based definitions | [
"Used",
"for",
"class",
"based",
"definitions"
] | python | train |
bcbio/bcbio-nextgen | bcbio/galaxy/api.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/galaxy/api.py#L52-L64 | def run_details(self, run_bc, run_date=None):
"""Next Gen LIMS specific API functionality.
"""
try:
details = self._get("/nglims/api_run_details", dict(run=run_bc))
except ValueError:
raise ValueError("Could not find information in Galaxy for run: %s" % run_bc)
... | [
"def",
"run_details",
"(",
"self",
",",
"run_bc",
",",
"run_date",
"=",
"None",
")",
":",
"try",
":",
"details",
"=",
"self",
".",
"_get",
"(",
"\"/nglims/api_run_details\"",
",",
"dict",
"(",
"run",
"=",
"run_bc",
")",
")",
"except",
"ValueError",
":",
... | Next Gen LIMS specific API functionality. | [
"Next",
"Gen",
"LIMS",
"specific",
"API",
"functionality",
"."
] | python | train |
metachris/RPIO | source/RPIO/_RPIO.py | https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L273-L322 | def wait_for_interrupts(self, epoll_timeout=1):
"""
Blocking loop to listen for GPIO interrupts and distribute them to
associated callbacks. epoll_timeout is an easy way to shutdown the
blocking function. Per default the timeout is set to 1 second; if
`_is_waiting_for_interrupts`... | [
"def",
"wait_for_interrupts",
"(",
"self",
",",
"epoll_timeout",
"=",
"1",
")",
":",
"self",
".",
"_is_waiting_for_interrupts",
"=",
"True",
"while",
"self",
".",
"_is_waiting_for_interrupts",
":",
"events",
"=",
"self",
".",
"_epoll",
".",
"poll",
"(",
"epoll... | Blocking loop to listen for GPIO interrupts and distribute them to
associated callbacks. epoll_timeout is an easy way to shutdown the
blocking function. Per default the timeout is set to 1 second; if
`_is_waiting_for_interrupts` is set to False the loop will exit.
If an exception occurs... | [
"Blocking",
"loop",
"to",
"listen",
"for",
"GPIO",
"interrupts",
"and",
"distribute",
"them",
"to",
"associated",
"callbacks",
".",
"epoll_timeout",
"is",
"an",
"easy",
"way",
"to",
"shutdown",
"the",
"blocking",
"function",
".",
"Per",
"default",
"the",
"time... | python | train |
fedora-python/pyp2rpm | pyp2rpm/metadata_extractors.py | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/metadata_extractors.py#L235-L243 | def srcname(self):
"""Return srcname for the macro if the pypi name should be changed.
Those cases are:
- name was provided with -r option
- pypi name is like python-<name>
"""
if self.rpm_name or self.name.startswith(('python-', 'Python-')):
return self.name... | [
"def",
"srcname",
"(",
"self",
")",
":",
"if",
"self",
".",
"rpm_name",
"or",
"self",
".",
"name",
".",
"startswith",
"(",
"(",
"'python-'",
",",
"'Python-'",
")",
")",
":",
"return",
"self",
".",
"name_convertor",
".",
"base_name",
"(",
"self",
".",
... | Return srcname for the macro if the pypi name should be changed.
Those cases are:
- name was provided with -r option
- pypi name is like python-<name> | [
"Return",
"srcname",
"for",
"the",
"macro",
"if",
"the",
"pypi",
"name",
"should",
"be",
"changed",
"."
] | python | train |
google/grr | grr/server/grr_response_server/hunts/standard.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/hunts/standard.py#L90-L102 | def Start(self):
"""Create the hunt, in the paused state."""
# Anyone can create the hunt but it will be created in the paused
# state. Permissions are required to actually start it.
with implementation.StartHunt(
runner_args=self.args.hunt_runner_args,
args=self.args.hunt_args,
... | [
"def",
"Start",
"(",
"self",
")",
":",
"# Anyone can create the hunt but it will be created in the paused",
"# state. Permissions are required to actually start it.",
"with",
"implementation",
".",
"StartHunt",
"(",
"runner_args",
"=",
"self",
".",
"args",
".",
"hunt_runner_arg... | Create the hunt, in the paused state. | [
"Create",
"the",
"hunt",
"in",
"the",
"paused",
"state",
"."
] | python | train |
NuGrid/NuGridPy | nugridpy/grain.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/grain.py#L1156-L1170 | def get_svnpath():
'''
This subroutine gives back the path of the whole svn tree
installation, which is necessary for the script to run.
'''
svnpathtmp = __file__
splitsvnpath = svnpathtmp.split('/')
if len(splitsvnpath) == 1:
svnpath = os.path.abspath('.') + '/../../'
else:
... | [
"def",
"get_svnpath",
"(",
")",
":",
"svnpathtmp",
"=",
"__file__",
"splitsvnpath",
"=",
"svnpathtmp",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"splitsvnpath",
")",
"==",
"1",
":",
"svnpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
... | This subroutine gives back the path of the whole svn tree
installation, which is necessary for the script to run. | [
"This",
"subroutine",
"gives",
"back",
"the",
"path",
"of",
"the",
"whole",
"svn",
"tree",
"installation",
"which",
"is",
"necessary",
"for",
"the",
"script",
"to",
"run",
"."
] | python | train |
RRZE-HPC/kerncraft | kerncraft/machinemodel.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/machinemodel.py#L193-L218 | def get_compiler(self, compiler=None, flags=None):
"""
Return tuple of compiler and compiler flags.
Selects compiler and flags from machine description file, commandline arguments or call
arguements.
"""
if self._args:
compiler = compiler or self._args.compil... | [
"def",
"get_compiler",
"(",
"self",
",",
"compiler",
"=",
"None",
",",
"flags",
"=",
"None",
")",
":",
"if",
"self",
".",
"_args",
":",
"compiler",
"=",
"compiler",
"or",
"self",
".",
"_args",
".",
"compiler",
"flags",
"=",
"flags",
"or",
"self",
"."... | Return tuple of compiler and compiler flags.
Selects compiler and flags from machine description file, commandline arguments or call
arguements. | [
"Return",
"tuple",
"of",
"compiler",
"and",
"compiler",
"flags",
"."
] | python | test |
digidotcom/python-wvalib | wva/http_client.py | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/http_client.py#L79-L97 | def raw_request(self, method, uri, **kwargs):
"""Perform a WVA web services request and return the raw response object
:param method: The HTTP method to use when making this request
:param uri: The path past /ws to request. That is, the path requested for
a relpath of `a/b/c` would... | [
"def",
"raw_request",
"(",
"self",
",",
"method",
",",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"# catch warning about certs not being verified",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
",",
... | Perform a WVA web services request and return the raw response object
:param method: The HTTP method to use when making this request
:param uri: The path past /ws to request. That is, the path requested for
a relpath of `a/b/c` would be `/ws/a/b/c`.
:raises WVAHttpSocketError: if t... | [
"Perform",
"a",
"WVA",
"web",
"services",
"request",
"and",
"return",
"the",
"raw",
"response",
"object"
] | python | train |
quantmind/pulsar | pulsar/utils/structures/zset.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/zset.py#L71-L76 | def update(self, score_vals):
'''Update the :class:`zset` with an iterable over pairs of
scores and values.'''
add = self.add
for score, value in score_vals:
add(score, value) | [
"def",
"update",
"(",
"self",
",",
"score_vals",
")",
":",
"add",
"=",
"self",
".",
"add",
"for",
"score",
",",
"value",
"in",
"score_vals",
":",
"add",
"(",
"score",
",",
"value",
")"
] | Update the :class:`zset` with an iterable over pairs of
scores and values. | [
"Update",
"the",
":",
"class",
":",
"zset",
"with",
"an",
"iterable",
"over",
"pairs",
"of",
"scores",
"and",
"values",
"."
] | python | train |
rdussurget/py-altimetry | altimetry/data/hydro.py | https://github.com/rdussurget/py-altimetry/blob/57ce7f2d63c6bbc4993821af0bbe46929e3a2d98/altimetry/data/hydro.py#L644-L656 | def get_currentDim(self):
'''
returns the current dimensions of the object
'''
selfDim = self._dimensions.copy()
if not isinstance(selfDim,dimStr):
if selfDim.has_key('_ndims') : nself = selfDim.pop('_ndims')
else :
self.warning(1,... | [
"def",
"get_currentDim",
"(",
"self",
")",
":",
"selfDim",
"=",
"self",
".",
"_dimensions",
".",
"copy",
"(",
")",
"if",
"not",
"isinstance",
"(",
"selfDim",
",",
"dimStr",
")",
":",
"if",
"selfDim",
".",
"has_key",
"(",
"'_ndims'",
")",
":",
"nself",
... | returns the current dimensions of the object | [
"returns",
"the",
"current",
"dimensions",
"of",
"the",
"object"
] | python | train |
PmagPy/PmagPy | pmagpy/builder2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/builder2.py#L508-L581 | def get_data(self):
"""
attempt to read measurements file in working directory.
"""
meas_file = os.path.join(self.WD, 'magic_measurements.txt')
if not os.path.isfile(meas_file):
print("-I- No magic_measurements.txt file")
return {}
try:
... | [
"def",
"get_data",
"(",
"self",
")",
":",
"meas_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"WD",
",",
"'magic_measurements.txt'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"meas_file",
")",
":",
"print",
"(",
"\"-I- ... | attempt to read measurements file in working directory. | [
"attempt",
"to",
"read",
"measurements",
"file",
"in",
"working",
"directory",
"."
] | python | train |
CyberReboot/vent | vent/menus/add_options.py | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/add_options.py#L16-L39 | def repo_values(self):
"""
Set the appropriate repo dir and get the branches and commits of it
"""
branches = []
commits = {}
m_helper = Tools()
status = m_helper.repo_branches(self.parentApp.repo_value['repo'])
# branches and commits must both be retrieve... | [
"def",
"repo_values",
"(",
"self",
")",
":",
"branches",
"=",
"[",
"]",
"commits",
"=",
"{",
"}",
"m_helper",
"=",
"Tools",
"(",
")",
"status",
"=",
"m_helper",
".",
"repo_branches",
"(",
"self",
".",
"parentApp",
".",
"repo_value",
"[",
"'repo'",
"]",... | Set the appropriate repo dir and get the branches and commits of it | [
"Set",
"the",
"appropriate",
"repo",
"dir",
"and",
"get",
"the",
"branches",
"and",
"commits",
"of",
"it"
] | python | train |
Microsoft/botbuilder-python | libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py | https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py#L174-L197 | async def get_answers(
self,
context: TurnContext,
options: QnAMakerOptions = None,
telemetry_properties: Dict[str,str] = None,
telemetry_metrics: Dict[str,int] = None
) -> [QueryResult]:
"""
Generates answers from the knowledge base.
:retu... | [
"async",
"def",
"get_answers",
"(",
"self",
",",
"context",
":",
"TurnContext",
",",
"options",
":",
"QnAMakerOptions",
"=",
"None",
",",
"telemetry_properties",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"telemetry_metrics",
":",
"Dict",
... | Generates answers from the knowledge base.
:return: A list of answers for the user's query, sorted in decreasing order of ranking score.
:rtype: [QueryResult] | [
"Generates",
"answers",
"from",
"the",
"knowledge",
"base",
".",
":",
"return",
":",
"A",
"list",
"of",
"answers",
"for",
"the",
"user",
"s",
"query",
"sorted",
"in",
"decreasing",
"order",
"of",
"ranking",
"score",
".",
":",
"rtype",
":",
"[",
"QueryRes... | python | test |
bitesofcode/projexui | projexui/widgets/xdocktoolbar.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xdocktoolbar.py#L197-L208 | def actionAt(self, pos):
"""
Returns the action at the given position.
:param pos | <QPoint>
:return <QAction> || None
"""
child = self.childAt(pos)
if child:
return child.action()
return None | [
"def",
"actionAt",
"(",
"self",
",",
"pos",
")",
":",
"child",
"=",
"self",
".",
"childAt",
"(",
"pos",
")",
"if",
"child",
":",
"return",
"child",
".",
"action",
"(",
")",
"return",
"None"
] | Returns the action at the given position.
:param pos | <QPoint>
:return <QAction> || None | [
"Returns",
"the",
"action",
"at",
"the",
"given",
"position",
".",
":",
"param",
"pos",
"|",
"<QPoint",
">",
":",
"return",
"<QAction",
">",
"||",
"None"
] | python | train |
deepmind/pysc2 | pysc2/lib/features.py | https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L774-L832 | def observation_spec(self):
"""The observation spec for the SC2 environment.
It's worth noting that the image-like observations are in y,x/row,column
order which is different than the actions which are in x,y order. This is
due to conflicting conventions, and to facilitate printing of the images.
... | [
"def",
"observation_spec",
"(",
"self",
")",
":",
"obs_spec",
"=",
"named_array",
".",
"NamedDict",
"(",
"{",
"\"action_result\"",
":",
"(",
"0",
",",
")",
",",
"# See error.proto: ActionResult.",
"\"alerts\"",
":",
"(",
"0",
",",
")",
",",
"# See sc2api.proto... | The observation spec for the SC2 environment.
It's worth noting that the image-like observations are in y,x/row,column
order which is different than the actions which are in x,y order. This is
due to conflicting conventions, and to facilitate printing of the images.
Returns:
The dict of observat... | [
"The",
"observation",
"spec",
"for",
"the",
"SC2",
"environment",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1157-L1188 | def add_timing_signal(x, min_timescale=1, max_timescale=1e4, num_timescales=16):
"""Adds a bunch of sinusoids of different frequencies to a Tensor.
This allows attention to learn to use absolute and relative positions.
The timing signal should be added to some precursor of both the source
and the target of the... | [
"def",
"add_timing_signal",
"(",
"x",
",",
"min_timescale",
"=",
"1",
",",
"max_timescale",
"=",
"1e4",
",",
"num_timescales",
"=",
"16",
")",
":",
"length",
"=",
"shape_list",
"(",
"x",
")",
"[",
"1",
"]",
"depth",
"=",
"shape_list",
"(",
"x",
")",
... | Adds a bunch of sinusoids of different frequencies to a Tensor.
This allows attention to learn to use absolute and relative positions.
The timing signal should be added to some precursor of both the source
and the target of the attention.
The use of relative position is possible because sin(x+y) and cos(x+y) ... | [
"Adds",
"a",
"bunch",
"of",
"sinusoids",
"of",
"different",
"frequencies",
"to",
"a",
"Tensor",
"."
] | python | train |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/skill_builder.py | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L216-L250 | def global_response_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global
response interceptors easily to the builder.
The returned wrapper function can be applied as a decorator
on any function that processes the input and the response
ge... | [
"def",
"global_response_interceptor",
"(",
"self",
")",
":",
"# type: () -> Callable",
"def",
"wrapper",
"(",
"process_func",
")",
":",
"if",
"not",
"callable",
"(",
"process_func",
")",
":",
"raise",
"SkillBuilderException",
"(",
"\"Global Response Interceptor process_... | Decorator that can be used to add global
response interceptors easily to the builder.
The returned wrapper function can be applied as a decorator
on any function that processes the input and the response
generated by the request handler. The function should follow
the signature ... | [
"Decorator",
"that",
"can",
"be",
"used",
"to",
"add",
"global",
"response",
"interceptors",
"easily",
"to",
"the",
"builder",
"."
] | python | train |
mcs07/ChemDataExtractor | chemdataextractor/text/__init__.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/__init__.py#L232-L258 | def levenshtein(s1, s2, allow_substring=False):
"""Return the Levenshtein distance between two strings.
The Levenshtein distance (a.k.a "edit difference") is the number of characters that need to be substituted,
inserted or deleted to transform s1 into s2.
Setting the `allow_substring` parameter to Tr... | [
"def",
"levenshtein",
"(",
"s1",
",",
"s2",
",",
"allow_substring",
"=",
"False",
")",
":",
"len1",
",",
"len2",
"=",
"len",
"(",
"s1",
")",
",",
"len",
"(",
"s2",
")",
"lev",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len1",
"+",
"1",
"... | Return the Levenshtein distance between two strings.
The Levenshtein distance (a.k.a "edit difference") is the number of characters that need to be substituted,
inserted or deleted to transform s1 into s2.
Setting the `allow_substring` parameter to True allows s1 to be a
substring of s2, so that, for ... | [
"Return",
"the",
"Levenshtein",
"distance",
"between",
"two",
"strings",
"."
] | python | train |
quantumlib/Cirq | cirq/google/sim/xmon_stepper.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/xmon_stepper.py#L36-L46 | def ensure_pool(func):
"""Decorator that ensures a pool is available for a stepper."""
def func_wrapper(*args, **kwargs):
if len(args) == 0 or not isinstance(args[0], Stepper):
raise Exception('@ensure_pool can only be used on Stepper methods.')
if args[0]._pool is None:
... | [
"def",
"ensure_pool",
"(",
"func",
")",
":",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"or",
"not",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"Stepper",
")",
":",
... | Decorator that ensures a pool is available for a stepper. | [
"Decorator",
"that",
"ensures",
"a",
"pool",
"is",
"available",
"for",
"a",
"stepper",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L78-L98 | def _context_menu_make(self, pos):
""" Reimplemented to return a custom context menu for images.
"""
format = self._control.cursorForPosition(pos).charFormat()
name = format.stringProperty(QtGui.QTextFormat.ImageName)
if name:
menu = QtGui.QMenu()
menu.ad... | [
"def",
"_context_menu_make",
"(",
"self",
",",
"pos",
")",
":",
"format",
"=",
"self",
".",
"_control",
".",
"cursorForPosition",
"(",
"pos",
")",
".",
"charFormat",
"(",
")",
"name",
"=",
"format",
".",
"stringProperty",
"(",
"QtGui",
".",
"QTextFormat",
... | Reimplemented to return a custom context menu for images. | [
"Reimplemented",
"to",
"return",
"a",
"custom",
"context",
"menu",
"for",
"images",
"."
] | python | test |
mapillary/mapillary_tools | mapillary_tools/geo.py | https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/geo.py#L191-L202 | def normalize_bearing(bearing, check_hex=False):
'''
Normalize bearing and convert from hex if
'''
if bearing > 360 and check_hex:
# fix negative value wrongly parsed in exifread
# -360 degree -> 4294966935 when converting from hex
bearing = bin(int(bearing))[2:]
bearing ... | [
"def",
"normalize_bearing",
"(",
"bearing",
",",
"check_hex",
"=",
"False",
")",
":",
"if",
"bearing",
">",
"360",
"and",
"check_hex",
":",
"# fix negative value wrongly parsed in exifread",
"# -360 degree -> 4294966935 when converting from hex",
"bearing",
"=",
"bin",
"(... | Normalize bearing and convert from hex if | [
"Normalize",
"bearing",
"and",
"convert",
"from",
"hex",
"if"
] | python | train |
Azure/azure-cosmos-python | azure/cosmos/execution_context/document_producer.py | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/execution_context/document_producer.py#L76-L88 | def next(self):
"""
:return: The next result item.
:rtype: dict
:raises StopIteration: If there is no more result.
"""
if self._cur_item is not None:
res = self._cur_item
self._cur_item = None
return res
r... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cur_item",
"is",
"not",
"None",
":",
"res",
"=",
"self",
".",
"_cur_item",
"self",
".",
"_cur_item",
"=",
"None",
"return",
"res",
"return",
"next",
"(",
"self",
".",
"_ex_context",
")"
] | :return: The next result item.
:rtype: dict
:raises StopIteration: If there is no more result. | [
":",
"return",
":",
"The",
"next",
"result",
"item",
".",
":",
"rtype",
":",
"dict",
":",
"raises",
"StopIteration",
":",
"If",
"there",
"is",
"no",
"more",
"result",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/urllib3/util/retry.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/retry.py#L329-L402 | def increment(self, method=None, url=None, response=None, error=None,
_pool=None, _stacktrace=None):
""" Return a new Retry object with incremented retry counters.
:param response: A response object, or None, if the server did not
return a response.
:type response:... | [
"def",
"increment",
"(",
"self",
",",
"method",
"=",
"None",
",",
"url",
"=",
"None",
",",
"response",
"=",
"None",
",",
"error",
"=",
"None",
",",
"_pool",
"=",
"None",
",",
"_stacktrace",
"=",
"None",
")",
":",
"if",
"self",
".",
"total",
"is",
... | Return a new Retry object with incremented retry counters.
:param response: A response object, or None, if the server did not
return a response.
:type response: :class:`~urllib3.response.HTTPResponse`
:param Exception error: An error encountered during the request, or
No... | [
"Return",
"a",
"new",
"Retry",
"object",
"with",
"incremented",
"retry",
"counters",
"."
] | python | train |
pyviz/holoviews | holoviews/plotting/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/util.py#L282-L306 | def get_nested_plot_frame(obj, key_map, cached=False):
"""Extracts a single frame from a nested object.
Replaces any HoloMap or DynamicMap in the nested data structure,
with the item corresponding to the supplied key.
Args:
obj: Nested Dimensioned object
key_map: Dictionary mapping bet... | [
"def",
"get_nested_plot_frame",
"(",
"obj",
",",
"key_map",
",",
"cached",
"=",
"False",
")",
":",
"clone",
"=",
"obj",
".",
"map",
"(",
"lambda",
"x",
":",
"x",
")",
"# Ensure that DynamicMaps in the cloned frame have",
"# identical callback inputs to allow memoizati... | Extracts a single frame from a nested object.
Replaces any HoloMap or DynamicMap in the nested data structure,
with the item corresponding to the supplied key.
Args:
obj: Nested Dimensioned object
key_map: Dictionary mapping between dimensions and key value
cached: Whether to allow... | [
"Extracts",
"a",
"single",
"frame",
"from",
"a",
"nested",
"object",
"."
] | python | train |
inasafe/inasafe | safe/messaging/item/text.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/text.py#L151-L170 | def to_html(self):
"""Render as html
Args:
None
Returns:
Str the html representation
Raises:
Errors are propagated
"""
icon = self.html_icon()
attributes = self.html_attributes()
# Deal with long file names that preve... | [
"def",
"to_html",
"(",
"self",
")",
":",
"icon",
"=",
"self",
".",
"html_icon",
"(",
")",
"attributes",
"=",
"self",
".",
"html_attributes",
"(",
")",
"# Deal with long file names that prevent wrapping",
"wrappable_text",
"=",
"self",
".",
"to_text",
"(",
")",
... | Render as html
Args:
None
Returns:
Str the html representation
Raises:
Errors are propagated | [
"Render",
"as",
"html"
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_tab_layout.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_tab_layout.py#L90-L98 | def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidTabLayout, self).init_widget()
w = self.widget
w.addOnTabSelectedListener(w.getId())
w.onTabSelected.connect(self.on_tab_selected)
w.onTabUnselected.connect(self.on_tab_unselected) | [
"def",
"init_widget",
"(",
"self",
")",
":",
"super",
"(",
"AndroidTabLayout",
",",
"self",
")",
".",
"init_widget",
"(",
")",
"w",
"=",
"self",
".",
"widget",
"w",
".",
"addOnTabSelectedListener",
"(",
"w",
".",
"getId",
"(",
")",
")",
"w",
".",
"on... | Initialize the underlying widget. | [
"Initialize",
"the",
"underlying",
"widget",
"."
] | python | train |
carlcarl/grabflickr | grabflickr/grabflickr.py | https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L53-L69 | def enter_api_key(parser=None):
"""Prompt for API key and secret
Then write them to CONFIG_PATH(Default: ~/.grabflickr.conf)
:param parser: Config parser
:type parser: SafeConfigParser
"""
if parser is None:
parser = SafeConfigParser()
parser.add_section('flickr')
global api_key... | [
"def",
"enter_api_key",
"(",
"parser",
"=",
"None",
")",
":",
"if",
"parser",
"is",
"None",
":",
"parser",
"=",
"SafeConfigParser",
"(",
")",
"parser",
".",
"add_section",
"(",
"'flickr'",
")",
"global",
"api_key",
",",
"api_secret",
"api_key",
"=",
"raw_i... | Prompt for API key and secret
Then write them to CONFIG_PATH(Default: ~/.grabflickr.conf)
:param parser: Config parser
:type parser: SafeConfigParser | [
"Prompt",
"for",
"API",
"key",
"and",
"secret",
"Then",
"write",
"them",
"to",
"CONFIG_PATH",
"(",
"Default",
":",
"~",
"/",
".",
"grabflickr",
".",
"conf",
")"
] | python | train |
googleapis/dialogflow-python-client-v2 | samples/knowledge_base_management.py | https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L74-L89 | def get_knowledge_base(project_id, knowledge_base_id):
"""Gets a specific Knowledge base.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base."""
import dialogflow_v2beta1 as dialogflow
client = dialogflow.KnowledgeBasesClient()
knowl... | [
"def",
"get_knowledge_base",
"(",
"project_id",
",",
"knowledge_base_id",
")",
":",
"import",
"dialogflow_v2beta1",
"as",
"dialogflow",
"client",
"=",
"dialogflow",
".",
"KnowledgeBasesClient",
"(",
")",
"knowledge_base_path",
"=",
"client",
".",
"knowledge_base_path",
... | Gets a specific Knowledge base.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base. | [
"Gets",
"a",
"specific",
"Knowledge",
"base",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.