repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
openstack/horizon | openstack_dashboard/api/neutron.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L2025-L2036 | def rbac_policy_update(request, policy_id, **kwargs):
"""Update a RBAC Policy.
:param request: request context
:param policy_id: target policy id
:param target_tenant: target tenant of the policy
:return: RBACPolicy object
"""
body = {'rbac_policy': kwargs}
rbac_policy = neutronclient(r... | [
"def",
"rbac_policy_update",
"(",
"request",
",",
"policy_id",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"{",
"'rbac_policy'",
":",
"kwargs",
"}",
"rbac_policy",
"=",
"neutronclient",
"(",
"request",
")",
".",
"update_rbac_policy",
"(",
"policy_id",
",... | Update a RBAC Policy.
:param request: request context
:param policy_id: target policy id
:param target_tenant: target tenant of the policy
:return: RBACPolicy object | [
"Update",
"a",
"RBAC",
"Policy",
"."
] | python | train | 35 |
jmbhughes/suvi-trainer | scripts/fetch_hek_labeled.py | https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/scripts/fetch_hek_labeled.py#L31-L42 | def query_hek(time, time_window=1):
"""
requests hek responses for a given time
:param time: datetime object
:param time_window: how far in hours on either side of the input time to look for results
:return: hek response list
"""
hek_client = hek.HEKClient()
start_time = time - timedelta... | [
"def",
"query_hek",
"(",
"time",
",",
"time_window",
"=",
"1",
")",
":",
"hek_client",
"=",
"hek",
".",
"HEKClient",
"(",
")",
"start_time",
"=",
"time",
"-",
"timedelta",
"(",
"hours",
"=",
"time_window",
")",
"end_time",
"=",
"time",
"+",
"timedelta",
... | requests hek responses for a given time
:param time: datetime object
:param time_window: how far in hours on either side of the input time to look for results
:return: hek response list | [
"requests",
"hek",
"responses",
"for",
"a",
"given",
"time",
":",
"param",
"time",
":",
"datetime",
"object",
":",
"param",
"time_window",
":",
"how",
"far",
"in",
"hours",
"on",
"either",
"side",
"of",
"the",
"input",
"time",
"to",
"look",
"for",
"resul... | python | train | 39.25 |
wandb/client | wandb/vendor/prompt_toolkit/styles/from_dict.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/styles/from_dict.py#L42-L128 | def style_from_dict(style_dict, include_defaults=True):
"""
Create a ``Style`` instance from a dictionary or other mapping.
The dictionary is equivalent to the ``Style.styles`` dictionary from
pygments, with a few additions: it supports 'reverse' and 'blink'.
Usage::
style_from_dict({
... | [
"def",
"style_from_dict",
"(",
"style_dict",
",",
"include_defaults",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"style_dict",
",",
"Mapping",
")",
"if",
"include_defaults",
":",
"s2",
"=",
"{",
"}",
"s2",
".",
"update",
"(",
"DEFAULT_STYLE_EXTENSIONS... | Create a ``Style`` instance from a dictionary or other mapping.
The dictionary is equivalent to the ``Style.styles`` dictionary from
pygments, with a few additions: it supports 'reverse' and 'blink'.
Usage::
style_from_dict({
Token: '#ff0000 bold underline',
Token.Title: '... | [
"Create",
"a",
"Style",
"instance",
"from",
"a",
"dictionary",
"or",
"other",
"mapping",
"."
] | python | train | 32.724138 |
facetoe/zenpy | zenpy/lib/api.py | https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api.py#L1165-L1179 | def merge(self, target, source,
target_comment=None, source_comment=None):
"""
Merge the ticket(s) or ticket ID(s) in source into the target ticket.
:param target: ticket id or object to merge tickets into
:param source: ticket id, object or list of tickets or ids to merge... | [
"def",
"merge",
"(",
"self",
",",
"target",
",",
"source",
",",
"target_comment",
"=",
"None",
",",
"source_comment",
"=",
"None",
")",
":",
"return",
"TicketMergeRequest",
"(",
"self",
")",
".",
"post",
"(",
"target",
",",
"source",
",",
"target_comment",... | Merge the ticket(s) or ticket ID(s) in source into the target ticket.
:param target: ticket id or object to merge tickets into
:param source: ticket id, object or list of tickets or ids to merge into target
:param source_comment: optional comment for the source ticket(s)
:param target_c... | [
"Merge",
"the",
"ticket",
"(",
"s",
")",
"or",
"ticket",
"ID",
"(",
"s",
")",
"in",
"source",
"into",
"the",
"target",
"ticket",
"."
] | python | train | 48.2 |
djangonauts/django-rest-framework-gis | rest_framework_gis/fields.py | https://github.com/djangonauts/django-rest-framework-gis/blob/7430d6b1ca480222c1b837748f4c60ea10c85f22/rest_framework_gis/fields.py#L65-L73 | def _recursive_round(self, value, precision):
"""
Round all numbers within an array or nested arrays
value: number or nested array of numbers
precision: integer valueue of number of decimals to keep
"""
if hasattr(value, '__iter__'):
return tuple(self.... | [
"def",
"_recursive_round",
"(",
"self",
",",
"value",
",",
"precision",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'__iter__'",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"_recursive_round",
"(",
"v",
",",
"precision",
")",
"for",
"v",
"in",
"v... | Round all numbers within an array or nested arrays
value: number or nested array of numbers
precision: integer valueue of number of decimals to keep | [
"Round",
"all",
"numbers",
"within",
"an",
"array",
"or",
"nested",
"arrays",
"value",
":",
"number",
"or",
"nested",
"array",
"of",
"numbers",
"precision",
":",
"integer",
"valueue",
"of",
"number",
"of",
"decimals",
"to",
"keep"
] | python | train | 44.111111 |
astroswego/plotypus | src/plotypus/periodogram.py | https://github.com/astroswego/plotypus/blob/b1162194ca1d4f6c00e79afe3e6fb40f0eaffcb9/src/plotypus/periodogram.py#L20-L51 | def Lomb_Scargle(data, precision, min_period, max_period, period_jobs=1):
"""
Returns the period of *data* according to the
`Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_.
**Parameters**
data : array-like, shape = [n... | [
"def",
"Lomb_Scargle",
"(",
"data",
",",
"precision",
",",
"min_period",
",",
"max_period",
",",
"period_jobs",
"=",
"1",
")",
":",
"time",
",",
"mags",
",",
"",
"*",
"err",
"=",
"data",
".",
"T",
"scaled_mags",
"=",
"(",
"mags",
"-",
"mags",
".",
... | Returns the period of *data* according to the
`Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_.
**Parameters**
data : array-like, shape = [n_samples, 2] or [n_samples, 3]
Array containing columns *time*, *mag*, and (op... | [
"Returns",
"the",
"period",
"of",
"*",
"data",
"*",
"according",
"to",
"the",
"Lomb",
"-",
"Scargle",
"periodogram",
"<https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Least",
"-",
"squares_spectral_analysis#The_Lomb",
".",
"E2",
"... | python | train | 37.625 |
contentful/contentful-management.py | contentful_management/resource.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/resource.py#L290-L297 | def to_json(self):
"""
Returns the JSON Representation of the resource.
"""
result = super(FieldsResource, self).to_json()
result['fields'] = self.fields_with_locales()
return result | [
"def",
"to_json",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
"FieldsResource",
",",
"self",
")",
".",
"to_json",
"(",
")",
"result",
"[",
"'fields'",
"]",
"=",
"self",
".",
"fields_with_locales",
"(",
")",
"return",
"result"
] | Returns the JSON Representation of the resource. | [
"Returns",
"the",
"JSON",
"Representation",
"of",
"the",
"resource",
"."
] | python | train | 28 |
jobovy/galpy | galpy/df/streamdf.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L2303-L2402 | def _approxaA(self,R,vR,vT,z,vz,phi,interp=True,cindx=None):
"""
NAME:
_approxaA
PURPOSE:
return action-angle coordinates for a point based on the linear
approximation around the stream track
INPUT:
R,vR,vT,z,vz,phi - phase-space coordinates o... | [
"def",
"_approxaA",
"(",
"self",
",",
"R",
",",
"vR",
",",
"vT",
",",
"z",
",",
"vz",
",",
"phi",
",",
"interp",
"=",
"True",
",",
"cindx",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"R",
",",
"(",
"int",
",",
"float",
",",
"numpy",
".",... | NAME:
_approxaA
PURPOSE:
return action-angle coordinates for a point based on the linear
approximation around the stream track
INPUT:
R,vR,vT,z,vz,phi - phase-space coordinates of the given point
interp= (True), if True, use the interpolated track
... | [
"NAME",
":",
"_approxaA",
"PURPOSE",
":",
"return",
"action",
"-",
"angle",
"coordinates",
"for",
"a",
"point",
"based",
"on",
"the",
"linear",
"approximation",
"around",
"the",
"stream",
"track",
"INPUT",
":",
"R",
"vR",
"vT",
"z",
"vz",
"phi",
"-",
"ph... | python | train | 49.25 |
Grunny/zap-cli | zapcli/helpers.py | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/helpers.py#L58-L70 | def validate_regex(ctx, param, value):
"""
Validate that a provided regex compiles.
"""
if not value:
return None
try:
re.compile(value)
except re.error:
raise click.BadParameter('Invalid regex "{0}" provided'.format(value))
return value | [
"def",
"validate_regex",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"try",
":",
"re",
".",
"compile",
"(",
"value",
")",
"except",
"re",
".",
"error",
":",
"raise",
"click",
".",
"BadParameter",
"("... | Validate that a provided regex compiles. | [
"Validate",
"that",
"a",
"provided",
"regex",
"compiles",
"."
] | python | train | 21.461538 |
wandb/client | wandb/apis/public.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/apis/public.py#L143-L158 | def runs(self, path="", filters={}, order="-created_at", per_page=None):
"""Return a set of runs from a project that match the filters provided.
You can filter by config.*, summary.*, state, username, createdAt, etc.
The filters use the same query language as MongoDB:
https://docs.mong... | [
"def",
"runs",
"(",
"self",
",",
"path",
"=",
"\"\"",
",",
"filters",
"=",
"{",
"}",
",",
"order",
"=",
"\"-created_at\"",
",",
"per_page",
"=",
"None",
")",
":",
"username",
",",
"project",
",",
"run",
"=",
"self",
".",
"_parse_path",
"(",
"path",
... | Return a set of runs from a project that match the filters provided.
You can filter by config.*, summary.*, state, username, createdAt, etc.
The filters use the same query language as MongoDB:
https://docs.mongodb.com/manual/reference/operator/query
Order can be created_at, heartbeat_... | [
"Return",
"a",
"set",
"of",
"runs",
"from",
"a",
"project",
"that",
"match",
"the",
"filters",
"provided",
".",
"You",
"can",
"filter",
"by",
"config",
".",
"*",
"summary",
".",
"*",
"state",
"username",
"createdAt",
"etc",
"."
] | python | train | 56 |
tanghaibao/jcvi | jcvi/projects/str.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L1410-L1450 | def mergebam(args):
"""
%prog mergebam dir1 homo_outdir
or
%prog mergebam dir1 dir2/20.bam het_outdir
Merge sets of BAMs to make diploid. Two modes:
- Homozygous mode: pair-up the bams in the two folders and merge
- Heterozygous mode: pair the bams in first folder with a particular bam
... | [
"def",
"mergebam",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mergebam",
".",
"__doc__",
")",
"p",
".",
"set_cpus",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"not",
"i... | %prog mergebam dir1 homo_outdir
or
%prog mergebam dir1 dir2/20.bam het_outdir
Merge sets of BAMs to make diploid. Two modes:
- Homozygous mode: pair-up the bams in the two folders and merge
- Heterozygous mode: pair the bams in first folder with a particular bam | [
"%prog",
"mergebam",
"dir1",
"homo_outdir",
"or",
"%prog",
"mergebam",
"dir1",
"dir2",
"/",
"20",
".",
"bam",
"het_outdir"
] | python | train | 35.02439 |
eqcorrscan/EQcorrscan | eqcorrscan/core/match_filter.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/core/match_filter.py#L2466-L2656 | def detect(self, stream, threshold, threshold_type, trig_int, plotvar,
daylong=False, parallel_process=True, xcorr_func=None,
concurrency=None, cores=None, ignore_length=False,
group_size=None, overlap="calculate", debug=0,
full_peaks=False, save_progress=Fals... | [
"def",
"detect",
"(",
"self",
",",
"stream",
",",
"threshold",
",",
"threshold_type",
",",
"trig_int",
",",
"plotvar",
",",
"daylong",
"=",
"False",
",",
"parallel_process",
"=",
"True",
",",
"xcorr_func",
"=",
"None",
",",
"concurrency",
"=",
"None",
",",... | Detect using a Tribe of templates within a continuous stream.
:type stream: `obspy.core.stream.Stream`
:param stream: Continuous data to detect within using the Template.
:type threshold: float
:param threshold:
Threshold level, if using `threshold_type='MAD'` then this will... | [
"Detect",
"using",
"a",
"Tribe",
"of",
"templates",
"within",
"a",
"continuous",
"stream",
"."
] | python | train | 46.204188 |
shin-/dockerpy-creds | dockerpycreds/utils.py | https://github.com/shin-/dockerpy-creds/blob/9c0b66d2e445a838e1518f2c3273df7ddc7ec0d4/dockerpycreds/utils.py#L6-L29 | def find_executable(executable, path=None):
"""
As distutils.spawn.find_executable, but on Windows, look up
every extension declared in PATHEXT instead of just `.exe`
"""
if sys.platform != 'win32':
return distutils.spawn.find_executable(executable, path)
if path is None:
path =... | [
"def",
"find_executable",
"(",
"executable",
",",
"path",
"=",
"None",
")",
":",
"if",
"sys",
".",
"platform",
"!=",
"'win32'",
":",
"return",
"distutils",
".",
"spawn",
".",
"find_executable",
"(",
"executable",
",",
"path",
")",
"if",
"path",
"is",
"No... | As distutils.spawn.find_executable, but on Windows, look up
every extension declared in PATHEXT instead of just `.exe` | [
"As",
"distutils",
".",
"spawn",
".",
"find_executable",
"but",
"on",
"Windows",
"look",
"up",
"every",
"extension",
"declared",
"in",
"PATHEXT",
"instead",
"of",
"just",
".",
"exe"
] | python | train | 30.666667 |
PatrikValkovic/grammpy | grammpy/transforms/Traversing.py | https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/transforms/Traversing.py#L143-L209 | def print(root):
# type: (Union[Nonterminal,Terminal,Rule])-> str
"""
Transform the parsed tree to the string. Expects tree like structure.
You can see example output below.
(R)SplitRules26
|--(N)Iterate
| `--(R)SplitRules30
| `--(N)Symb
| ... | [
"def",
"print",
"(",
"root",
")",
":",
"# type: (Union[Nonterminal,Terminal,Rule])-> str",
"# print the part before the element",
"def",
"print_before",
"(",
"previous",
"=",
"0",
",",
"defined",
"=",
"None",
",",
"is_last",
"=",
"False",
")",
":",
"defined",
"=",
... | Transform the parsed tree to the string. Expects tree like structure.
You can see example output below.
(R)SplitRules26
|--(N)Iterate
| `--(R)SplitRules30
| `--(N)Symb
| `--(R)SplitRules4
| `--(T)e
`--(N)Concat
`--(R)Split... | [
"Transform",
"the",
"parsed",
"tree",
"to",
"the",
"string",
".",
"Expects",
"tree",
"like",
"structure",
".",
"You",
"can",
"see",
"example",
"output",
"below",
"."
] | python | train | 41.313433 |
MisterY/asset-allocation | asset_allocation/model.py | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L67-L77 | def fullname(self):
""" includes the full path with parent names """
prefix = ""
if self.parent:
if self.parent.fullname:
prefix = self.parent.fullname + ":"
else:
# Only the root does not have a parent. In that case we also don't need a name.
... | [
"def",
"fullname",
"(",
"self",
")",
":",
"prefix",
"=",
"\"\"",
"if",
"self",
".",
"parent",
":",
"if",
"self",
".",
"parent",
".",
"fullname",
":",
"prefix",
"=",
"self",
".",
"parent",
".",
"fullname",
"+",
"\":\"",
"else",
":",
"# Only the root doe... | includes the full path with parent names | [
"includes",
"the",
"full",
"path",
"with",
"parent",
"names"
] | python | train | 32.909091 |
quantmind/pulsar | pulsar/utils/string.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/string.py#L10-L18 | def to_bytes(s, encoding=None, errors=None):
'''Convert *s* into bytes'''
if not isinstance(s, bytes):
return ('%s' % s).encode(encoding or 'utf-8', errors or 'strict')
elif not encoding or encoding == 'utf-8':
return s
else:
d = s.decode('utf-8')
return d.encode(encoding... | [
"def",
"to_bytes",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"return",
"(",
"'%s'",
"%",
"s",
")",
".",
"encode",
"(",
"encoding",
"or",
"'utf-8'",
"... | Convert *s* into bytes | [
"Convert",
"*",
"s",
"*",
"into",
"bytes"
] | python | train | 37 |
zzyztyy/pyIGRF | pyIGRF/calculate.py | https://github.com/zzyztyy/pyIGRF/blob/3369ccafec34d18ca2c57f48b867cb2417078866/pyIGRF/calculate.py#L39-L208 | def igrf12syn(isv, date, itype, alt, lat, elong):
"""
This is a synthesis routine for the 12th generation IGRF as agreed
in December 2014 by IAGA Working Group V-MOD. It is valid 1900.0 to
2020.0 inclusive. Values for dates from 1945.0 to 2010.0 inclusive are
definitive, otherwise they are non-d... | [
"def",
"igrf12syn",
"(",
"isv",
",",
"date",
",",
"itype",
",",
"alt",
",",
"lat",
",",
"elong",
")",
":",
"p",
",",
"q",
",",
"cl",
",",
"sl",
"=",
"[",
"0.",
"]",
"*",
"105",
",",
"[",
"0.",
"]",
"*",
"105",
",",
"[",
"0.",
"]",
"*",
... | This is a synthesis routine for the 12th generation IGRF as agreed
in December 2014 by IAGA Working Group V-MOD. It is valid 1900.0 to
2020.0 inclusive. Values for dates from 1945.0 to 2010.0 inclusive are
definitive, otherwise they are non-definitive.
INPUT
isv = 0 if main-field values are req... | [
"This",
"is",
"a",
"synthesis",
"routine",
"for",
"the",
"12th",
"generation",
"IGRF",
"as",
"agreed",
"in",
"December",
"2014",
"by",
"IAGA",
"Working",
"Group",
"V",
"-",
"MOD",
".",
"It",
"is",
"valid",
"1900",
".",
"0",
"to",
"2020",
".",
"0",
"i... | python | train | 35.511765 |
OnroerendErfgoed/language-tags | language_tags/Subtag.py | https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/Subtag.py#L101-L112 | def format(self):
"""
Get the subtag code conventional format according to RFC 5646 section 2.1.1.
:return: string -- subtag code conventional format.
"""
subtag = self.data['subtag']
if self.data['type'] == 'region':
return subtag.upper()
if self.dat... | [
"def",
"format",
"(",
"self",
")",
":",
"subtag",
"=",
"self",
".",
"data",
"[",
"'subtag'",
"]",
"if",
"self",
".",
"data",
"[",
"'type'",
"]",
"==",
"'region'",
":",
"return",
"subtag",
".",
"upper",
"(",
")",
"if",
"self",
".",
"data",
"[",
"'... | Get the subtag code conventional format according to RFC 5646 section 2.1.1.
:return: string -- subtag code conventional format. | [
"Get",
"the",
"subtag",
"code",
"conventional",
"format",
"according",
"to",
"RFC",
"5646",
"section",
"2",
".",
"1",
".",
"1",
"."
] | python | train | 32.666667 |
6809/MC6809 | MC6809/components/mc6809_stack.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_stack.py#L51-L65 | def pull_byte(self, stack_pointer):
""" pulled a byte from stack """
addr = stack_pointer.value
byte = self.memory.read_byte(addr)
# log.info(
# log.error(
# "%x|\tpull $%x from %s stack at $%x\t|%s",
# self.last_op_address, byte, stack_pointer.name, addr,
# ... | [
"def",
"pull_byte",
"(",
"self",
",",
"stack_pointer",
")",
":",
"addr",
"=",
"stack_pointer",
".",
"value",
"byte",
"=",
"self",
".",
"memory",
".",
"read_byte",
"(",
"addr",
")",
"# log.info(",
"# log.error(",
"# \"%x|\\tpull $%x from %s ... | pulled a byte from stack | [
"pulled",
"a",
"byte",
"from",
"stack"
] | python | train | 32.333333 |
dourvaris/nano-python | src/nano/rpc.py | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L2432-L2457 | def wallet_frontiers(self, wallet):
"""
Returns a list of pairs of account and block hash representing the
head block starting for accounts from **wallet**
:param wallet: Wallet to return frontiers for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
... | [
"def",
"wallet_frontiers",
"(",
"self",
",",
"wallet",
")",
":",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"payload",
"=",
"{",
"\"wallet\"",
":",
"wallet",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'wallet_fro... | Returns a list of pairs of account and block hash representing the
head block starting for accounts from **wallet**
:param wallet: Wallet to return frontiers for
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.wallet_frontiers(
... wallet="000D1B... | [
"Returns",
"a",
"list",
"of",
"pairs",
"of",
"account",
"and",
"block",
"hash",
"representing",
"the",
"head",
"block",
"starting",
"for",
"accounts",
"from",
"**",
"wallet",
"**"
] | python | train | 30.653846 |
honzajavorek/redis-collections | redis_collections/sortedsets.py | https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L472-L526 | def places_within_radius(
self, place=None, latitude=None, longitude=None, radius=0, **kwargs
):
"""
Return descriptions of the places stored in the collection that are
within the circle specified by the given location and radius.
A list of dicts will be returned.
Th... | [
"def",
"places_within_radius",
"(",
"self",
",",
"place",
"=",
"None",
",",
"latitude",
"=",
"None",
",",
"longitude",
"=",
"None",
",",
"radius",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'withdist'",
"]",
"=",
"True",
"kwargs",
"... | Return descriptions of the places stored in the collection that are
within the circle specified by the given location and radius.
A list of dicts will be returned.
The center of the circle can be specified by the identifier of another
place in the collection with the *place* keyword arg... | [
"Return",
"descriptions",
"of",
"the",
"places",
"stored",
"in",
"the",
"collection",
"that",
"are",
"within",
"the",
"circle",
"specified",
"by",
"the",
"given",
"location",
"and",
"radius",
".",
"A",
"list",
"of",
"dicts",
"will",
"be",
"returned",
"."
] | python | train | 35.036364 |
pallets/werkzeug | src/werkzeug/datastructures.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2325-L2331 | def make_content_range(self, length):
"""Creates a :class:`~werkzeug.datastructures.ContentRange` object
from the current range and given content length.
"""
rng = self.range_for_length(length)
if rng is not None:
return ContentRange(self.units, rng[0], rng[1], length... | [
"def",
"make_content_range",
"(",
"self",
",",
"length",
")",
":",
"rng",
"=",
"self",
".",
"range_for_length",
"(",
"length",
")",
"if",
"rng",
"is",
"not",
"None",
":",
"return",
"ContentRange",
"(",
"self",
".",
"units",
",",
"rng",
"[",
"0",
"]",
... | Creates a :class:`~werkzeug.datastructures.ContentRange` object
from the current range and given content length. | [
"Creates",
"a",
":",
"class",
":",
"~werkzeug",
".",
"datastructures",
".",
"ContentRange",
"object",
"from",
"the",
"current",
"range",
"and",
"given",
"content",
"length",
"."
] | python | train | 45 |
radical-cybertools/radical.entk | src/radical/entk/pipeline/pipeline.py | https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/pipeline/pipeline.py#L300-L313 | def _increment_stage(self):
"""
Purpose: Increment stage pointer. Also check if Pipeline has completed.
"""
try:
if self._cur_stage < self._stage_count:
self._cur_stage += 1
else:
self._completed_flag.set()
except Excepti... | [
"def",
"_increment_stage",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_cur_stage",
"<",
"self",
".",
"_stage_count",
":",
"self",
".",
"_cur_stage",
"+=",
"1",
"else",
":",
"self",
".",
"_completed_flag",
".",
"set",
"(",
")",
"except",
"Ex... | Purpose: Increment stage pointer. Also check if Pipeline has completed. | [
"Purpose",
":",
"Increment",
"stage",
"pointer",
".",
"Also",
"check",
"if",
"Pipeline",
"has",
"completed",
"."
] | python | train | 25.071429 |
decryptus/sonicprobe | sonicprobe/libs/daemonize.py | https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/daemonize.py#L142-L167 | def lock_pidfile_or_die(pidfile):
"""
@pidfile:
must be a writable path
Exceptions are logged.
Returns the PID.
"""
pid = os.getpid()
try:
remove_if_stale_pidfile(pidfile)
pid_write_file = pidfile + '.' + str(pid)
fpid = open(pid_write_file, 'w')
try... | [
"def",
"lock_pidfile_or_die",
"(",
"pidfile",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"try",
":",
"remove_if_stale_pidfile",
"(",
"pidfile",
")",
"pid_write_file",
"=",
"pidfile",
"+",
"'.'",
"+",
"str",
"(",
"pid",
")",
"fpid",
"=",
"open",... | @pidfile:
must be a writable path
Exceptions are logged.
Returns the PID. | [
"@pidfile",
":",
"must",
"be",
"a",
"writable",
"path"
] | python | train | 23.5 |
xym-tool/xym | xym/xym.py | https://github.com/xym-tool/xym/blob/48984e6bd41595df8f383e6dc7e6eedfecc96898/xym/xym.py#L332-L343 | def debug_print_strip_msg(self, i, line):
"""
Debug print indicating that an empty line is being skipped
:param i: The line number of the line that is being currently parsed
:param line: the parsed line
:return: None
"""
if self.debug_level == 2:
print... | [
"def",
"debug_print_strip_msg",
"(",
"self",
",",
"i",
",",
"line",
")",
":",
"if",
"self",
".",
"debug_level",
"==",
"2",
":",
"print",
"(",
"\" Stripping Line %d: '%s'\"",
"%",
"(",
"i",
"+",
"1",
",",
"line",
".",
"rstrip",
"(",
"' \\r\\n\\t\\f'",
... | Debug print indicating that an empty line is being skipped
:param i: The line number of the line that is being currently parsed
:param line: the parsed line
:return: None | [
"Debug",
"print",
"indicating",
"that",
"an",
"empty",
"line",
"is",
"being",
"skipped",
":",
"param",
"i",
":",
"The",
"line",
"number",
"of",
"the",
"line",
"that",
"is",
"being",
"currently",
"parsed",
":",
"param",
"line",
":",
"the",
"parsed",
"line... | python | train | 41.083333 |
MicroPyramid/forex-python | forex_python/bitcoin.py | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L56-L73 | def get_previous_price_list(self, currency, start_date, end_date):
"""
Get List of prices between two dates
"""
start = start_date.strftime('%Y-%m-%d')
end = end_date.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
... | [
"def",
"get_previous_price_list",
"(",
"self",
",",
"currency",
",",
"start_date",
",",
"end_date",
")",
":",
"start",
"=",
"start_date",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"end",
"=",
"end_date",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"url",
"=",
... | Get List of prices between two dates | [
"Get",
"List",
"of",
"prices",
"between",
"two",
"dates"
] | python | train | 35 |
digidotcom/python-devicecloud | devicecloud/devicecore.py | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/devicecore.py#L48-L83 | def get_devices(self, condition=None, page_size=1000):
"""Iterates over each :class:`Device` for this device cloud account
Examples::
# get a list of all devices
all_devices = list(dc.devicecore.get_devices())
# build a mapping of devices by their vendor id using a... | [
"def",
"get_devices",
"(",
"self",
",",
"condition",
"=",
"None",
",",
"page_size",
"=",
"1000",
")",
":",
"condition",
"=",
"validate_type",
"(",
"condition",
",",
"type",
"(",
"None",
")",
",",
"Expression",
",",
"*",
"six",
".",
"string_types",
")",
... | Iterates over each :class:`Device` for this device cloud account
Examples::
# get a list of all devices
all_devices = list(dc.devicecore.get_devices())
# build a mapping of devices by their vendor id using a
# dict comprehension
devices = dc.devicec... | [
"Iterates",
"over",
"each",
":",
"class",
":",
"Device",
"for",
"this",
"device",
"cloud",
"account"
] | python | train | 45.638889 |
BD2KGenomics/toil-scripts | src/toil_scripts/bwa_alignment/bwa_alignment.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/bwa_alignment/bwa_alignment.py#L61-L96 | def download_sample_and_align(job, sample, inputs, ids):
"""
Downloads the sample and runs BWA-kit
:param JobFunctionWrappingJob job: Passed by Toil automatically
:param tuple(str, list) sample: UUID and URLS for sample
:param Namespace inputs: Contains input arguments
:param dict ids: FileStor... | [
"def",
"download_sample_and_align",
"(",
"job",
",",
"sample",
",",
"inputs",
",",
"ids",
")",
":",
"uuid",
",",
"urls",
"=",
"sample",
"r1_url",
",",
"r2_url",
"=",
"urls",
"if",
"len",
"(",
"urls",
")",
"==",
"2",
"else",
"(",
"urls",
"[",
"0",
"... | Downloads the sample and runs BWA-kit
:param JobFunctionWrappingJob job: Passed by Toil automatically
:param tuple(str, list) sample: UUID and URLS for sample
:param Namespace inputs: Contains input arguments
:param dict ids: FileStore IDs for shared inputs | [
"Downloads",
"the",
"sample",
"and",
"runs",
"BWA",
"-",
"kit"
] | python | train | 54.805556 |
Data-Mechanics/geoql | geoql/geoql.py | https://github.com/Data-Mechanics/geoql/blob/c6184e1734c76a259855d6282e919614839a767e/geoql/geoql.py#L51-L61 | def features_properties_null_remove(obj):
"""
Remove any properties of features in the collection that have
entries mapping to a null (i.e., None) value
"""
features = obj['features']
for i in tqdm(range(len(features))):
if 'properties' in features[i]:
properties = features[... | [
"def",
"features_properties_null_remove",
"(",
"obj",
")",
":",
"features",
"=",
"obj",
"[",
"'features'",
"]",
"for",
"i",
"in",
"tqdm",
"(",
"range",
"(",
"len",
"(",
"features",
")",
")",
")",
":",
"if",
"'properties'",
"in",
"features",
"[",
"i",
"... | Remove any properties of features in the collection that have
entries mapping to a null (i.e., None) value | [
"Remove",
"any",
"properties",
"of",
"features",
"in",
"the",
"collection",
"that",
"have",
"entries",
"mapping",
"to",
"a",
"null",
"(",
"i",
".",
"e",
".",
"None",
")",
"value"
] | python | train | 40.727273 |
EventTeam/beliefs | src/beliefs/beliefstate.py | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L270-L321 | def merge(self, keypath, value, op='set'):
"""
First gets the cell at BeliefState's keypath, or creates a new cell
from the first target that has that keypath (This could mess up if the
member its copying from has a different Cell or domain for that keypath.)
Second, this merges... | [
"def",
"merge",
"(",
"self",
",",
"keypath",
",",
"value",
",",
"op",
"=",
"'set'",
")",
":",
"negated",
"=",
"False",
"keypath",
"=",
"keypath",
"[",
":",
"]",
"# copy it ",
"if",
"keypath",
"[",
"0",
"]",
"==",
"'target'",
":",
"# only pull negated i... | First gets the cell at BeliefState's keypath, or creates a new cell
from the first target that has that keypath (This could mess up if the
member its copying from has a different Cell or domain for that keypath.)
Second, this merges that cell with the value | [
"First",
"gets",
"the",
"cell",
"at",
"BeliefState",
"s",
"keypath",
"or",
"creates",
"a",
"new",
"cell",
"from",
"the",
"first",
"target",
"that",
"has",
"that",
"keypath",
"(",
"This",
"could",
"mess",
"up",
"if",
"the",
"member",
"its",
"copying",
"fr... | python | train | 45.807692 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/sql_io.py | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/sql_io.py#L55-L97 | def excel_to_sql(excel_file_path, engine,
read_excel_kwargs=None,
to_generic_type_kwargs=None,
to_sql_kwargs=None):
"""Create a database from excel.
:param read_excel_kwargs: dict, arguments for ``pandas.read_excel`` method.
example: ``{"employee": {"ski... | [
"def",
"excel_to_sql",
"(",
"excel_file_path",
",",
"engine",
",",
"read_excel_kwargs",
"=",
"None",
",",
"to_generic_type_kwargs",
"=",
"None",
",",
"to_sql_kwargs",
"=",
"None",
")",
":",
"if",
"read_excel_kwargs",
"is",
"None",
":",
"read_excel_kwargs",
"=",
... | Create a database from excel.
:param read_excel_kwargs: dict, arguments for ``pandas.read_excel`` method.
example: ``{"employee": {"skiprows": 10}, "department": {}}``
:param to_sql_kwargs: dict, arguments for ``pandas.DataFrame.to_sql``
method.
limitation:
1. If a integer column has Non... | [
"Create",
"a",
"database",
"from",
"excel",
"."
] | python | train | 34.186047 |
zomux/deepy | deepy/layers/attention.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/layers/attention.py#L29-L50 | def compute_alignments(self, prev_state, precomputed_values, mask=None):
"""
Compute the alignment weights based on the previous state.
"""
WaSp = T.dot(prev_state, self.Wa)
UaH = precomputed_values
# For test time the UaH will be (time, output_dim)
if UaH.ndim =... | [
"def",
"compute_alignments",
"(",
"self",
",",
"prev_state",
",",
"precomputed_values",
",",
"mask",
"=",
"None",
")",
":",
"WaSp",
"=",
"T",
".",
"dot",
"(",
"prev_state",
",",
"self",
".",
"Wa",
")",
"UaH",
"=",
"precomputed_values",
"# For test time the U... | Compute the alignment weights based on the previous state. | [
"Compute",
"the",
"alignment",
"weights",
"based",
"on",
"the",
"previous",
"state",
"."
] | python | test | 36.272727 |
tansey/gfl | pygfl/trendfiltering.py | https://github.com/tansey/gfl/blob/ae0f078bab57aba9e827ed6162f247ff9dc2aa19/pygfl/trendfiltering.py#L73-L81 | def solve(self, lam):
'''Solves the GFL for a fixed value of lambda.'''
s = weighted_graphtf(self.nnodes, self.y, self.weights, lam,
self.Dk.shape[0], self.Dk.shape[1], self.Dk.nnz,
self.Dk.row.astype('int32'), self.Dk.col.astype('int32'), self.D... | [
"def",
"solve",
"(",
"self",
",",
"lam",
")",
":",
"s",
"=",
"weighted_graphtf",
"(",
"self",
".",
"nnodes",
",",
"self",
".",
"y",
",",
"self",
".",
"weights",
",",
"lam",
",",
"self",
".",
"Dk",
".",
"shape",
"[",
"0",
"]",
",",
"self",
".",
... | Solves the GFL for a fixed value of lambda. | [
"Solves",
"the",
"GFL",
"for",
"a",
"fixed",
"value",
"of",
"lambda",
"."
] | python | train | 55.222222 |
galactics/beyond | beyond/orbits/orbit.py | https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/orbit.py#L402-L405 | def period(self):
"""Period of the orbit as a timedelta
"""
return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu)) | [
"def",
"period",
"(",
"self",
")",
":",
"return",
"timedelta",
"(",
"seconds",
"=",
"2",
"*",
"np",
".",
"pi",
"*",
"np",
".",
"sqrt",
"(",
"self",
".",
"kep",
".",
"a",
"**",
"3",
"/",
"self",
".",
"mu",
")",
")"
] | Period of the orbit as a timedelta | [
"Period",
"of",
"the",
"orbit",
"as",
"a",
"timedelta"
] | python | train | 38.25 |
quantopian/zipline | zipline/data/bundles/quandl.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/quandl.py#L183-L250 | def quandl_bundle(environ,
asset_db_writer,
minute_bar_writer,
daily_bar_writer,
adjustment_writer,
calendar,
start_session,
end_session,
cache,
show_progress... | [
"def",
"quandl_bundle",
"(",
"environ",
",",
"asset_db_writer",
",",
"minute_bar_writer",
",",
"daily_bar_writer",
",",
"adjustment_writer",
",",
"calendar",
",",
"start_session",
",",
"end_session",
",",
"cache",
",",
"show_progress",
",",
"output_dir",
")",
":",
... | quandl_bundle builds a daily dataset using Quandl's WIKI Prices dataset.
For more information on Quandl's API and how to obtain an API key,
please visit https://docs.quandl.com/docs#section-authentication | [
"quandl_bundle",
"builds",
"a",
"daily",
"dataset",
"using",
"Quandl",
"s",
"WIKI",
"Prices",
"dataset",
"."
] | python | train | 29.029412 |
cslarsen/lyn | lyn/lyn.py | https://github.com/cslarsen/lyn/blob/d615a6a9473083ffc7318a98fcc697cbc28ba5da/lyn/lyn.py#L161-L165 | def state(self):
"""Returns a new JIT state. You have to clean up by calling .destroy()
afterwards.
"""
return Emitter(weakref.proxy(self.lib), self.lib.jit_new_state()) | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"Emitter",
"(",
"weakref",
".",
"proxy",
"(",
"self",
".",
"lib",
")",
",",
"self",
".",
"lib",
".",
"jit_new_state",
"(",
")",
")"
] | Returns a new JIT state. You have to clean up by calling .destroy()
afterwards. | [
"Returns",
"a",
"new",
"JIT",
"state",
".",
"You",
"have",
"to",
"clean",
"up",
"by",
"calling",
".",
"destroy",
"()",
"afterwards",
"."
] | python | train | 39.4 |
XuShaohua/bcloud | bcloud/pcs.py | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/pcs.py#L364-L372 | def get_share_url_with_dirname(uk, shareid, dirname):
'''得到共享目录的链接'''
return ''.join([
const.PAN_URL, 'wap/link',
'?shareid=', shareid,
'&uk=', uk,
'&dir=', encoder.encode_uri_component(dirname),
'&third=0',
]) | [
"def",
"get_share_url_with_dirname",
"(",
"uk",
",",
"shareid",
",",
"dirname",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_URL",
",",
"'wap/link'",
",",
"'?shareid='",
",",
"shareid",
",",
"'&uk='",
",",
"uk",
",",
"'&dir='",
","... | 得到共享目录的链接 | [
"得到共享目录的链接"
] | python | train | 30.333333 |
pyecore/pyecore | pyecore/ecore.py | https://github.com/pyecore/pyecore/blob/22b67ad8799594f8f44fd8bee497583d4f12ed63/pyecore/ecore.py#L300-L305 | def getEAnnotation(self, source):
"""Return the annotation with a matching source attribute."""
for annotation in self.eAnnotations:
if annotation.source == source:
return annotation
return None | [
"def",
"getEAnnotation",
"(",
"self",
",",
"source",
")",
":",
"for",
"annotation",
"in",
"self",
".",
"eAnnotations",
":",
"if",
"annotation",
".",
"source",
"==",
"source",
":",
"return",
"annotation",
"return",
"None"
] | Return the annotation with a matching source attribute. | [
"Return",
"the",
"annotation",
"with",
"a",
"matching",
"source",
"attribute",
"."
] | python | train | 40.166667 |
devopshq/artifactory | dohq_artifactory/admin.py | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/dohq_artifactory/admin.py#L340-L347 | def _read_response(self, response):
"""
JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON
"""
self.name = response['key']
self.description = response['description']
self.layoutName = response['repoLayoutRef']
self.archi... | [
"def",
"_read_response",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"name",
"=",
"response",
"[",
"'key'",
"]",
"self",
".",
"description",
"=",
"response",
"[",
"'description'",
"]",
"self",
".",
"layoutName",
"=",
"response",
"[",
"'repoLayoutR... | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON | [
"JSON",
"Documentation",
":",
"https",
":",
"//",
"www",
".",
"jfrog",
".",
"com",
"/",
"confluence",
"/",
"display",
"/",
"RTF",
"/",
"Repository",
"+",
"Configuration",
"+",
"JSON"
] | python | train | 45.875 |
facelessuser/pyspelling | pyspelling/filters/__init__.py | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L146-L167 | def _analyze_file(self, f):
"""Analyze the file."""
f.seek(0)
# Check for BOMs
if self.CHECK_BOM:
encoding = self.has_bom(f)
f.seek(0)
else:
util.warn_deprecated(
"'CHECK_BOM' attribute is deprecated. "
"Please ... | [
"def",
"_analyze_file",
"(",
"self",
",",
"f",
")",
":",
"f",
".",
"seek",
"(",
"0",
")",
"# Check for BOMs",
"if",
"self",
".",
"CHECK_BOM",
":",
"encoding",
"=",
"self",
".",
"has_bom",
"(",
"f",
")",
"f",
".",
"seek",
"(",
"0",
")",
"else",
":... | Analyze the file. | [
"Analyze",
"the",
"file",
"."
] | python | train | 30.772727 |
heuer/cablemap | cablemap.core/cablemap/core/predicates.py | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/predicates.py#L235-L251 | def origin_east_asia(origin):
"""\
Returns if the origin is located in East Asia
Holds true for the following countries:
* China
* Japan
* Mongolia
* South Korea
* Taiwan
`origin`
The origin to check.
"""
return origin_china(origin) or origin_jap... | [
"def",
"origin_east_asia",
"(",
"origin",
")",
":",
"return",
"origin_china",
"(",
"origin",
")",
"or",
"origin_japan",
"(",
"origin",
")",
"or",
"origin_mongolia",
"(",
"origin",
")",
"or",
"origin_south_korea",
"(",
"origin",
")",
"or",
"origin_taiwan",
"(",... | \
Returns if the origin is located in East Asia
Holds true for the following countries:
* China
* Japan
* Mongolia
* South Korea
* Taiwan
`origin`
The origin to check. | [
"\\",
"Returns",
"if",
"the",
"origin",
"is",
"located",
"in",
"East",
"Asia"
] | python | train | 24.823529 |
rigetti/quantumflow | quantumflow/states.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L108-L111 | def normalize(self) -> 'State':
"""Normalize the state"""
tensor = self.tensor / bk.ccast(bk.sqrt(self.norm()))
return State(tensor, self.qubits, self._memory) | [
"def",
"normalize",
"(",
"self",
")",
"->",
"'State'",
":",
"tensor",
"=",
"self",
".",
"tensor",
"/",
"bk",
".",
"ccast",
"(",
"bk",
".",
"sqrt",
"(",
"self",
".",
"norm",
"(",
")",
")",
")",
"return",
"State",
"(",
"tensor",
",",
"self",
".",
... | Normalize the state | [
"Normalize",
"the",
"state"
] | python | train | 45 |
utiasSTARS/pykitti | pykitti/odometry.py | https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/odometry.py#L216-L238 | def _load_poses(self):
"""Load ground truth poses (T_w_cam0) from file."""
pose_file = os.path.join(self.pose_path, self.sequence + '.txt')
# Read and parse the poses
poses = []
try:
with open(pose_file, 'r') as f:
lines = f.readlines()
... | [
"def",
"_load_poses",
"(",
"self",
")",
":",
"pose_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"pose_path",
",",
"self",
".",
"sequence",
"+",
"'.txt'",
")",
"# Read and parse the poses",
"poses",
"=",
"[",
"]",
"try",
":",
"with",
"o... | Load ground truth poses (T_w_cam0) from file. | [
"Load",
"ground",
"truth",
"poses",
"(",
"T_w_cam0",
")",
"from",
"file",
"."
] | python | train | 36.304348 |
HumanCellAtlas/cloud-blobstore | cloud_blobstore/s3.py | https://github.com/HumanCellAtlas/cloud-blobstore/blob/b8a60e8e8c0da0e39dda084cb467a34cd2d1ef0a/cloud_blobstore/s3.py#L295-L308 | def get_creation_date(
self,
bucket: str,
key: str,
) -> datetime:
"""
Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is ... | [
"def",
"get_creation_date",
"(",
"self",
",",
"bucket",
":",
"str",
",",
"key",
":",
"str",
",",
")",
"->",
"datetime",
":",
"# An S3 object's creation date is stored in its LastModified field which stores the",
"# most recent value between the two.",
"return",
"self",
".",... | Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is being retrieved.
:return: the creation date | [
"Retrieves",
"the",
"creation",
"date",
"for",
"a",
"given",
"key",
"in",
"a",
"given",
"bucket",
".",
":",
"param",
"bucket",
":",
"the",
"bucket",
"the",
"object",
"resides",
"in",
".",
":",
"param",
"key",
":",
"the",
"key",
"of",
"the",
"object",
... | python | train | 40.214286 |
googlefonts/glyphsLib | Lib/glyphsLib/builder/features.py | https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/builder/features.py#L582-L613 | def _pop_comment_block(self, statements, header_re):
"""Look for a series of comments that start with one that matches the
regex. If the first comment is found, all subsequent comments are
popped from statements, concatenated and dedented and returned.
"""
res = []
commen... | [
"def",
"_pop_comment_block",
"(",
"self",
",",
"statements",
",",
"header_re",
")",
":",
"res",
"=",
"[",
"]",
"comments",
"=",
"[",
"]",
"match",
"=",
"None",
"st_iter",
"=",
"iter",
"(",
"statements",
")",
"# Look for the header",
"for",
"st",
"in",
"s... | Look for a series of comments that start with one that matches the
regex. If the first comment is found, all subsequent comments are
popped from statements, concatenated and dedented and returned. | [
"Look",
"for",
"a",
"series",
"of",
"comments",
"that",
"start",
"with",
"one",
"that",
"matches",
"the",
"regex",
".",
"If",
"the",
"first",
"comment",
"is",
"found",
"all",
"subsequent",
"comments",
"are",
"popped",
"from",
"statements",
"concatenated",
"a... | python | train | 39.1875 |
tanghaibao/jcvi | jcvi/graphics/assembly.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/graphics/assembly.py#L36-L87 | def covlen(args):
"""
%prog covlen covfile fastafile
Plot coverage vs length. `covfile` is two-column listing contig id and
depth of coverage.
"""
import numpy as np
import pandas as pd
import seaborn as sns
from jcvi.formats.base import DictFile
p = OptionParser(covlen.__doc__... | [
"def",
"covlen",
"(",
"args",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"pandas",
"as",
"pd",
"import",
"seaborn",
"as",
"sns",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"DictFile",
"p",
"=",
"OptionParser",
"(",
"covlen",
".",
"_... | %prog covlen covfile fastafile
Plot coverage vs length. `covfile` is two-column listing contig id and
depth of coverage. | [
"%prog",
"covlen",
"covfile",
"fastafile"
] | python | train | 31.442308 |
mukulhase/WebWhatsapp-Wrapper | webwhatsapi/__init__.py | https://github.com/mukulhase/WebWhatsapp-Wrapper/blob/81b918ee4e0cd0cb563807a72baa167f670d70cb/webwhatsapi/__init__.py#L292-L302 | def get_contacts(self):
"""
Fetches list of all contacts
This will return chats with people from the address book only
Use get_all_chats for all chats
:return: List of contacts
:rtype: list[Contact]
"""
all_contacts = self.wapi_functions.getAllContacts()
... | [
"def",
"get_contacts",
"(",
"self",
")",
":",
"all_contacts",
"=",
"self",
".",
"wapi_functions",
".",
"getAllContacts",
"(",
")",
"return",
"[",
"Contact",
"(",
"contact",
",",
"self",
")",
"for",
"contact",
"in",
"all_contacts",
"]"
] | Fetches list of all contacts
This will return chats with people from the address book only
Use get_all_chats for all chats
:return: List of contacts
:rtype: list[Contact] | [
"Fetches",
"list",
"of",
"all",
"contacts",
"This",
"will",
"return",
"chats",
"with",
"people",
"from",
"the",
"address",
"book",
"only",
"Use",
"get_all_chats",
"for",
"all",
"chats"
] | python | train | 34.272727 |
danielhrisca/asammdf | asammdf/signal.py | https://github.com/danielhrisca/asammdf/blob/3c7a1fd19c957ceebe4dcdbb2abf00806c2bdb66/asammdf/signal.py#L731-L847 | def interp(self, new_timestamps, interpolation_mode=0):
""" returns a new *Signal* interpolated using the *new_timestamps*
Parameters
----------
new_timestamps : np.array
timestamps used for interpolation
interpolation_mode : int
interpolation mode for in... | [
"def",
"interp",
"(",
"self",
",",
"new_timestamps",
",",
"interpolation_mode",
"=",
"0",
")",
":",
"if",
"not",
"len",
"(",
"self",
".",
"samples",
")",
"or",
"not",
"len",
"(",
"new_timestamps",
")",
":",
"return",
"Signal",
"(",
"self",
".",
"sample... | returns a new *Signal* interpolated using the *new_timestamps*
Parameters
----------
new_timestamps : np.array
timestamps used for interpolation
interpolation_mode : int
interpolation mode for integer signals; default 0
* 0 - repeat previous samp... | [
"returns",
"a",
"new",
"*",
"Signal",
"*",
"interpolated",
"using",
"the",
"*",
"new_timestamps",
"*"
] | python | train | 38.376068 |
spyder-ide/spyder | spyder/preferences/shortcuts.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/shortcuts.py#L448-L454 | def set_sequence_from_str(self, sequence):
"""
This is a convenience method to set the new QKeySequence of the
shortcut editor from a string.
"""
self._qsequences = [QKeySequence(s) for s in sequence.split(', ')]
self.update_warning() | [
"def",
"set_sequence_from_str",
"(",
"self",
",",
"sequence",
")",
":",
"self",
".",
"_qsequences",
"=",
"[",
"QKeySequence",
"(",
"s",
")",
"for",
"s",
"in",
"sequence",
".",
"split",
"(",
"', '",
")",
"]",
"self",
".",
"update_warning",
"(",
")"
] | This is a convenience method to set the new QKeySequence of the
shortcut editor from a string. | [
"This",
"is",
"a",
"convenience",
"method",
"to",
"set",
"the",
"new",
"QKeySequence",
"of",
"the",
"shortcut",
"editor",
"from",
"a",
"string",
"."
] | python | train | 40.285714 |
jeffh/sniffer | sniffer/modules_restore_point.py | https://github.com/jeffh/sniffer/blob/8e4c3e77743aef08109ea0225b4a6536d4e60270/sniffer/modules_restore_point.py#L19-L25 | def restore(self):
"""
Unloads all modules that weren't loaded when save_modules was called.
"""
sys = set(self._sys_modules.keys())
for mod_name in sys.difference(self._saved_modules):
del self._sys_modules[mod_name] | [
"def",
"restore",
"(",
"self",
")",
":",
"sys",
"=",
"set",
"(",
"self",
".",
"_sys_modules",
".",
"keys",
"(",
")",
")",
"for",
"mod_name",
"in",
"sys",
".",
"difference",
"(",
"self",
".",
"_saved_modules",
")",
":",
"del",
"self",
".",
"_sys_modul... | Unloads all modules that weren't loaded when save_modules was called. | [
"Unloads",
"all",
"modules",
"that",
"weren",
"t",
"loaded",
"when",
"save_modules",
"was",
"called",
"."
] | python | train | 37.571429 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/extensions.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/extensions.py#L94-L102 | def unload_extension(self, module_str):
"""Unload an IPython extension by its module name.
This function looks up the extension's name in ``sys.modules`` and
simply calls ``mod.unload_ipython_extension(self)``.
"""
if module_str in sys.modules:
mod = sys.modules[modu... | [
"def",
"unload_extension",
"(",
"self",
",",
"module_str",
")",
":",
"if",
"module_str",
"in",
"sys",
".",
"modules",
":",
"mod",
"=",
"sys",
".",
"modules",
"[",
"module_str",
"]",
"self",
".",
"_call_unload_ipython_extension",
"(",
"mod",
")"
] | Unload an IPython extension by its module name.
This function looks up the extension's name in ``sys.modules`` and
simply calls ``mod.unload_ipython_extension(self)``. | [
"Unload",
"an",
"IPython",
"extension",
"by",
"its",
"module",
"name",
"."
] | python | test | 41.333333 |
yamcs/yamcs-python | yamcs-client/yamcs/client.py | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L386-L401 | def list_data_links(self, instance):
"""
Lists the data links visible to this client.
Data links are returned in random order.
:param str instance: A Yamcs instance name.
:rtype: ~collections.Iterable[.Link]
"""
# Server does not do pagination on listings of thi... | [
"def",
"list_data_links",
"(",
"self",
",",
"instance",
")",
":",
"# Server does not do pagination on listings of this resource.",
"# Return an iterator anyway for similarity with other API methods",
"response",
"=",
"self",
".",
"get_proto",
"(",
"path",
"=",
"'/links/'",
"+",... | Lists the data links visible to this client.
Data links are returned in random order.
:param str instance: A Yamcs instance name.
:rtype: ~collections.Iterable[.Link] | [
"Lists",
"the",
"data",
"links",
"visible",
"to",
"this",
"client",
"."
] | python | train | 40.25 |
Arello-Mobile/swagger2rst | swg2rst/swagger/abstract_type_object.py | https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/swagger/abstract_type_object.py#L75-L89 | def set_type_by_schema(self, schema_obj, schema_type):
"""
Set property type by schema object
Schema will create, if it doesn't exists in collection
:param dict schema_obj: raw schema object
:param str schema_type:
"""
schema_id = self._get_object_schema_id(schem... | [
"def",
"set_type_by_schema",
"(",
"self",
",",
"schema_obj",
",",
"schema_type",
")",
":",
"schema_id",
"=",
"self",
".",
"_get_object_schema_id",
"(",
"schema_obj",
",",
"schema_type",
")",
"if",
"not",
"self",
".",
"storage",
".",
"contains",
"(",
"schema_id... | Set property type by schema object
Schema will create, if it doesn't exists in collection
:param dict schema_obj: raw schema object
:param str schema_type: | [
"Set",
"property",
"type",
"by",
"schema",
"object",
"Schema",
"will",
"create",
"if",
"it",
"doesn",
"t",
"exists",
"in",
"collection"
] | python | train | 38.133333 |
symengine/symengine.py | symengine/compatibility.py | https://github.com/symengine/symengine.py/blob/1366cf98ceaade339c5dd24ae3381a0e63ea9dad/symengine/compatibility.py#L140-L182 | def with_metaclass(meta, *bases):
"""
Create a base class with a metaclass.
For example, if you have the metaclass
>>> class Meta(type):
... pass
Use this as the metaclass by doing
>>> from symengine.compatibility import with_metaclass
>>> class MyClass(with_metaclass(Meta, objec... | [
"def",
"with_metaclass",
"(",
"meta",
",",
"*",
"bases",
")",
":",
"class",
"metaclass",
"(",
"meta",
")",
":",
"__call__",
"=",
"type",
".",
"__call__",
"__init__",
"=",
"type",
".",
"__init__",
"def",
"__new__",
"(",
"cls",
",",
"name",
",",
"this_ba... | Create a base class with a metaclass.
For example, if you have the metaclass
>>> class Meta(type):
... pass
Use this as the metaclass by doing
>>> from symengine.compatibility import with_metaclass
>>> class MyClass(with_metaclass(Meta, object)):
... pass
This is equivalent ... | [
"Create",
"a",
"base",
"class",
"with",
"a",
"metaclass",
"."
] | python | train | 25.348837 |
openpaperwork/paperwork-backend | paperwork_backend/img/page.py | https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/img/page.py#L82-L93 | def _get_text(self):
"""
Get the text corresponding to this page
"""
boxes = self.boxes
txt = []
for line in boxes:
txt_line = u""
for box in line.word_boxes:
txt_line += u" " + box.content
txt.append(txt_line)
r... | [
"def",
"_get_text",
"(",
"self",
")",
":",
"boxes",
"=",
"self",
".",
"boxes",
"txt",
"=",
"[",
"]",
"for",
"line",
"in",
"boxes",
":",
"txt_line",
"=",
"u\"\"",
"for",
"box",
"in",
"line",
".",
"word_boxes",
":",
"txt_line",
"+=",
"u\" \"",
"+",
"... | Get the text corresponding to this page | [
"Get",
"the",
"text",
"corresponding",
"to",
"this",
"page"
] | python | train | 26.5 |
nfcpy/nfcpy | src/nfc/clf/rcs956.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/rcs956.py#L231-L242 | def sense_ttb(self, target):
"""Activate the RF field and probe for a Type B Target.
The RC-S956 can discover Type B Targets (Type 4B Tag) at 106
kbps. For a Type 4B Tag the firmware automatically sends an
ATTRIB command that configures the use of DID and 64 byte
maximum frame s... | [
"def",
"sense_ttb",
"(",
"self",
",",
"target",
")",
":",
"return",
"super",
"(",
"Device",
",",
"self",
")",
".",
"sense_ttb",
"(",
"target",
",",
"did",
"=",
"b'\\x01'",
")"
] | Activate the RF field and probe for a Type B Target.
The RC-S956 can discover Type B Targets (Type 4B Tag) at 106
kbps. For a Type 4B Tag the firmware automatically sends an
ATTRIB command that configures the use of DID and 64 byte
maximum frame size. The driver reverts this configurati... | [
"Activate",
"the",
"RF",
"field",
"and",
"probe",
"for",
"a",
"Type",
"B",
"Target",
"."
] | python | train | 47.583333 |
ciena/afkak | afkak/consumer.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/consumer.py#L858-L906 | def _process_messages(self, messages):
"""Send messages to the `processor` callback to be processed
In the case we have a commit policy, we send messages to the processor
in blocks no bigger than auto_commit_every_n (if set). Otherwise, we
send the entire message block to be processed.
... | [
"def",
"_process_messages",
"(",
"self",
",",
"messages",
")",
":",
"# Have we been told to shutdown?",
"if",
"self",
".",
"_shuttingdown",
":",
"return",
"# Do we have any messages to process?",
"if",
"not",
"messages",
":",
"# No, we're done with this block. If we had anoth... | Send messages to the `processor` callback to be processed
In the case we have a commit policy, we send messages to the processor
in blocks no bigger than auto_commit_every_n (if set). Otherwise, we
send the entire message block to be processed. | [
"Send",
"messages",
"to",
"the",
"processor",
"callback",
"to",
"be",
"processed"
] | python | train | 49.285714 |
openwisp/netdiff | netdiff/parsers/base.py | https://github.com/openwisp/netdiff/blob/f7fda2ed78ad815b8c56eae27dfd193172fb23f5/netdiff/parsers/base.py#L135-L150 | def json(self, dict=False, **kwargs):
"""
Outputs NetJSON format
"""
try:
graph = self.graph
except AttributeError:
raise NotImplementedError()
return _netjson_networkgraph(self.protocol,
self.version,
... | [
"def",
"json",
"(",
"self",
",",
"dict",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"graph",
"=",
"self",
".",
"graph",
"except",
"AttributeError",
":",
"raise",
"NotImplementedError",
"(",
")",
"return",
"_netjson_networkgraph",
"(",
"... | Outputs NetJSON format | [
"Outputs",
"NetJSON",
"format"
] | python | train | 38.0625 |
pydron/twistit | twistit/_events.py | https://github.com/pydron/twistit/blob/23ac43b830083fd32c400fcdfa5300e302769c74/twistit/_events.py#L77-L90 | def derive(self, modifier):
"""
Returns a new :class:`Event` instance that will fire
when this event fires. The value passed to the callbacks
to the new event is the return value of the given
`modifier` function which is passed the original value.
"""
def forward(... | [
"def",
"derive",
"(",
"self",
",",
"modifier",
")",
":",
"def",
"forward",
"(",
"value",
")",
":",
"changed_value",
"=",
"modifier",
"(",
"value",
")",
"derived",
".",
"fire",
"(",
"changed_value",
")",
"derived",
"=",
"Event",
"(",
")",
"self",
".",
... | Returns a new :class:`Event` instance that will fire
when this event fires. The value passed to the callbacks
to the new event is the return value of the given
`modifier` function which is passed the original value. | [
"Returns",
"a",
"new",
":",
"class",
":",
"Event",
"instance",
"that",
"will",
"fire",
"when",
"this",
"event",
"fires",
".",
"The",
"value",
"passed",
"to",
"the",
"callbacks",
"to",
"the",
"new",
"event",
"is",
"the",
"return",
"value",
"of",
"the",
... | python | train | 35.071429 |
Rediker-Software/doac | doac/views.py | https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/views.py#L94-L113 | def verify_client_id(self):
"""
Verify a provided client id against the database and set the `Client` object that is
associated with it to `self.client`.
TODO: Document all of the thrown exceptions.
"""
from .models import Client
from .exceptions.invalid_client ... | [
"def",
"verify_client_id",
"(",
"self",
")",
":",
"from",
".",
"models",
"import",
"Client",
"from",
".",
"exceptions",
".",
"invalid_client",
"import",
"ClientDoesNotExist",
"from",
".",
"exceptions",
".",
"invalid_request",
"import",
"ClientNotProvided",
"if",
"... | Verify a provided client id against the database and set the `Client` object that is
associated with it to `self.client`.
TODO: Document all of the thrown exceptions. | [
"Verify",
"a",
"provided",
"client",
"id",
"against",
"the",
"database",
"and",
"set",
"the",
"Client",
"object",
"that",
"is",
"associated",
"with",
"it",
"to",
"self",
".",
"client",
"."
] | python | train | 37.45 |
DataDog/integrations-core | vsphere/datadog_checks/vsphere/metadata_cache.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/vsphere/datadog_checks/vsphere/metadata_cache.py#L32-L38 | def contains(self, key, counter_id):
"""
Return whether a counter_id is present for a given instance key.
If the key is not in the cache, raises a KeyError.
"""
with self._lock:
return counter_id in self._metadata[key] | [
"def",
"contains",
"(",
"self",
",",
"key",
",",
"counter_id",
")",
":",
"with",
"self",
".",
"_lock",
":",
"return",
"counter_id",
"in",
"self",
".",
"_metadata",
"[",
"key",
"]"
] | Return whether a counter_id is present for a given instance key.
If the key is not in the cache, raises a KeyError. | [
"Return",
"whether",
"a",
"counter_id",
"is",
"present",
"for",
"a",
"given",
"instance",
"key",
".",
"If",
"the",
"key",
"is",
"not",
"in",
"the",
"cache",
"raises",
"a",
"KeyError",
"."
] | python | train | 37.714286 |
frawau/aiolifx | aiolifx/aiolifx.py | https://github.com/frawau/aiolifx/blob/9bd8c5e6d291f4c79314989402f7e2c6476d5851/aiolifx/aiolifx.py#L367-L388 | def get_label(self,callb=None):
"""Convenience method to request the label from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that callb ... | [
"def",
"get_label",
"(",
"self",
",",
"callb",
"=",
"None",
")",
":",
"if",
"self",
".",
"label",
"is",
"None",
":",
"mypartial",
"=",
"partial",
"(",
"self",
".",
"resp_set_label",
")",
"if",
"callb",
":",
"mycallb",
"=",
"lambda",
"x",
",",
"y",
... | Convenience method to request the label from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
and request that callb be executed when a response is received. Th... | [
"Convenience",
"method",
"to",
"request",
"the",
"label",
"from",
"the",
"device"
] | python | train | 45.045455 |
jaywink/federation | federation/protocols/diaspora/encrypted.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/diaspora/encrypted.py#L25-L35 | def pkcs7_unpad(data):
"""
Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
"""
if isinstance(data, str):
return data[0:-ord(data[-1])]
else:
... | [
"def",
"pkcs7_unpad",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"return",
"data",
"[",
"0",
":",
"-",
"ord",
"(",
"data",
"[",
"-",
"1",
"]",
")",
"]",
"else",
":",
"return",
"data",
"[",
"0",
":",
"-",
"da... | Remove the padding bytes that were added at point of encryption.
Implementation copied from pyaspora:
https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 | [
"Remove",
"the",
"padding",
"bytes",
"that",
"were",
"added",
"at",
"point",
"of",
"encryption",
"."
] | python | train | 30.727273 |
saltstack/salt | salt/states/svn.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/svn.py#L190-L291 | def export(name,
target=None,
rev=None,
user=None,
username=None,
password=None,
force=False,
overwrite=False,
externals=True,
trust=False,
trust_failures=None):
'''
Export a file or directory from an S... | [
"def",
"export",
"(",
"name",
",",
"target",
"=",
"None",
",",
"rev",
"=",
"None",
",",
"user",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"force",
"=",
"False",
",",
"overwrite",
"=",
"False",
",",
"externals",
"... | Export a file or directory from an SVN repository
name
Address and path to the file or directory to be exported.
target
Name of the target directory where the checkout will put the working
directory
rev : None
The name revision number to checkout. Enable "force" if the dir... | [
"Export",
"a",
"file",
"or",
"directory",
"from",
"an",
"SVN",
"repository"
] | python | train | 27.95098 |
saltstack/salt | salt/utils/url.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L73-L93 | def escape(url):
'''
add escape character `|` to `url`
'''
if salt.utils.platform.is_windows():
return url
scheme = urlparse(url).scheme
if not scheme:
if url.startswith('|'):
return url
else:
return '|{0}'.format(url)
elif scheme == 'salt':
... | [
"def",
"escape",
"(",
"url",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"return",
"url",
"scheme",
"=",
"urlparse",
"(",
"url",
")",
".",
"scheme",
"if",
"not",
"scheme",
":",
"if",
"url",
".",
"startsw... | add escape character `|` to `url` | [
"add",
"escape",
"character",
"|",
"to",
"url"
] | python | train | 24.095238 |
mbedmicro/pyOCD | pyocd/gdbserver/context_facade.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/gdbserver/context_facade.py#L172-L187 | def get_memory_map_xml(self):
"""! @brief Generate GDB memory map XML.
"""
root = ElementTree.Element('memory-map')
for r in self._context.core.memory_map:
# Look up the region type name. Regions default to ram if gdb doesn't
# have a concept of the region type.
... | [
"def",
"get_memory_map_xml",
"(",
"self",
")",
":",
"root",
"=",
"ElementTree",
".",
"Element",
"(",
"'memory-map'",
")",
"for",
"r",
"in",
"self",
".",
"_context",
".",
"core",
".",
"memory_map",
":",
"# Look up the region type name. Regions default to ram if gdb d... | ! @brief Generate GDB memory map XML. | [
"!"
] | python | train | 49.125 |
openego/eDisGo | edisgo/tools/pypsa_io.py | https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/tools/pypsa_io.py#L605-L685 | def add_aggregated_lv_components(network, components):
"""
Aggregates LV load and generation at LV stations
Use this function if you aim for MV calculation only. The according
DataFrames of `components` are extended by load and generators representing
these aggregated respecting the technology type... | [
"def",
"add_aggregated_lv_components",
"(",
"network",
",",
"components",
")",
":",
"generators",
"=",
"{",
"}",
"loads",
"=",
"{",
"}",
"# collect aggregated generation capacity by type and subtype",
"# collect aggregated load grouped by sector",
"for",
"lv_grid",
"in",
"n... | Aggregates LV load and generation at LV stations
Use this function if you aim for MV calculation only. The according
DataFrames of `components` are extended by load and generators representing
these aggregated respecting the technology type.
Parameters
----------
network : Network
The ... | [
"Aggregates",
"LV",
"load",
"and",
"generation",
"at",
"LV",
"stations"
] | python | train | 38.851852 |
biocore/burrito-fillings | bfillings/rdp_classifier.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/rdp_classifier.py#L377-L452 | def assign_taxonomy(
data, min_confidence=0.80, output_fp=None, training_data_fp=None,
fixrank=True, max_memory=None, tmp_dir=tempfile.gettempdir()):
"""Assign taxonomy to each sequence in data with the RDP classifier
data: open fasta file object or list of fasta lines
confidence: m... | [
"def",
"assign_taxonomy",
"(",
"data",
",",
"min_confidence",
"=",
"0.80",
",",
"output_fp",
"=",
"None",
",",
"training_data_fp",
"=",
"None",
",",
"fixrank",
"=",
"True",
",",
"max_memory",
"=",
"None",
",",
"tmp_dir",
"=",
"tempfile",
".",
"gettempdir",
... | Assign taxonomy to each sequence in data with the RDP classifier
data: open fasta file object or list of fasta lines
confidence: minimum support threshold to assign taxonomy to a sequence
output_fp: path to write output; if not provided, result will be
returned in a dict of {seq_id:(ta... | [
"Assign",
"taxonomy",
"to",
"each",
"sequence",
"in",
"data",
"with",
"the",
"RDP",
"classifier"
] | python | train | 34.578947 |
thespacedoctor/qubits | qubits/workspace.py | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/workspace.py#L63-L123 | def setup(self):
"""
*setup the workspace in the requested location*
**Return:**
- ``None``
"""
self.log.info('starting the ``setup`` method')
# RECURSIVELY CREATE MISSING DIRECTORIES
if not os.path.exists(self.pathToWorkspace):
os.makedi... | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``setup`` method'",
")",
"# RECURSIVELY CREATE MISSING DIRECTORIES",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"pathToWorkspace",
")",
":",
"os",... | *setup the workspace in the requested location*
**Return:**
- ``None`` | [
"*",
"setup",
"the",
"workspace",
"in",
"the",
"requested",
"location",
"*"
] | python | train | 38.131148 |
camptocamp/Studio | studio/controllers/layertemplates.py | https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/layertemplates.py#L97-L106 | def delete(self, id):
"""DELETE /layertemplates/id: Delete an existing item."""
# url('LayerTemplates', id=ID)
lt = meta.Session.query(LayerTemplate).get(id)
# use following query for getting a layertemplate owned by current user
#lt = self._get_lt_from_user_by_id(c.user, id)
... | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"# url('LayerTemplates', id=ID)",
"lt",
"=",
"meta",
".",
"Session",
".",
"query",
"(",
"LayerTemplate",
")",
".",
"get",
"(",
"id",
")",
"# use following query for getting a layertemplate owned by current user",
"#... | DELETE /layertemplates/id: Delete an existing item. | [
"DELETE",
"/",
"layertemplates",
"/",
"id",
":",
"Delete",
"an",
"existing",
"item",
"."
] | python | train | 41.5 |
oceanprotocol/aquarius | aquarius/app/assets.py | https://github.com/oceanprotocol/aquarius/blob/9fb094b1ac01f0604d0c854166dd324e476a010e/aquarius/app/assets.py#L284-L475 | def update(did):
"""Update DDO of an existing asset
---
tags:
- ddo
consumes:
- application/json
parameters:
- in: body
name: body
required: true
description: DDO of the asset.
schema:
type: object
required:
- "@contex... | [
"def",
"update",
"(",
"did",
")",
":",
"required_attributes",
"=",
"[",
"'@context'",
",",
"'created'",
",",
"'id'",
",",
"'publicKey'",
",",
"'authentication'",
",",
"'proof'",
",",
"'service'",
"]",
"required_metadata_base_attributes",
"=",
"[",
"'name'",
",",... | Update DDO of an existing asset
---
tags:
- ddo
consumes:
- application/json
parameters:
- in: body
name: body
required: true
description: DDO of the asset.
schema:
type: object
required:
- "@context"
- created... | [
"Update",
"DDO",
"of",
"an",
"existing",
"asset",
"---",
"tags",
":",
"-",
"ddo",
"consumes",
":",
"-",
"application",
"/",
"json",
"parameters",
":",
"-",
"in",
":",
"body",
"name",
":",
"body",
"required",
":",
"true",
"description",
":",
"DDO",
"of"... | python | train | 46.203125 |
earlzo/hfut | hfut/parser.py | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L73-L87 | def flatten_list(multiply_list):
"""
碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list
"""
if isinstance(multiply_list, list):
return [rv for l in multiply_list for rv ... | [
"def",
"flatten_list",
"(",
"multiply_list",
")",
":",
"if",
"isinstance",
"(",
"multiply_list",
",",
"list",
")",
":",
"return",
"[",
"rv",
"for",
"l",
"in",
"multiply_list",
"for",
"rv",
"in",
"flatten_list",
"(",
"l",
")",
"]",
"else",
":",
"return",
... | 碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list | [
"碾平",
"list",
"::"
] | python | train | 24.4 |
tanghaibao/goatools | goatools/grouper/grprobj.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L219-L228 | def get_go2sectiontxt(self):
"""Return a dict with actual header and user GO IDs as keys and their sections as values."""
go2txt = {}
_get_secs = self.hdrobj.get_sections
hdrgo2sectxt = {h:" ".join(_get_secs(h)) for h in self.get_hdrgos()}
usrgo2hdrgo = self.get_usrgo2hdrgo()
... | [
"def",
"get_go2sectiontxt",
"(",
"self",
")",
":",
"go2txt",
"=",
"{",
"}",
"_get_secs",
"=",
"self",
".",
"hdrobj",
".",
"get_sections",
"hdrgo2sectxt",
"=",
"{",
"h",
":",
"\" \"",
".",
"join",
"(",
"_get_secs",
"(",
"h",
")",
")",
"for",
"h",
"in"... | Return a dict with actual header and user GO IDs as keys and their sections as values. | [
"Return",
"a",
"dict",
"with",
"actual",
"header",
"and",
"user",
"GO",
"IDs",
"as",
"keys",
"and",
"their",
"sections",
"as",
"values",
"."
] | python | train | 49.3 |
xu2243051/easyui-menu | easyui/mixins/model_mixins.py | https://github.com/xu2243051/easyui-menu/blob/4da0b50cf2d3ddb0f1ec7a4da65fd3c4339f8dfb/easyui/mixins/model_mixins.py#L51-L84 | def get_fields(self, field_verbose=True, value_verbose=True, fields=[], extra_fields=[], remove_fields = []):
'''
返回字段名及其对应值的列表
field_verbose 为True,返回定义中的字段的verbose_name, False返回其name
value_verbose 为True,返回数据的显示数据,会转换为choice的内容,为False, 返回数据的实际值
fields 指定了要显示的字段
extra_fiel... | [
"def",
"get_fields",
"(",
"self",
",",
"field_verbose",
"=",
"True",
",",
"value_verbose",
"=",
"True",
",",
"fields",
"=",
"[",
"]",
",",
"extra_fields",
"=",
"[",
"]",
",",
"remove_fields",
"=",
"[",
"]",
")",
":",
"field_list",
"=",
"[",
"]",
"for... | 返回字段名及其对应值的列表
field_verbose 为True,返回定义中的字段的verbose_name, False返回其name
value_verbose 为True,返回数据的显示数据,会转换为choice的内容,为False, 返回数据的实际值
fields 指定了要显示的字段
extra_fields 指定了要特殊处理的非field,比如是函数
remove_fields 指定了不显示的字段 | [
"返回字段名及其对应值的列表",
"field_verbose",
"为True,返回定义中的字段的verbose_name,",
"False返回其name",
"value_verbose",
"为True,返回数据的显示数据,会转换为choice的内容,为False,",
"返回数据的实际值",
"fields",
"指定了要显示的字段",
"extra_fields",
"指定了要特殊处理的非field,比如是函数",
"remove_fields",
"指定了不显示的字段"
] | python | valid | 35.588235 |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/collectionseditor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L268-L273 | def rowCount(self, index=QModelIndex()):
"""Array row number"""
if self.total_rows <= self.rows_loaded:
return self.total_rows
else:
return self.rows_loaded | [
"def",
"rowCount",
"(",
"self",
",",
"index",
"=",
"QModelIndex",
"(",
")",
")",
":",
"if",
"self",
".",
"total_rows",
"<=",
"self",
".",
"rows_loaded",
":",
"return",
"self",
".",
"total_rows",
"else",
":",
"return",
"self",
".",
"rows_loaded"
] | Array row number | [
"Array",
"row",
"number"
] | python | train | 34 |
ella/ella | ella/core/views.py | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/views.py#L321-L334 | def _archive_entry_year(self, category):
" Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category "
year = getattr(settings, 'ARCHIVE_ENTRY_YEAR', None)
if not year:
n = now()
try:
year = Listing.objects.filter(
... | [
"def",
"_archive_entry_year",
"(",
"self",
",",
"category",
")",
":",
"year",
"=",
"getattr",
"(",
"settings",
",",
"'ARCHIVE_ENTRY_YEAR'",
",",
"None",
")",
"if",
"not",
"year",
":",
"n",
"=",
"now",
"(",
")",
"try",
":",
"year",
"=",
"Listing",
".",
... | Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category | [
"Return",
"ARCHIVE_ENTRY_YEAR",
"from",
"settings",
"(",
"if",
"exists",
")",
"or",
"year",
"of",
"the",
"newest",
"object",
"in",
"category"
] | python | train | 44.285714 |
inveniosoftware/invenio-stats | invenio_stats/aggregations.py | https://github.com/inveniosoftware/invenio-stats/blob/d877ae5462084abb4a28a20f1ebb3d636769c1bc/invenio_stats/aggregations.py#L310-L328 | def list_bookmarks(self, start_date=None, end_date=None, limit=None):
"""List the aggregation's bookmarks."""
query = Search(
using=self.client,
index=self.aggregation_alias,
doc_type=self.bookmark_doc_type
).sort({'date': {'order': 'desc'}})
range_ar... | [
"def",
"list_bookmarks",
"(",
"self",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"query",
"=",
"Search",
"(",
"using",
"=",
"self",
".",
"client",
",",
"index",
"=",
"self",
".",
"aggregation_alia... | List the aggregation's bookmarks. | [
"List",
"the",
"aggregation",
"s",
"bookmarks",
"."
] | python | valid | 37.526316 |
google/grr | grr/server/grr_response_server/databases/mem_hunts.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_hunts.py#L41-L63 | def UpdateHuntObject(self, hunt_id, start_time=None, **kwargs):
"""Updates the hunt object by applying the update function."""
hunt_obj = self.ReadHuntObject(hunt_id)
delta_suffix = "_delta"
for k, v in kwargs.items():
if v is None:
continue
if k.endswith(delta_suffix):
ke... | [
"def",
"UpdateHuntObject",
"(",
"self",
",",
"hunt_id",
",",
"start_time",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"hunt_obj",
"=",
"self",
".",
"ReadHuntObject",
"(",
"hunt_id",
")",
"delta_suffix",
"=",
"\"_delta\"",
"for",
"k",
",",
"v",
"in",... | Updates the hunt object by applying the update function. | [
"Updates",
"the",
"hunt",
"object",
"by",
"applying",
"the",
"update",
"function",
"."
] | python | train | 31.173913 |
UCL-INGI/INGInious | inginious/frontend/pages/course_admin/task_edit_file.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L214-L233 | def action_delete(self, courseid, taskid, path):
""" Delete a file or a directory """
# normalize
path = path.strip()
if not path.startswith("/"):
path = "/" + path
wanted_path = self.verify_path(courseid, taskid, path)
if wanted_path is None:
ret... | [
"def",
"action_delete",
"(",
"self",
",",
"courseid",
",",
"taskid",
",",
"path",
")",
":",
"# normalize",
"path",
"=",
"path",
".",
"strip",
"(",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"path",
"=",
"\"/\"",
"+",
"path",... | Delete a file or a directory | [
"Delete",
"a",
"file",
"or",
"a",
"directory"
] | python | train | 40.5 |
ssato/python-anyconfig | src/anyconfig/utils.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L259-L290 | def _try_to_get_extension(obj):
"""
Try to get file extension from given path or file object.
:param obj: a file, file-like object or something
:return: File extension or None
>>> _try_to_get_extension("a.py")
'py'
"""
if is_path(obj):
path = obj
elif is_path_obj(obj):
... | [
"def",
"_try_to_get_extension",
"(",
"obj",
")",
":",
"if",
"is_path",
"(",
"obj",
")",
":",
"path",
"=",
"obj",
"elif",
"is_path_obj",
"(",
"obj",
")",
":",
"return",
"obj",
".",
"suffix",
"[",
"1",
":",
"]",
"elif",
"is_file_stream",
"(",
"obj",
")... | Try to get file extension from given path or file object.
:param obj: a file, file-like object or something
:return: File extension or None
>>> _try_to_get_extension("a.py")
'py' | [
"Try",
"to",
"get",
"file",
"extension",
"from",
"given",
"path",
"or",
"file",
"object",
"."
] | python | train | 18.96875 |
manns/pyspread | pyspread/src/lib/vlc.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L1869-L1875 | def vlm_add_input(self, psz_name, psz_input):
'''Add a media's input MRL. This will add the specified one.
@param psz_name: the media to work on.
@param psz_input: the input MRL.
@return: 0 on success, -1 on error.
'''
return libvlc_vlm_add_input(self, str_to_bytes(psz_na... | [
"def",
"vlm_add_input",
"(",
"self",
",",
"psz_name",
",",
"psz_input",
")",
":",
"return",
"libvlc_vlm_add_input",
"(",
"self",
",",
"str_to_bytes",
"(",
"psz_name",
")",
",",
"str_to_bytes",
"(",
"psz_input",
")",
")"
] | Add a media's input MRL. This will add the specified one.
@param psz_name: the media to work on.
@param psz_input: the input MRL.
@return: 0 on success, -1 on error. | [
"Add",
"a",
"media",
"s",
"input",
"MRL",
".",
"This",
"will",
"add",
"the",
"specified",
"one",
"."
] | python | train | 49 |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L561-L571 | def IsPropertyInMetaIgnoreCase(classId, key):
""" Methods returns the property meta of the provided key for the given classId. Given key is case insensitive. """
if classId in _ManagedObjectMeta:
for prop in _ManagedObjectMeta[classId]:
if (prop.lower() == key.lower()):
return _ManagedObjectMeta[classId... | [
"def",
"IsPropertyInMetaIgnoreCase",
"(",
"classId",
",",
"key",
")",
":",
"if",
"classId",
"in",
"_ManagedObjectMeta",
":",
"for",
"prop",
"in",
"_ManagedObjectMeta",
"[",
"classId",
"]",
":",
"if",
"(",
"prop",
".",
"lower",
"(",
")",
"==",
"key",
".",
... | Methods returns the property meta of the provided key for the given classId. Given key is case insensitive. | [
"Methods",
"returns",
"the",
"property",
"meta",
"of",
"the",
"provided",
"key",
"for",
"the",
"given",
"classId",
".",
"Given",
"key",
"is",
"case",
"insensitive",
"."
] | python | train | 45 |
StorjOld/heartbeat | heartbeat/PySwizzle/PySwizzle.py | https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L149-L160 | def get_hmac(self, key):
"""Returns the keyed HMAC for authentication of this state data.
:param key: the key for the keyed hash function
"""
h = HMAC.new(key, None, SHA256)
h.update(self.iv)
h.update(str(self.chunks).encode())
h.update(self.f_key)
h.upda... | [
"def",
"get_hmac",
"(",
"self",
",",
"key",
")",
":",
"h",
"=",
"HMAC",
".",
"new",
"(",
"key",
",",
"None",
",",
"SHA256",
")",
"h",
".",
"update",
"(",
"self",
".",
"iv",
")",
"h",
".",
"update",
"(",
"str",
"(",
"self",
".",
"chunks",
")",... | Returns the keyed HMAC for authentication of this state data.
:param key: the key for the keyed hash function | [
"Returns",
"the",
"keyed",
"HMAC",
"for",
"authentication",
"of",
"this",
"state",
"data",
"."
] | python | train | 33.333333 |
ribozz/sphinx-argparse | sphinxarg/markdown.py | https://github.com/ribozz/sphinx-argparse/blob/178672cd5c846440ff7ecd695e3708feea13e4b4/sphinxarg/markdown.py#L47-L59 | def paragraph(node):
"""
Process a paragraph, which includes all content under it
"""
text = ''
if node.string_content is not None:
text = node.string_content
o = nodes.paragraph('', ' '.join(text))
o.line = node.sourcepos[0][0]
for n in MarkDown(node):
o.append(n)
r... | [
"def",
"paragraph",
"(",
"node",
")",
":",
"text",
"=",
"''",
"if",
"node",
".",
"string_content",
"is",
"not",
"None",
":",
"text",
"=",
"node",
".",
"string_content",
"o",
"=",
"nodes",
".",
"paragraph",
"(",
"''",
",",
"' '",
".",
"join",
"(",
"... | Process a paragraph, which includes all content under it | [
"Process",
"a",
"paragraph",
"which",
"includes",
"all",
"content",
"under",
"it"
] | python | train | 24.230769 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Util.py#L1452-L1486 | def AddMethod(obj, function, name=None):
"""
Adds either a bound method to an instance or the function itself (or an unbound method in Python 2) to a class.
If name is ommited the name of the specified function
is used by default.
Example::
a = A()
def f(self, x, y):
self.z... | [
"def",
"AddMethod",
"(",
"obj",
",",
"function",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"function",
".",
"__name__",
"else",
":",
"function",
"=",
"RenameFunction",
"(",
"function",
",",
"name",
")",
"# Note t... | Adds either a bound method to an instance or the function itself (or an unbound method in Python 2) to a class.
If name is ommited the name of the specified function
is used by default.
Example::
a = A()
def f(self, x, y):
self.z = x + y
AddMethod(f, A, "add")
a.add... | [
"Adds",
"either",
"a",
"bound",
"method",
"to",
"an",
"instance",
"or",
"the",
"function",
"itself",
"(",
"or",
"an",
"unbound",
"method",
"in",
"Python",
"2",
")",
"to",
"a",
"class",
".",
"If",
"name",
"is",
"ommited",
"the",
"name",
"of",
"the",
"... | python | train | 30.485714 |
cjdrake/pyeda | pyeda/boolalg/expr.py | https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L500-L524 | def NHot(n, *xs, simplify=True):
"""
Return an expression that means
"exactly N input functions are true".
If *simplify* is ``True``, return a simplified expression.
"""
if not isinstance(n, int):
raise TypeError("expected n to be an int")
if not 0 <= n <= len(xs):
fstr = "e... | [
"def",
"NHot",
"(",
"n",
",",
"*",
"xs",
",",
"simplify",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"n",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"expected n to be an int\"",
")",
"if",
"not",
"0",
"<=",
"n",
"<=",
"len",
"("... | Return an expression that means
"exactly N input functions are true".
If *simplify* is ``True``, return a simplified expression. | [
"Return",
"an",
"expression",
"that",
"means",
"exactly",
"N",
"input",
"functions",
"are",
"true",
"."
] | python | train | 31.36 |
bihealth/vcfpy | vcfpy/parser.py | https://github.com/bihealth/vcfpy/blob/99e2165df30f11e0c95f3170f31bc5191d9e9e15/vcfpy/parser.py#L613-L636 | def run(self, key, value, num_alts):
"""Check value in INFO[key] of record
Currently, only checks for consistent counts are implemented
:param str key: key of INFO entry to check
:param value: value to check
:param int alts: list of alternative alleles, for length
"""
... | [
"def",
"run",
"(",
"self",
",",
"key",
",",
"value",
",",
"num_alts",
")",
":",
"field_info",
"=",
"self",
".",
"header",
".",
"get_info_field_info",
"(",
"key",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"TABLE",
... | Check value in INFO[key] of record
Currently, only checks for consistent counts are implemented
:param str key: key of INFO entry to check
:param value: value to check
:param int alts: list of alternative alleles, for length | [
"Check",
"value",
"in",
"INFO",
"[",
"key",
"]",
"of",
"record"
] | python | train | 38.166667 |
genialis/resolwe | resolwe/flow/executors/docker/prepare.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/docker/prepare.py#L46-L57 | def resolve_upload_path(self, filename=None):
"""Resolve upload path for use with the executor.
:param filename: Filename to resolve
:return: Resolved filename, which can be used to access the
given uploaded file in programs executed using this
executor
"""
... | [
"def",
"resolve_upload_path",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"return",
"constants",
".",
"UPLOAD_VOLUME",
"return",
"os",
".",
"path",
".",
"join",
"(",
"constants",
".",
"UPLOAD_VOLUME",
",",
"fil... | Resolve upload path for use with the executor.
:param filename: Filename to resolve
:return: Resolved filename, which can be used to access the
given uploaded file in programs executed using this
executor | [
"Resolve",
"upload",
"path",
"for",
"use",
"with",
"the",
"executor",
"."
] | python | train | 36.583333 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_silva_2008.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L438-L461 | def _compute_e2_factor(self, imt, vs30):
"""
Compute and return e2 factor, equation 19, page 80.
"""
e2 = np.zeros_like(vs30)
if imt.name == "PGV":
period = 1
elif imt.name == "PGA":
period = 0
else:
period = imt.period
... | [
"def",
"_compute_e2_factor",
"(",
"self",
",",
"imt",
",",
"vs30",
")",
":",
"e2",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"if",
"imt",
".",
"name",
"==",
"\"PGV\"",
":",
"period",
"=",
"1",
"elif",
"imt",
".",
"name",
"==",
"\"PGA\"",
":",... | Compute and return e2 factor, equation 19, page 80. | [
"Compute",
"and",
"return",
"e2",
"factor",
"equation",
"19",
"page",
"80",
"."
] | python | train | 29.416667 |
google/grr | grr/client/grr_response_client/comms.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/comms.py#L761-L788 | def OnStartup(self):
"""A handler that is called on client startup."""
# We read the transaction log and fail any requests that are in it. If there
# is anything in the transaction log we assume its there because we crashed
# last time and let the server know.
last_request = self.transaction_log.Ge... | [
"def",
"OnStartup",
"(",
"self",
")",
":",
"# We read the transaction log and fail any requests that are in it. If there",
"# is anything in the transaction log we assume its there because we crashed",
"# last time and let the server know.",
"last_request",
"=",
"self",
".",
"transaction_l... | A handler that is called on client startup. | [
"A",
"handler",
"that",
"is",
"called",
"on",
"client",
"startup",
"."
] | python | train | 36.25 |
ARMmbed/autoversion | src/auto_version/auto_version_tool.py | https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L111-L119 | def get_all_triggers(bump, file_triggers):
"""Aggregated set of significant figures to bump"""
triggers = set()
if file_triggers:
triggers = triggers.union(detect_file_triggers(config.trigger_patterns))
if bump:
_LOG.debug("trigger: %s bump requested", bump)
triggers.add(bump)
... | [
"def",
"get_all_triggers",
"(",
"bump",
",",
"file_triggers",
")",
":",
"triggers",
"=",
"set",
"(",
")",
"if",
"file_triggers",
":",
"triggers",
"=",
"triggers",
".",
"union",
"(",
"detect_file_triggers",
"(",
"config",
".",
"trigger_patterns",
")",
")",
"i... | Aggregated set of significant figures to bump | [
"Aggregated",
"set",
"of",
"significant",
"figures",
"to",
"bump"
] | python | train | 36.555556 |
gem/oq-engine | openquake/hazardlib/correlation.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L29-L71 | def apply_correlation(self, sites, imt, residuals, stddev_intra=0):
"""
Apply correlation to randomly sampled residuals.
:param sites:
:class:`~openquake.hazardlib.site.SiteCollection` residuals were
sampled for.
:param imt:
Intensity measure type obj... | [
"def",
"apply_correlation",
"(",
"self",
",",
"sites",
",",
"imt",
",",
"residuals",
",",
"stddev_intra",
"=",
"0",
")",
":",
"# intra-event residual for a single relization is a product",
"# of lower-triangle decomposed correlation matrix and vector",
"# of N random numbers (whe... | Apply correlation to randomly sampled residuals.
:param sites:
:class:`~openquake.hazardlib.site.SiteCollection` residuals were
sampled for.
:param imt:
Intensity measure type object, see :mod:`openquake.hazardlib.imt`.
:param residuals:
2d numpy ... | [
"Apply",
"correlation",
"to",
"randomly",
"sampled",
"residuals",
"."
] | python | train | 48.813953 |
quikmile/trellio | trellio/utils/log.py | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/utils/log.py#L21-L32 | def formatTime(self, record, datefmt=None): # noqa
"""
Overrides formatTime method to use datetime module instead of time module
to display time in microseconds. Time module by default does not resolve
time to microseconds.
"""
if datefmt:
s = datetime.dateti... | [
"def",
"formatTime",
"(",
"self",
",",
"record",
",",
"datefmt",
"=",
"None",
")",
":",
"# noqa",
"if",
"datefmt",
":",
"s",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"datefmt",
")",
"else",
":",
"t",
"=",
"datet... | Overrides formatTime method to use datetime module instead of time module
to display time in microseconds. Time module by default does not resolve
time to microseconds. | [
"Overrides",
"formatTime",
"method",
"to",
"use",
"datetime",
"module",
"instead",
"of",
"time",
"module",
"to",
"display",
"time",
"in",
"microseconds",
".",
"Time",
"module",
"by",
"default",
"does",
"not",
"resolve",
"time",
"to",
"microseconds",
"."
] | python | train | 41.833333 |
jrief/djangocms-cascade | cmsplugin_cascade/sharable/forms.py | https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/sharable/forms.py#L58-L67 | def _enrich_link(self, glossary):
"""
Enrich the dict glossary['link'] with an identifier onto the model
"""
try:
Model = apps.get_model(*glossary['link']['model'].split('.'))
obj = Model.objects.get(pk=glossary['link']['pk'])
glossary['link'].update(i... | [
"def",
"_enrich_link",
"(",
"self",
",",
"glossary",
")",
":",
"try",
":",
"Model",
"=",
"apps",
".",
"get_model",
"(",
"*",
"glossary",
"[",
"'link'",
"]",
"[",
"'model'",
"]",
".",
"split",
"(",
"'.'",
")",
")",
"obj",
"=",
"Model",
".",
"objects... | Enrich the dict glossary['link'] with an identifier onto the model | [
"Enrich",
"the",
"dict",
"glossary",
"[",
"link",
"]",
"with",
"an",
"identifier",
"onto",
"the",
"model"
] | python | train | 39.4 |
BerkeleyAutomation/autolab_core | autolab_core/tensor_dataset.py | https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/tensor_dataset.py#L415-L419 | def datapoint_indices_for_tensor(self, tensor_index):
""" Returns the indices for all datapoints in the given tensor. """
if tensor_index >= self._num_tensors:
raise ValueError('Tensor index %d is greater than the number of tensors (%d)' %(tensor_index, self._num_tensors))
return sel... | [
"def",
"datapoint_indices_for_tensor",
"(",
"self",
",",
"tensor_index",
")",
":",
"if",
"tensor_index",
">=",
"self",
".",
"_num_tensors",
":",
"raise",
"ValueError",
"(",
"'Tensor index %d is greater than the number of tensors (%d)'",
"%",
"(",
"tensor_index",
",",
"s... | Returns the indices for all datapoints in the given tensor. | [
"Returns",
"the",
"indices",
"for",
"all",
"datapoints",
"in",
"the",
"given",
"tensor",
"."
] | python | train | 70.4 |
jasonrollins/shareplum | shareplum/shareplum.py | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L376-L411 | def _python_type(self, key, value):
"""Returns proper type from the schema"""
try:
field_type = self._sp_cols[key]['type']
if field_type in ['Number', 'Currency']:
return float(value)
elif field_type == 'DateTime':
# Need to remove th... | [
"def",
"_python_type",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"try",
":",
"field_type",
"=",
"self",
".",
"_sp_cols",
"[",
"key",
"]",
"[",
"'type'",
"]",
"if",
"field_type",
"in",
"[",
"'Number'",
",",
"'Currency'",
"]",
":",
"return",
"fl... | Returns proper type from the schema | [
"Returns",
"proper",
"type",
"from",
"the",
"schema"
] | python | train | 39.916667 |
thumbor/thumbor | thumbor/engines/extensions/pil.py | https://github.com/thumbor/thumbor/blob/558ccdd6e3bc29e1c9ee3687372c4b3eb05ac607/thumbor/engines/extensions/pil.py#L554-L601 | def readGif(filename, asNumpy=True):
""" readGif(filename, asNumpy=True)
Read images from an animated GIF file. Returns a list of numpy
arrays, or, if asNumpy is false, a list if PIL images.
"""
# Check PIL
if PIL is None:
raise RuntimeError("Need PIL to read animated gif files.")
... | [
"def",
"readGif",
"(",
"filename",
",",
"asNumpy",
"=",
"True",
")",
":",
"# Check PIL",
"if",
"PIL",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Need PIL to read animated gif files.\"",
")",
"# Check Numpy",
"if",
"np",
"is",
"None",
":",
"raise",
"Ru... | readGif(filename, asNumpy=True)
Read images from an animated GIF file. Returns a list of numpy
arrays, or, if asNumpy is false, a list if PIL images. | [
"readGif",
"(",
"filename",
"asNumpy",
"=",
"True",
")"
] | python | train | 26.270833 |
emin63/eyap | eyap/core/github_comments.py | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/github_comments.py#L254-L300 | def lookup_thread_id(self):
"""Lookup thread id as required by CommentThread.lookup_thread_id.
This implementation will query GitHub with the required parameters
to try and find the topic for the owner, realm, topic, etc., specified
in init.
"""
query_string = 'in:title... | [
"def",
"lookup_thread_id",
"(",
"self",
")",
":",
"query_string",
"=",
"'in:title \"%s\" repo:%s/%s'",
"%",
"(",
"self",
".",
"topic",
",",
"self",
".",
"owner",
",",
"self",
".",
"realm",
")",
"cache_key",
"=",
"(",
"self",
".",
"owner",
",",
"self",
".... | Lookup thread id as required by CommentThread.lookup_thread_id.
This implementation will query GitHub with the required parameters
to try and find the topic for the owner, realm, topic, etc., specified
in init. | [
"Lookup",
"thread",
"id",
"as",
"required",
"by",
"CommentThread",
".",
"lookup_thread_id",
"."
] | python | train | 42.93617 |
objectrocket/python-client | objectrocket/instances/__init__.py | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/__init__.py#L99-L123 | def _concrete_instance(self, instance_doc):
"""Concretize an instance document.
:param dict instance_doc: A document describing an instance. Should come from the API.
:returns: A subclass of :py:class:`bases.BaseInstance`, or None.
:rtype: :py:class:`bases.BaseInstance`
"""
... | [
"def",
"_concrete_instance",
"(",
"self",
",",
"instance_doc",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance_doc",
",",
"dict",
")",
":",
"return",
"None",
"# Attempt to instantiate the appropriate class for the given instance document.",
"try",
":",
"service",
"=... | Concretize an instance document.
:param dict instance_doc: A document describing an instance. Should come from the API.
:returns: A subclass of :py:class:`bases.BaseInstance`, or None.
:rtype: :py:class:`bases.BaseInstance` | [
"Concretize",
"an",
"instance",
"document",
"."
] | python | train | 42.28 |
pypa/pipenv | pipenv/vendor/distlib/_backport/tarfile.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L479-L486 | def __write(self, s):
"""Write string s to the stream if a whole new block
is ready to be written.
"""
self.buf += s
while len(self.buf) > self.bufsize:
self.fileobj.write(self.buf[:self.bufsize])
self.buf = self.buf[self.bufsize:] | [
"def",
"__write",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"buf",
"+=",
"s",
"while",
"len",
"(",
"self",
".",
"buf",
")",
">",
"self",
".",
"bufsize",
":",
"self",
".",
"fileobj",
".",
"write",
"(",
"self",
".",
"buf",
"[",
":",
"self",
... | Write string s to the stream if a whole new block
is ready to be written. | [
"Write",
"string",
"s",
"to",
"the",
"stream",
"if",
"a",
"whole",
"new",
"block",
"is",
"ready",
"to",
"be",
"written",
"."
] | python | train | 36.375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.