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 |
|---|---|---|---|---|---|---|---|---|---|
ansible/tacacs_plus | tacacs_plus/client.py | https://github.com/ansible/tacacs_plus/blob/de0d01372169c8849fa284d75097e57367c8930f/tacacs_plus/client.py#L155-L224 | def authenticate(self, username, password, priv_lvl=TAC_PLUS_PRIV_LVL_MIN,
authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII,
chap_ppp_id=None, chap_challenge=None,
rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT):
"""
Authenticate to a ... | [
"def",
"authenticate",
"(",
"self",
",",
"username",
",",
"password",
",",
"priv_lvl",
"=",
"TAC_PLUS_PRIV_LVL_MIN",
",",
"authen_type",
"=",
"TAC_PLUS_AUTHEN_TYPE_ASCII",
",",
"chap_ppp_id",
"=",
"None",
",",
"chap_challenge",
"=",
"None",
",",
"rem_addr",
"=",
... | Authenticate to a TACACS+ server with a username and password.
:param username:
:param password:
:param priv_lvl:
:param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII,
TAC_PLUS_AUTHEN_TYPE_PAP,
TAC_PLUS_AUTHEN_TYPE_CHAP
... | [
"Authenticate",
"to",
"a",
"TACACS",
"+",
"server",
"with",
"a",
"username",
"and",
"password",
"."
] | python | train | 47.4 |
shaypal5/utilitime | utilitime/timestamp/timestamp.py | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L58-L63 | def get_timestamp(timezone_name, year, month, day, hour=0, minute=0):
"""Epoch timestamp from timezone, year, month, day, hour and minute."""
tz = pytz.timezone(timezone_name)
tz_datetime = tz.localize(datetime(year, month, day, hour, minute))
timestamp = calendar.timegm(tz_datetime.utctimetuple())
... | [
"def",
"get_timestamp",
"(",
"timezone_name",
",",
"year",
",",
"month",
",",
"day",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"timezone_name",
")",
"tz_datetime",
"=",
"tz",
".",
"localize",
"... | Epoch timestamp from timezone, year, month, day, hour and minute. | [
"Epoch",
"timestamp",
"from",
"timezone",
"year",
"month",
"day",
"hour",
"and",
"minute",
"."
] | python | train | 55.166667 |
FlorianRhiem/pyGLFW | glfw/__init__.py | https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L1578-L1598 | def set_scroll_callback(window, cbfun):
"""
Sets the scroll callback.
Wrapper for:
GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
... | [
"def",
"set_scroll_callback",
"(",
"window",
",",
"cbfun",
")",
":",
"window_addr",
"=",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"pointer",
"(",
"window",
")",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_long",
")",
")",
".",
"contents",
"... | Sets the scroll callback.
Wrapper for:
GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); | [
"Sets",
"the",
"scroll",
"callback",
"."
] | python | train | 36.809524 |
shoebot/shoebot | shoebot/kgp.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/kgp.py#L38-L84 | def openAnything(source, searchpaths=None):
"""URI, filename, or string --> stream
This function lets you define parsers that take any input source
(URL, pathname to local or network file, or actual data as a string)
and deal with it in a uniform manner. Returned object is guaranteed
to have... | [
"def",
"openAnything",
"(",
"source",
",",
"searchpaths",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"\"read\"",
")",
":",
"return",
"source",
"if",
"source",
"==",
"\"-\"",
":",
"import",
"sys",
"return",
"sys",
".",
"stdin",
"# try to ... | URI, filename, or string --> stream
This function lets you define parsers that take any input source
(URL, pathname to local or network file, or actual data as a string)
and deal with it in a uniform manner. Returned object is guaranteed
to have all the basic stdio read methods (read, readline, r... | [
"URI",
"filename",
"or",
"string",
"--",
">",
"stream",
"This",
"function",
"lets",
"you",
"define",
"parsers",
"that",
"take",
"any",
"input",
"source",
"(",
"URL",
"pathname",
"to",
"local",
"or",
"network",
"file",
"or",
"actual",
"data",
"as",
"a",
"... | python | valid | 31.787234 |
senaite/senaite.core | bika/lims/upgrade/v01_01_006.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/upgrade/v01_01_006.py#L348-L368 | def touidref(src, dst, src_relation, src_portal_type, fieldname):
"""Convert an archetypes reference in src/src_relation to a UIDReference
in dst/fieldname.
"""
field = dst.getField(fieldname)
refs = src.getRefs(relationship=src_relation)
if len(refs) == 1:
value = get_uid(refs[0])
... | [
"def",
"touidref",
"(",
"src",
",",
"dst",
",",
"src_relation",
",",
"src_portal_type",
",",
"fieldname",
")",
":",
"field",
"=",
"dst",
".",
"getField",
"(",
"fieldname",
")",
"refs",
"=",
"src",
".",
"getRefs",
"(",
"relationship",
"=",
"src_relation",
... | Convert an archetypes reference in src/src_relation to a UIDReference
in dst/fieldname. | [
"Convert",
"an",
"archetypes",
"reference",
"in",
"src",
"/",
"src_relation",
"to",
"a",
"UIDReference",
"in",
"dst",
"/",
"fieldname",
"."
] | python | train | 35.47619 |
harvard-nrg/yaxil | yaxil/__init__.py | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L80-L138 | def auth(alias=None, url=None, cfg="~/.xnat_auth"):
'''
Read connection details from an xnat_auth XML file
Example:
>>> import yaxil
>>> auth = yaxil.auth('xnatastic')
>>> auth.url, auth.username, auth.password
('https://www.xnatastic.org/', 'username', '********')
:par... | [
"def",
"auth",
"(",
"alias",
"=",
"None",
",",
"url",
"=",
"None",
",",
"cfg",
"=",
"\"~/.xnat_auth\"",
")",
":",
"if",
"not",
"alias",
"and",
"not",
"url",
":",
"raise",
"ValueError",
"(",
"'you must provide an alias or url argument'",
")",
"if",
"alias",
... | Read connection details from an xnat_auth XML file
Example:
>>> import yaxil
>>> auth = yaxil.auth('xnatastic')
>>> auth.url, auth.username, auth.password
('https://www.xnatastic.org/', 'username', '********')
:param alias: XNAT alias
:type alias: str
:param url: XNAT U... | [
"Read",
"connection",
"details",
"from",
"an",
"xnat_auth",
"XML",
"file"
] | python | train | 35.847458 |
shopkick/flawless | flawless/client/decorators.py | https://github.com/shopkick/flawless/blob/c54b63ca1991c153e6f75080536f6df445aacc64/flawless/client/decorators.py#L44-L58 | def wrap_class(cls, error_threshold=None):
''' Wraps a class with reporting to errors backend by decorating each function of the class.
Decorators are injected under the classmethod decorator if they exist.
'''
methods = inspect.getmembers(cls, inspect.ismethod) + inspect.getmembers(cls, inspect... | [
"def",
"wrap_class",
"(",
"cls",
",",
"error_threshold",
"=",
"None",
")",
":",
"methods",
"=",
"inspect",
".",
"getmembers",
"(",
"cls",
",",
"inspect",
".",
"ismethod",
")",
"+",
"inspect",
".",
"getmembers",
"(",
"cls",
",",
"inspect",
".",
"isfunctio... | Wraps a class with reporting to errors backend by decorating each function of the class.
Decorators are injected under the classmethod decorator if they exist. | [
"Wraps",
"a",
"class",
"with",
"reporting",
"to",
"errors",
"backend",
"by",
"decorating",
"each",
"function",
"of",
"the",
"class",
".",
"Decorators",
"are",
"injected",
"under",
"the",
"classmethod",
"decorator",
"if",
"they",
"exist",
"."
] | python | test | 50.4 |
Workiva/furious | furious/extras/appengine/ndb_persistence.py | https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L156-L184 | def _completion_checker(async_id, context_id):
"""Check if all Async jobs within a Context have been run."""
if not context_id:
logging.debug("Context for async %s does not exist", async_id)
return
context = FuriousContext.from_id(context_id)
marker = FuriousCompletionMarker.get_by_id(... | [
"def",
"_completion_checker",
"(",
"async_id",
",",
"context_id",
")",
":",
"if",
"not",
"context_id",
":",
"logging",
".",
"debug",
"(",
"\"Context for async %s does not exist\"",
",",
"async_id",
")",
"return",
"context",
"=",
"FuriousContext",
".",
"from_id",
"... | Check if all Async jobs within a Context have been run. | [
"Check",
"if",
"all",
"Async",
"jobs",
"within",
"a",
"Context",
"have",
"been",
"run",
"."
] | python | train | 25.793103 |
PredixDev/predixpy | predix/admin/cf/orgs.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/orgs.py#L68-L74 | def add_user(self, user_name, role='user'):
"""
Calls CF's associate user with org. Valid roles include `user`, `auditor`,
`manager`,`billing_manager`
"""
role_uri = self._get_role_uri(role=role)
return self.api.put(path=role_uri, data={'username': user_name}) | [
"def",
"add_user",
"(",
"self",
",",
"user_name",
",",
"role",
"=",
"'user'",
")",
":",
"role_uri",
"=",
"self",
".",
"_get_role_uri",
"(",
"role",
"=",
"role",
")",
"return",
"self",
".",
"api",
".",
"put",
"(",
"path",
"=",
"role_uri",
",",
"data",... | Calls CF's associate user with org. Valid roles include `user`, `auditor`,
`manager`,`billing_manager` | [
"Calls",
"CF",
"s",
"associate",
"user",
"with",
"org",
".",
"Valid",
"roles",
"include",
"user",
"auditor",
"manager",
"billing_manager"
] | python | train | 43.142857 |
guzzle/guzzle_sphinx_theme | guzzle_sphinx_theme/__init__.py | https://github.com/guzzle/guzzle_sphinx_theme/blob/eefd45b79383b1b4aab1607444e41366fd1348a6/guzzle_sphinx_theme/__init__.py#L23-L27 | def add_html_link(app, pagename, templatename, context, doctree):
"""As each page is built, collect page names for the sitemap"""
base_url = app.config['html_theme_options'].get('base_url', '')
if base_url:
app.sitemap_links.append(base_url + pagename + ".html") | [
"def",
"add_html_link",
"(",
"app",
",",
"pagename",
",",
"templatename",
",",
"context",
",",
"doctree",
")",
":",
"base_url",
"=",
"app",
".",
"config",
"[",
"'html_theme_options'",
"]",
".",
"get",
"(",
"'base_url'",
",",
"''",
")",
"if",
"base_url",
... | As each page is built, collect page names for the sitemap | [
"As",
"each",
"page",
"is",
"built",
"collect",
"page",
"names",
"for",
"the",
"sitemap"
] | python | train | 55.6 |
ioos/cc-plugin-ncei | cc_plugin_ncei/util.py | https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/util.py#L111-L122 | def get_lat_variable(nc):
'''
Returns the variable for latitude
:param netcdf4.dataset nc: an open netcdf dataset object
'''
if 'latitude' in nc.variables:
return 'latitude'
latitudes = nc.get_variables_by_attributes(standard_name="latitude")
if latitudes:
return latitudes[0... | [
"def",
"get_lat_variable",
"(",
"nc",
")",
":",
"if",
"'latitude'",
"in",
"nc",
".",
"variables",
":",
"return",
"'latitude'",
"latitudes",
"=",
"nc",
".",
"get_variables_by_attributes",
"(",
"standard_name",
"=",
"\"latitude\"",
")",
"if",
"latitudes",
":",
"... | Returns the variable for latitude
:param netcdf4.dataset nc: an open netcdf dataset object | [
"Returns",
"the",
"variable",
"for",
"latitude"
] | python | train | 27.583333 |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/model.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/model.py#L973-L985 | def reset_for_retry(self):
"""Reset self for shard retry."""
self.retries += 1
self.last_work_item = ""
self.active = True
self.result_status = None
self.input_finished = False
self.counters_map = CountersMap()
self.slice_id = 0
self.slice_start_time = None
self.slice_request_id ... | [
"def",
"reset_for_retry",
"(",
"self",
")",
":",
"self",
".",
"retries",
"+=",
"1",
"self",
".",
"last_work_item",
"=",
"\"\"",
"self",
".",
"active",
"=",
"True",
"self",
".",
"result_status",
"=",
"None",
"self",
".",
"input_finished",
"=",
"False",
"s... | Reset self for shard retry. | [
"Reset",
"self",
"for",
"shard",
"retry",
"."
] | python | train | 28.615385 |
myyang/django-unixtimestampfield | unixtimestampfield/fields.py | https://github.com/myyang/django-unixtimestampfield/blob/d647681cd628d1a5cdde8dcbb025bcb9612e9b24/unixtimestampfield/fields.py#L347-L364 | def to_utc_datetime(self, value):
"""
from value to datetime with tzinfo format (datetime.datetime instance)
"""
if isinstance(value, (six.integer_types, float, six.string_types)):
value = self.to_naive_datetime(value)
if isinstance(value, datetime.datetime):
... | [
"def",
"to_utc_datetime",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"six",
".",
"integer_types",
",",
"float",
",",
"six",
".",
"string_types",
")",
")",
":",
"value",
"=",
"self",
".",
"to_naive_datetime",
"(",
"... | from value to datetime with tzinfo format (datetime.datetime instance) | [
"from",
"value",
"to",
"datetime",
"with",
"tzinfo",
"format",
"(",
"datetime",
".",
"datetime",
"instance",
")"
] | python | train | 37.222222 |
python-rope/rope | rope/refactor/inline.py | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/inline.py#L113-L151 | def get_changes(self, remove=True, only_current=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get the changes this refactoring makes
If `remove` is `False` the definition will not be removed. If
`only_current` is `True`, the the current occurrence will... | [
"def",
"get_changes",
"(",
"self",
",",
"remove",
"=",
"True",
",",
"only_current",
"=",
"False",
",",
"resources",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"changes",
"=",
"ChangeSet",
"(",
"'Inline me... | Get the changes this refactoring makes
If `remove` is `False` the definition will not be removed. If
`only_current` is `True`, the the current occurrence will be
inlined, only. | [
"Get",
"the",
"changes",
"this",
"refactoring",
"makes"
] | python | train | 47.025641 |
marshmallow-code/webargs | src/webargs/pyramidparser.py | https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/pyramidparser.py#L79-L82 | def parse_files(self, req, name, field):
"""Pull a file from the request."""
files = ((k, v) for k, v in req.POST.items() if hasattr(v, "file"))
return core.get_value(MultiDict(files), name, field) | [
"def",
"parse_files",
"(",
"self",
",",
"req",
",",
"name",
",",
"field",
")",
":",
"files",
"=",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"req",
".",
"POST",
".",
"items",
"(",
")",
"if",
"hasattr",
"(",
"v",
",",
"\"file\""... | Pull a file from the request. | [
"Pull",
"a",
"file",
"from",
"the",
"request",
"."
] | python | train | 54.5 |
AdvancedClimateSystems/uModbus | umodbus/client/serial/rtu.py | https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/client/serial/rtu.py#L161-L171 | def write_multiple_registers(slave_id, starting_address, values):
""" Return ADU for Modbus function code 16: Write Multiple Registers.
:param slave_id: Number of slave.
:return: Byte array with ADU.
"""
function = WriteMultipleRegisters()
function.starting_address = starting_address
functi... | [
"def",
"write_multiple_registers",
"(",
"slave_id",
",",
"starting_address",
",",
"values",
")",
":",
"function",
"=",
"WriteMultipleRegisters",
"(",
")",
"function",
".",
"starting_address",
"=",
"starting_address",
"function",
".",
"values",
"=",
"values",
"return... | Return ADU for Modbus function code 16: Write Multiple Registers.
:param slave_id: Number of slave.
:return: Byte array with ADU. | [
"Return",
"ADU",
"for",
"Modbus",
"function",
"code",
"16",
":",
"Write",
"Multiple",
"Registers",
"."
] | python | train | 35.636364 |
googlefonts/fontbakery | Lib/fontbakery/checkrunner.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/checkrunner.py#L622-L630 | def check_order(self, order):
"""
order must be a subset of self.order
"""
own_order = self.order
for item in order:
if item not in own_order:
raise ValueError(f'Order item {item} not found.')
return order | [
"def",
"check_order",
"(",
"self",
",",
"order",
")",
":",
"own_order",
"=",
"self",
".",
"order",
"for",
"item",
"in",
"order",
":",
"if",
"item",
"not",
"in",
"own_order",
":",
"raise",
"ValueError",
"(",
"f'Order item {item} not found.'",
")",
"return",
... | order must be a subset of self.order | [
"order",
"must",
"be",
"a",
"subset",
"of",
"self",
".",
"order"
] | python | train | 26.333333 |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L59-L111 | def _prepare_configs(configs, requires_filters, temporal_timeouts):
"""
Overrides the filters specified in the decorator with the given ones
:param configs: Field → (Requirement, key, allow_none) dictionary
:param requires_filters: Content of the 'requires.filter' component
... | [
"def",
"_prepare_configs",
"(",
"configs",
",",
"requires_filters",
",",
"temporal_timeouts",
")",
":",
"if",
"not",
"isinstance",
"(",
"requires_filters",
",",
"dict",
")",
":",
"requires_filters",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"temporal_timeou... | Overrides the filters specified in the decorator with the given ones
:param configs: Field → (Requirement, key, allow_none) dictionary
:param requires_filters: Content of the 'requires.filter' component
property (field → string)
:param temporal_timeouts: Content... | [
"Overrides",
"the",
"filters",
"specified",
"in",
"the",
"decorator",
"with",
"the",
"given",
"ones"
] | python | train | 40.90566 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/mprofile.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/mprofile.py#L49-L61 | def codepoint_included(self, codepoint):
"""Check if codepoint matches any of the defined codepoints."""
if self.codepoints == None:
return True
for cp in self.codepoints:
mismatch = False
for i in range(len(cp)):
if (cp[i] is not None) and (cp... | [
"def",
"codepoint_included",
"(",
"self",
",",
"codepoint",
")",
":",
"if",
"self",
".",
"codepoints",
"==",
"None",
":",
"return",
"True",
"for",
"cp",
"in",
"self",
".",
"codepoints",
":",
"mismatch",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"le... | Check if codepoint matches any of the defined codepoints. | [
"Check",
"if",
"codepoint",
"matches",
"any",
"of",
"the",
"defined",
"codepoints",
"."
] | python | train | 36.076923 |
googledatalab/pydatalab | datalab/utils/commands/_commands.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_commands.py#L49-L64 | def create_args(line, namespace):
""" Expand any meta-variable references in the argument list. """
args = []
# Using shlex.split handles quotes args and escape characters.
for arg in shlex.split(line):
if not arg:
continue
if arg[0] == '$':
var_name = arg[1:]
if var... | [
"def",
"create_args",
"(",
"line",
",",
"namespace",
")",
":",
"args",
"=",
"[",
"]",
"# Using shlex.split handles quotes args and escape characters.",
"for",
"arg",
"in",
"shlex",
".",
"split",
"(",
"line",
")",
":",
"if",
"not",
"arg",
":",
"continue",
"if",... | Expand any meta-variable references in the argument list. | [
"Expand",
"any",
"meta",
"-",
"variable",
"references",
"in",
"the",
"argument",
"list",
"."
] | python | train | 32.5625 |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/directory.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L2533-L2731 | def save(self):
"""
:return: save this OS instance on Ariane server (create or update)
"""
LOGGER.debug("OSInstance.save")
post_payload = {}
consolidated_osi_id = []
consolidated_ipa_id = []
consolidated_nic_id = []
consolidated_app_id = []
... | [
"def",
"save",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"OSInstance.save\"",
")",
"post_payload",
"=",
"{",
"}",
"consolidated_osi_id",
"=",
"[",
"]",
"consolidated_ipa_id",
"=",
"[",
"]",
"consolidated_nic_id",
"=",
"[",
"]",
"consolidated_app_id... | :return: save this OS instance on Ariane server (create or update) | [
":",
"return",
":",
"save",
"this",
"OS",
"instance",
"on",
"Ariane",
"server",
"(",
"create",
"or",
"update",
")"
] | python | train | 41.914573 |
googleapis/google-cloud-python | websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/websecurityscanner/google/cloud/websecurityscanner_v1alpha/gapic/web_security_scanner_client.py#L87-L95 | def finding_path(cls, project, scan_config, scan_run, finding):
"""Return a fully-qualified finding string."""
return google.api_core.path_template.expand(
"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/{finding}",
project=project,
scan_con... | [
"def",
"finding_path",
"(",
"cls",
",",
"project",
",",
"scan_config",
",",
"scan_run",
",",
"finding",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/scanConfigs/{scan_config}/scanRuns/{scan_run}/findings/... | Return a fully-qualified finding string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"finding",
"string",
"."
] | python | train | 44.222222 |
freakboy3742/pyxero | xero/auth.py | https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L165-L177 | def _init_oauth(self, oauth_token, oauth_token_secret):
"Store and initialize a verified set of OAuth credentials"
self.oauth_token = oauth_token
self.oauth_token_secret = oauth_token_secret
self._oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_sec... | [
"def",
"_init_oauth",
"(",
"self",
",",
"oauth_token",
",",
"oauth_token_secret",
")",
":",
"self",
".",
"oauth_token",
"=",
"oauth_token",
"self",
".",
"oauth_token_secret",
"=",
"oauth_token_secret",
"self",
".",
"_oauth",
"=",
"OAuth1",
"(",
"self",
".",
"c... | Store and initialize a verified set of OAuth credentials | [
"Store",
"and",
"initialize",
"a",
"verified",
"set",
"of",
"OAuth",
"credentials"
] | python | train | 39.692308 |
taskcluster/taskcluster-client.py | taskcluster/queue.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/queue.py#L241-L263 | def cancelTask(self, *args, **kwargs):
"""
Cancel Task
This method will cancel a task that is either `unscheduled`, `pending` or
`running`. It will resolve the current run as `exception` with
`reasonResolved` set to `canceled`. If the task isn't scheduled yet, ie.
it doe... | [
"def",
"cancelTask",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"cancelTask\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Cancel Task
This method will cancel a task that is either `unscheduled`, `pending` or
`running`. It will resolve the current run as `exception` with
`reasonResolved` set to `canceled`. If the task isn't scheduled yet, ie.
it doesn't have any runs, an initial run will be added and resolv... | [
"Cancel",
"Task"
] | python | train | 45.391304 |
NetEaseGame/ATX | atx/drivers/mixin.py | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L246-L332 | def match(self, pattern, screen=None, rect=None, offset=None, threshold=None, method=None):
"""Check if image position in screen
Args:
- pattern: Image file name or opencv image object
- screen (PIL.Image): optional, if not None, screenshot method will be called
- th... | [
"def",
"match",
"(",
"self",
",",
"pattern",
",",
"screen",
"=",
"None",
",",
"rect",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"threshold",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"pattern",
"=",
"self",
".",
"pattern_open",
"(",
"p... | Check if image position in screen
Args:
- pattern: Image file name or opencv image object
- screen (PIL.Image): optional, if not None, screenshot method will be called
- threshold (float): it depends on the image match method
- method (string): choices on <templa... | [
"Check",
"if",
"image",
"position",
"in",
"screen"
] | python | train | 40.011494 |
shin-/dockerpy-creds | dockerpycreds/store.py | https://github.com/shin-/dockerpy-creds/blob/9c0b66d2e445a838e1518f2c3273df7ddc7ec0d4/dockerpycreds/store.py#L29-L47 | def get(self, server):
""" Retrieve credentials for `server`. If no credentials are found,
a `StoreError` will be raised.
"""
if not isinstance(server, six.binary_type):
server = server.encode('utf-8')
data = self._execute('get', server)
result = json.load... | [
"def",
"get",
"(",
"self",
",",
"server",
")",
":",
"if",
"not",
"isinstance",
"(",
"server",
",",
"six",
".",
"binary_type",
")",
":",
"server",
"=",
"server",
".",
"encode",
"(",
"'utf-8'",
")",
"data",
"=",
"self",
".",
"_execute",
"(",
"'get'",
... | Retrieve credentials for `server`. If no credentials are found,
a `StoreError` will be raised. | [
"Retrieve",
"credentials",
"for",
"server",
".",
"If",
"no",
"credentials",
"are",
"found",
"a",
"StoreError",
"will",
"be",
"raised",
"."
] | python | train | 41.210526 |
jtwhite79/pyemu | pyemu/mat/mat_handler.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/mat/mat_handler.py#L1100-L1114 | def full_s(self):
""" Get the full singular value matrix of self
Returns
-------
Matrix : Matrix
"""
x = np.zeros((self.shape),dtype=np.float32)
x[:self.s.shape[0],:self.s.shape[0]] = self.s.as_2d
s = Matrix(x=x, row_names=self.row_names,
... | [
"def",
"full_s",
"(",
"self",
")",
":",
"x",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"shape",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"x",
"[",
":",
"self",
".",
"s",
".",
"shape",
"[",
"0",
"]",
",",
":",
"self",
".",
... | Get the full singular value matrix of self
Returns
-------
Matrix : Matrix | [
"Get",
"the",
"full",
"singular",
"value",
"matrix",
"of",
"self"
] | python | train | 28.066667 |
lsbardel/python-stdnet | stdnet/odm/struct.py | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/struct.py#L661-L663 | def push_front(self, value):
'''Appends a copy of ``value`` to the beginning of the list.'''
self.cache.push_front(self.value_pickler.dumps(value)) | [
"def",
"push_front",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"cache",
".",
"push_front",
"(",
"self",
".",
"value_pickler",
".",
"dumps",
"(",
"value",
")",
")"
] | Appends a copy of ``value`` to the beginning of the list. | [
"Appends",
"a",
"copy",
"of",
"value",
"to",
"the",
"beginning",
"of",
"the",
"list",
"."
] | python | train | 54.333333 |
maweigert/gputools | gputools/denoise/tv2.py | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/denoise/tv2.py#L80-L113 | def tv2(data,weight,Niter=50):
"""
chambolles tv regularized denoising
weight should be around 2+1.5*noise_sigma
"""
prog = OCLProgram(abspath("kernels/tv2.cl"))
data_im = OCLImage.from_array(data.astype(np,float32,copy=False))
pImgs = [ dev.createImage(data.shape[::-1],
... | [
"def",
"tv2",
"(",
"data",
",",
"weight",
",",
"Niter",
"=",
"50",
")",
":",
"prog",
"=",
"OCLProgram",
"(",
"abspath",
"(",
"\"kernels/tv2.cl\"",
")",
")",
"data_im",
"=",
"OCLImage",
".",
"from_array",
"(",
"data",
".",
"astype",
"(",
"np",
",",
"f... | chambolles tv regularized denoising
weight should be around 2+1.5*noise_sigma | [
"chambolles",
"tv",
"regularized",
"denoising"
] | python | train | 36.029412 |
pandas-dev/pandas | pandas/core/ops.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/ops.py#L2422-L2447 | def _arith_method_SPARSE_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
op_name = _get_op_name(op, special)
def wrapper(self, other):
if isinstance(other, ABCDataFrame):
return NotImplemented
elif isins... | [
"def",
"_arith_method_SPARSE_SERIES",
"(",
"cls",
",",
"op",
",",
"special",
")",
":",
"op_name",
"=",
"_get_op_name",
"(",
"op",
",",
"special",
")",
"def",
"wrapper",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"ABCDataF... | Wrapper function for Series arithmetic operations, to avoid
code duplication. | [
"Wrapper",
"function",
"for",
"Series",
"arithmetic",
"operations",
"to",
"avoid",
"code",
"duplication",
"."
] | python | train | 38.346154 |
rafaelmartins/dnsimple-dyndns | dnsimple_dyndns/dnsimple.py | https://github.com/rafaelmartins/dnsimple-dyndns/blob/36d9ec7508673b5354d324cf7c59128440d5bfd1/dnsimple_dyndns/dnsimple.py#L62-L77 | def _update_record(self, record_id, name, address, ttl):
"""Updates an existing record."""
data = json.dumps({'record': {'name': name,
'content': address,
'ttl': ttl}})
headers = {'Content-Type': 'application/json'}
... | [
"def",
"_update_record",
"(",
"self",
",",
"record_id",
",",
"name",
",",
"address",
",",
"ttl",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'record'",
":",
"{",
"'name'",
":",
"name",
",",
"'content'",
":",
"address",
",",
"'ttl'",
":",
... | Updates an existing record. | [
"Updates",
"an",
"existing",
"record",
"."
] | python | train | 55.5 |
emencia/emencia-django-forum | forum/forms/category.py | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/category.py#L29-L38 | def clean_description(self):
"""
Text content validation
"""
description = self.cleaned_data.get("description")
validation_helper = safe_import_module(settings.FORUM_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, d... | [
"def",
"clean_description",
"(",
"self",
")",
":",
"description",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"\"description\"",
")",
"validation_helper",
"=",
"safe_import_module",
"(",
"settings",
".",
"FORUM_TEXT_VALIDATOR_HELPER_PATH",
")",
"if",
"validat... | Text content validation | [
"Text",
"content",
"validation"
] | python | train | 36.7 |
mitsei/dlkit | dlkit/json_/assessment/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/managers.py#L2128-L2144 | def get_item_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the item administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.ItemAdminSession) - an
``ItemAdminSession``
raise: NullArgument - ``proxy`` is ``null... | [
"def",
"get_item_admin_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_item_admin",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"ItemAdminSession",
... | Gets the ``OsidSession`` associated with the item administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.ItemAdminSession) - an
``ItemAdminSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to compl... | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"the",
"item",
"administration",
"service",
"."
] | python | train | 44.941176 |
QInfer/python-qinfer | src/qinfer/utils.py | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L235-L287 | def particle_covariance_mtx(weights,locations):
"""
Returns an estimate of the covariance of a distribution
represented by a given set of SMC particle.
:param weights: An array containing the weights of each
particle.
:param location: An array containing the locations of
each partic... | [
"def",
"particle_covariance_mtx",
"(",
"weights",
",",
"locations",
")",
":",
"# TODO: add shapes to docstring.",
"warnings",
".",
"warn",
"(",
"'particle_covariance_mtx is deprecated, please use distributions.ParticleDistribution'",
",",
"DeprecationWarning",
")",
"# Find the mean... | Returns an estimate of the covariance of a distribution
represented by a given set of SMC particle.
:param weights: An array containing the weights of each
particle.
:param location: An array containing the locations of
each particle.
:rtype: :class:`numpy.ndarray`, shape
``(n_m... | [
"Returns",
"an",
"estimate",
"of",
"the",
"covariance",
"of",
"a",
"distribution",
"represented",
"by",
"a",
"given",
"set",
"of",
"SMC",
"particle",
"."
] | python | train | 41.679245 |
tjcsl/ion | intranet/apps/notifications/views.py | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/notifications/views.py#L22-L49 | def android_setup_view(request):
"""Set up a GCM session.
This does *not* require a valid login session. Instead, a token from the client
session is sent to the Android backend, which queries a POST request to this view.
The "android_gcm_rand" is randomly set when the Android app is detected through
... | [
"def",
"android_setup_view",
"(",
"request",
")",
":",
"logger",
".",
"debug",
"(",
"request",
".",
"POST",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"if",
"\"user_token\"",
"in",
"request",
".",
"POST",
"and",
"\"gcm_token\"",
"in",
"req... | Set up a GCM session.
This does *not* require a valid login session. Instead, a token from the client
session is sent to the Android backend, which queries a POST request to this view.
The "android_gcm_rand" is randomly set when the Android app is detected through
the user agent. If it has the same val... | [
"Set",
"up",
"a",
"GCM",
"session",
".",
"This",
"does",
"*",
"not",
"*",
"require",
"a",
"valid",
"login",
"session",
".",
"Instead",
"a",
"token",
"from",
"the",
"client",
"session",
"is",
"sent",
"to",
"the",
"Android",
"backend",
"which",
"queries",
... | python | train | 46.357143 |
manrajgrover/halo | halo/halo.py | https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L321-L334 | def clear(self):
"""Clears the line and returns cursor to the start.
of line
Returns
-------
self
"""
if not self._enabled:
return self
self._stream.write('\r')
self._stream.write(self.CLEAR_LINE)
return self | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_enabled",
":",
"return",
"self",
"self",
".",
"_stream",
".",
"write",
"(",
"'\\r'",
")",
"self",
".",
"_stream",
".",
"write",
"(",
"self",
".",
"CLEAR_LINE",
")",
"return",
"self"
] | Clears the line and returns cursor to the start.
of line
Returns
-------
self | [
"Clears",
"the",
"line",
"and",
"returns",
"cursor",
"to",
"the",
"start",
".",
"of",
"line",
"Returns",
"-------",
"self"
] | python | train | 20.642857 |
trevisanj/a99 | a99/search.py | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/search.py#L15-L29 | def index_nearest(array, value):
"""
Finds index of nearest value in array.
Args:
array: numpy array
value:
Returns:
int
http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array
"""
idx = (np.abs(array-value)).argmin()
return i... | [
"def",
"index_nearest",
"(",
"array",
",",
"value",
")",
":",
"idx",
"=",
"(",
"np",
".",
"abs",
"(",
"array",
"-",
"value",
")",
")",
".",
"argmin",
"(",
")",
"return",
"idx"
] | Finds index of nearest value in array.
Args:
array: numpy array
value:
Returns:
int
http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array | [
"Finds",
"index",
"of",
"nearest",
"value",
"in",
"array",
".",
"Args",
":",
"array",
":",
"numpy",
"array",
"value",
":",
"Returns",
":",
"int",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"2566412",
"/",
"find",
"-",
"neare... | python | train | 20.533333 |
google/python-gflags | gflags/flagvalues.py | https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags/flagvalues.py#L490-L511 | def _IsUnparsedFlagAccessAllowed(self, name):
"""Determine whether to allow unparsed flag access or not."""
if _UNPARSED_FLAG_ACCESS_ENV_NAME in os.environ:
# We've been told explicitly what to do.
allow_unparsed_flag_access = (
os.getenv(_UNPARSED_FLAG_ACCESS_ENV_NAME) == '1')
elif se... | [
"def",
"_IsUnparsedFlagAccessAllowed",
"(",
"self",
",",
"name",
")",
":",
"if",
"_UNPARSED_FLAG_ACCESS_ENV_NAME",
"in",
"os",
".",
"environ",
":",
"# We've been told explicitly what to do.",
"allow_unparsed_flag_access",
"=",
"(",
"os",
".",
"getenv",
"(",
"_UNPARSED_F... | Determine whether to allow unparsed flag access or not. | [
"Determine",
"whether",
"to",
"allow",
"unparsed",
"flag",
"access",
"or",
"not",
"."
] | python | train | 49.681818 |
dsoprea/NsqSpinner | nsq/connection.py | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L423-L443 | def __read_frame(self):
"""*Attempt* to read a frame. If we get an EAGAIN on the frame header,
it'll raise to our caller. If we get it *after* we already got the
header, wait-out the rest of the frame.
"""
if self.__frame_header_cache is None:
_logger.debug("Readin... | [
"def",
"__read_frame",
"(",
"self",
")",
":",
"if",
"self",
".",
"__frame_header_cache",
"is",
"None",
":",
"_logger",
".",
"debug",
"(",
"\"Reading frame header.\"",
")",
"(",
"length",
",",
"frame_type",
")",
"=",
"struct",
".",
"unpack",
"(",
"'!II'",
"... | *Attempt* to read a frame. If we get an EAGAIN on the frame header,
it'll raise to our caller. If we get it *after* we already got the
header, wait-out the rest of the frame. | [
"*",
"Attempt",
"*",
"to",
"read",
"a",
"frame",
".",
"If",
"we",
"get",
"an",
"EAGAIN",
"on",
"the",
"frame",
"header",
"it",
"ll",
"raise",
"to",
"our",
"caller",
".",
"If",
"we",
"get",
"it",
"*",
"after",
"*",
"we",
"already",
"got",
"the",
"... | python | train | 37.190476 |
JNRowe/upoints | upoints/gpx.py | https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/gpx.py#L245-L256 | def sunset(self, date=None, zenith=None):
"""Calculate sunset times for locations.
Args:
date (datetime.date): Calculate rise or set for given date
zenith (str): Calculate sunset events, or start of twilight times
Returns:
list of list of datetime.datetime: ... | [
"def",
"sunset",
"(",
"self",
",",
"date",
"=",
"None",
",",
"zenith",
"=",
"None",
")",
":",
"return",
"(",
"segment",
".",
"sunset",
"(",
"date",
",",
"zenith",
")",
"for",
"segment",
"in",
"self",
")"
] | Calculate sunset times for locations.
Args:
date (datetime.date): Calculate rise or set for given date
zenith (str): Calculate sunset events, or start of twilight times
Returns:
list of list of datetime.datetime: The time for the sunset for each
poin... | [
"Calculate",
"sunset",
"times",
"for",
"locations",
"."
] | python | train | 38.083333 |
bradmontgomery/django-redis-metrics | redis_metrics/templatetags/redis_metric_tags.py | https://github.com/bradmontgomery/django-redis-metrics/blob/2c92332920113d28c39234b949aa496b39a091d1/redis_metrics/templatetags/redis_metric_tags.py#L116-L159 | def metric_history(slug, granularity="daily", since=None, to=None,
with_data_table=False):
"""Template Tag to display a metric's history.
* ``slug`` -- the metric's unique slug
* ``granularity`` -- the granularity: daily, hourly, weekly, monthly, yearly
* ``since`` -- a datetime obje... | [
"def",
"metric_history",
"(",
"slug",
",",
"granularity",
"=",
"\"daily\"",
",",
"since",
"=",
"None",
",",
"to",
"=",
"None",
",",
"with_data_table",
"=",
"False",
")",
":",
"r",
"=",
"get_r",
"(",
")",
"try",
":",
"if",
"since",
"and",
"len",
"(",
... | Template Tag to display a metric's history.
* ``slug`` -- the metric's unique slug
* ``granularity`` -- the granularity: daily, hourly, weekly, monthly, yearly
* ``since`` -- a datetime object or a string string matching one of the
following patterns: "YYYY-mm-dd" for a date or "YYYY-mm-dd HH:MM:SS" ... | [
"Template",
"Tag",
"to",
"display",
"a",
"metric",
"s",
"history",
"."
] | python | train | 34.136364 |
apache/spark | python/pyspark/sql/dataframe.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/dataframe.py#L975-L990 | def crossJoin(self, other):
"""Returns the cartesian product with another :class:`DataFrame`.
:param other: Right side of the cartesian product.
>>> df.select("age", "name").collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
>>> df2.select("name", "height").collect(... | [
"def",
"crossJoin",
"(",
"self",
",",
"other",
")",
":",
"jdf",
"=",
"self",
".",
"_jdf",
".",
"crossJoin",
"(",
"other",
".",
"_jdf",
")",
"return",
"DataFrame",
"(",
"jdf",
",",
"self",
".",
"sql_ctx",
")"
] | Returns the cartesian product with another :class:`DataFrame`.
:param other: Right side of the cartesian product.
>>> df.select("age", "name").collect()
[Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
>>> df2.select("name", "height").collect()
[Row(name=u'Tom', height=80),... | [
"Returns",
"the",
"cartesian",
"product",
"with",
"another",
":",
"class",
":",
"DataFrame",
"."
] | python | train | 45.6875 |
twosigma/marbles | marbles/mixins/marbles/mixins/mixins.py | https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L884-L909 | def assertFileSizeAlmostEqual(
self, filename, size, places=None, msg=None, delta=None):
'''Fail if ``filename`` does not have the given ``size`` as
determined by their difference rounded to the given number of
decimal ``places`` (default 7) and comparing to zero, or if
their... | [
"def",
"assertFileSizeAlmostEqual",
"(",
"self",
",",
"filename",
",",
"size",
",",
"places",
"=",
"None",
",",
"msg",
"=",
"None",
",",
"delta",
"=",
"None",
")",
":",
"fsize",
"=",
"self",
".",
"_get_file_size",
"(",
"filename",
")",
"self",
".",
"as... | Fail if ``filename`` does not have the given ``size`` as
determined by their difference rounded to the given number of
decimal ``places`` (default 7) and comparing to zero, or if
their difference is greater than a given ``delta``.
Parameters
----------
filename : str, by... | [
"Fail",
"if",
"filename",
"does",
"not",
"have",
"the",
"given",
"size",
"as",
"determined",
"by",
"their",
"difference",
"rounded",
"to",
"the",
"given",
"number",
"of",
"decimal",
"places",
"(",
"default",
"7",
")",
"and",
"comparing",
"to",
"zero",
"or"... | python | train | 35.615385 |
saltstack/salt | salt/template.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/template.py#L35-L139 | def compile_template(template,
renderers,
default,
blacklist,
whitelist,
saltenv='base',
sls='',
input_data='',
**kwargs):
'''
Take the path to ... | [
"def",
"compile_template",
"(",
"template",
",",
"renderers",
",",
"default",
",",
"blacklist",
",",
"whitelist",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"input_data",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"# if any error occurs,... | Take the path to a template and return the high data structure
derived from the template.
Helpers:
:param mask_value:
Mask value for debugging purposes (prevent sensitive information etc)
example: "mask_value="pass*". All "passwd", "password", "pass" will
be masked (as text). | [
"Take",
"the",
"path",
"to",
"a",
"template",
"and",
"return",
"the",
"high",
"data",
"structure",
"derived",
"from",
"the",
"template",
"."
] | python | train | 38.114286 |
aio-libs/aioodbc | aioodbc/connection.py | https://github.com/aio-libs/aioodbc/blob/01245560828d4adce0d7d16930fa566102322a0a/aioodbc/connection.py#L203-L212 | def set_attr(self, attr_id, value):
"""Calls SQLSetConnectAttr with the given values.
:param attr_id: the attribute ID (integer) to set. These are ODBC or
driver constants.
:parm value: the connection attribute value to set. At this time
only integer values are supported... | [
"def",
"set_attr",
"(",
"self",
",",
"attr_id",
",",
"value",
")",
":",
"fut",
"=",
"self",
".",
"_execute",
"(",
"self",
".",
"_conn",
".",
"set_attr",
",",
"attr_id",
",",
"value",
")",
"return",
"fut"
] | Calls SQLSetConnectAttr with the given values.
:param attr_id: the attribute ID (integer) to set. These are ODBC or
driver constants.
:parm value: the connection attribute value to set. At this time
only integer values are supported. | [
"Calls",
"SQLSetConnectAttr",
"with",
"the",
"given",
"values",
"."
] | python | train | 40.8 |
micha030201/aionationstates | aionationstates/world_.py | https://github.com/micha030201/aionationstates/blob/dc86b86d994cbab830b69ab8023601c73e778b3a/aionationstates/world_.py#L222-L245 | def poll(self, id):
"""Poll with a given id.
Parameters
----------
id : int
Poll id.
Returns
-------
an :class:`ApiQuery` of :class:`Poll`
Raises
------
:class:`NotFound`
If a poll with the requested id doesn't ex... | [
"def",
"poll",
"(",
"self",
",",
"id",
")",
":",
"@",
"api_query",
"(",
"'poll'",
",",
"pollid",
"=",
"str",
"(",
"id",
")",
")",
"async",
"def",
"result",
"(",
"_",
",",
"root",
")",
":",
"elem",
"=",
"root",
".",
"find",
"(",
"'POLL'",
")",
... | Poll with a given id.
Parameters
----------
id : int
Poll id.
Returns
-------
an :class:`ApiQuery` of :class:`Poll`
Raises
------
:class:`NotFound`
If a poll with the requested id doesn't exist. | [
"Poll",
"with",
"a",
"given",
"id",
"."
] | python | train | 23.875 |
PythonCharmers/python-future | src/future/backports/http/cookiejar.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1367-L1462 | def _normalized_cookie_tuples(self, attrs_set):
"""Return list of tuples containing normalised cookie information.
attrs_set is the list of lists of key,value pairs extracted from
the Set-Cookie or Set-Cookie2 headers.
Tuples are name, value, standard, rest, where name and value are th... | [
"def",
"_normalized_cookie_tuples",
"(",
"self",
",",
"attrs_set",
")",
":",
"cookie_tuples",
"=",
"[",
"]",
"boolean_attrs",
"=",
"\"discard\"",
",",
"\"secure\"",
"value_attrs",
"=",
"(",
"\"version\"",
",",
"\"expires\"",
",",
"\"max-age\"",
",",
"\"domain\"",
... | Return list of tuples containing normalised cookie information.
attrs_set is the list of lists of key,value pairs extracted from
the Set-Cookie or Set-Cookie2 headers.
Tuples are name, value, standard, rest, where name and value are the
cookie name and value, standard is a dictionary c... | [
"Return",
"list",
"of",
"tuples",
"containing",
"normalised",
"cookie",
"information",
"."
] | python | train | 41.458333 |
apple/turicreate | src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py#L52-L62 | def reduce(self, body):
'''
remove nodes from a list
'''
i = 0
while i < len(body):
stmnt = body[i]
if self.visit(stmnt):
body.pop(i)
else:
i += 1 | [
"def",
"reduce",
"(",
"self",
",",
"body",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"body",
")",
":",
"stmnt",
"=",
"body",
"[",
"i",
"]",
"if",
"self",
".",
"visit",
"(",
"stmnt",
")",
":",
"body",
".",
"pop",
"(",
"i",
")",... | remove nodes from a list | [
"remove",
"nodes",
"from",
"a",
"list"
] | python | train | 22.181818 |
bradleyfay/py-Goldsberry | goldsberry/apiconvertor.py | https://github.com/bradleyfay/py-Goldsberry/blob/828179f8e4aad910d7a8c58faa12d3ae2c354503/goldsberry/apiconvertor.py#L38-L52 | def season_id(x):
"""takes in 4-digit years and returns API formatted seasonID
Input Values: YYYY
Used in:
"""
if len(str(x)) == 4:
try:
return "".join(["2", str(x)])
except ValueError:
raise ValueError("Enter the four digit year for the first half of the ... | [
"def",
"season_id",
"(",
"x",
")",
":",
"if",
"len",
"(",
"str",
"(",
"x",
")",
")",
"==",
"4",
":",
"try",
":",
"return",
"\"\"",
".",
"join",
"(",
"[",
"\"2\"",
",",
"str",
"(",
"x",
")",
"]",
")",
"except",
"ValueError",
":",
"raise",
"Val... | takes in 4-digit years and returns API formatted seasonID
Input Values: YYYY
Used in: | [
"takes",
"in",
"4",
"-",
"digit",
"years",
"and",
"returns",
"API",
"formatted",
"seasonID"
] | python | train | 28.466667 |
KE-works/pykechain | pykechain/client.py | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/client.py#L312-L360 | def scopes(self, name=None, pk=None, status=ScopeStatus.ACTIVE, **kwargs):
# type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Scope]
"""Return all scopes visible / accessible for the logged in user.
If additional `keyword=value` arguments are provided, these are added to the r... | [
"def",
"scopes",
"(",
"self",
",",
"name",
"=",
"None",
",",
"pk",
"=",
"None",
",",
"status",
"=",
"ScopeStatus",
".",
"ACTIVE",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Scope]",
"request_params",
"=... | Return all scopes visible / accessible for the logged in user.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:param name: if provided, filter the search for... | [
"Return",
"all",
"scopes",
"visible",
"/",
"accessible",
"for",
"the",
"logged",
"in",
"user",
"."
] | python | train | 38.265306 |
nfcpy/nfcpy | src/nfc/tag/tt1.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt1.py#L387-L392 | def read_all(self):
"""Returns the 2 byte Header ROM and all 120 byte static memory.
"""
log.debug("read all static memory")
cmd = "\x00\x00\x00" + self.uid
return self.transceive(cmd) | [
"def",
"read_all",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"read all static memory\"",
")",
"cmd",
"=",
"\"\\x00\\x00\\x00\"",
"+",
"self",
".",
"uid",
"return",
"self",
".",
"transceive",
"(",
"cmd",
")"
] | Returns the 2 byte Header ROM and all 120 byte static memory. | [
"Returns",
"the",
"2",
"byte",
"Header",
"ROM",
"and",
"all",
"120",
"byte",
"static",
"memory",
"."
] | python | train | 36.5 |
elkiwy/paynter | paynter/paynter.py | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L127-L147 | def drawPoint(self, x, y, silent=True):
"""
Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: Point X coordinate.
:param y1: Point Y coordinate.
:rtype: Nothing.
"""
start = tim... | [
"def",
"drawPoint",
"(",
"self",
",",
"x",
",",
"y",
",",
"silent",
"=",
"True",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"#Downsample the coordinates",
"x",
"=",
"int",
"(",
"x",
"/",
"config",
".",
"DOWNSAMPLING",
")",
"y",
"=",
"in... | Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: Point X coordinate.
:param y1: Point Y coordinate.
:rtype: Nothing. | [
"Draws",
"a",
"point",
"on",
"the",
"current",
":",
"py",
":",
"class",
":",
"Layer",
"with",
"the",
"current",
":",
"py",
":",
"class",
":",
"Brush",
".",
"Coordinates",
"are",
"relative",
"to",
"the",
"original",
"layer",
"size",
"WITHOUT",
"downsampli... | python | train | 42 |
zsethna/OLGA | olga/generation_probability.py | https://github.com/zsethna/OLGA/blob/e825c333f0f9a4eb02132e0bcf86f0dca9123114/olga/generation_probability.py#L1679-L1746 | def compute_Pi_V_given_J(self, CDR3_seq, V_usage_mask, J_usage_mask):
"""Compute Pi_V conditioned on J.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}.
For clarity in parsing the a... | [
"def",
"compute_Pi_V_given_J",
"(",
"self",
",",
"CDR3_seq",
",",
"V_usage_mask",
",",
"J_usage_mask",
")",
":",
"#Note, the cutV_genomic_CDR3_segs INCLUDE the palindromic insertions and thus are max_palindrome nts longer than the template.",
"#furthermore, the genomic sequence should be p... | Compute Pi_V conditioned on J.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V, J)*P(delV|V). This corresponds to V(J)_{x_1}.
For clarity in parsing the algorithm implementation, we include which
instance attributes are used i... | [
"Compute",
"Pi_V",
"conditioned",
"on",
"J",
".",
"This",
"function",
"returns",
"the",
"Pi",
"array",
"from",
"the",
"model",
"factors",
"of",
"the",
"V",
"genomic",
"contributions",
"P",
"(",
"V",
"J",
")",
"*",
"P",
"(",
"delV|V",
")",
".",
"This",
... | python | train | 52.573529 |
twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/this_month.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/this_month.py#L185-L194 | def get_instance(self, payload):
"""
Build an instance of ThisMonthInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance
:rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMon... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"ThisMonthInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | Build an instance of ThisMonthInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance
:rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance | [
"Build",
"an",
"instance",
"of",
"ThisMonthInstance"
] | python | train | 43.5 |
data-8/datascience | datascience/tables.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L572-L581 | def copy(self, *, shallow=False):
"""Return a copy of a table."""
table = type(self)()
for label in self.labels:
if shallow:
column = self[label]
else:
column = np.copy(self[label])
self._add_column_and_format(table, label, colu... | [
"def",
"copy",
"(",
"self",
",",
"*",
",",
"shallow",
"=",
"False",
")",
":",
"table",
"=",
"type",
"(",
"self",
")",
"(",
")",
"for",
"label",
"in",
"self",
".",
"labels",
":",
"if",
"shallow",
":",
"column",
"=",
"self",
"[",
"label",
"]",
"e... | Return a copy of a table. | [
"Return",
"a",
"copy",
"of",
"a",
"table",
"."
] | python | train | 33.5 |
apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/vggish_input.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/vggish_input.py#L24-L71 | def waveform_to_examples(data, sample_rate):
"""Converts audio waveform into an array of examples for VGGish.
Args:
data: np.array of either one dimension (mono) or two dimensions
(multi-channel, with the outer dimension representing channels).
Each sample is generally expected to lie in the range ... | [
"def",
"waveform_to_examples",
"(",
"data",
",",
"sample_rate",
")",
":",
"import",
"resampy",
"# Convert to mono.",
"if",
"len",
"(",
"data",
".",
"shape",
")",
">",
"1",
":",
"data",
"=",
"np",
".",
"mean",
"(",
"data",
",",
"axis",
"=",
"1",
")",
... | Converts audio waveform into an array of examples for VGGish.
Args:
data: np.array of either one dimension (mono) or two dimensions
(multi-channel, with the outer dimension representing channels).
Each sample is generally expected to lie in the range [-1.0, +1.0],
although this is not required.... | [
"Converts",
"audio",
"waveform",
"into",
"an",
"array",
"of",
"examples",
"for",
"VGGish",
"."
] | python | train | 39.395833 |
20tab/twentytab-tree | tree/menu.py | https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L68-L74 | def as_ul(self, current_linkable=False, class_current="active_link",
before_1="", after_1="", before_all="", after_all=""):
"""
It returns menu as ul
"""
return self.__do_menu("as_ul", current_linkable, class_current,
before_1=before_1, after_1... | [
"def",
"as_ul",
"(",
"self",
",",
"current_linkable",
"=",
"False",
",",
"class_current",
"=",
"\"active_link\"",
",",
"before_1",
"=",
"\"\"",
",",
"after_1",
"=",
"\"\"",
",",
"before_all",
"=",
"\"\"",
",",
"after_all",
"=",
"\"\"",
")",
":",
"return",
... | It returns menu as ul | [
"It",
"returns",
"menu",
"as",
"ul"
] | python | train | 52.428571 |
Titan-C/slaveparticles | slaveparticles/spins.py | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L127-L143 | def set_filling(self, populations):
"""Sets the orbital enenergies for on the reference of the free case.
By setting the desired local populations on every orbital.
Then generate the necesary operators to respect such configuraion"""
populations = np.asarray(populations)
#
# s... | [
"def",
"set_filling",
"(",
"self",
",",
"populations",
")",
":",
"populations",
"=",
"np",
".",
"asarray",
"(",
"populations",
")",
"#",
"# self.param['orbital_e'] -= bethe_findfill_zeroT( \\",
"# self.param['avg_particles'],",
"# ... | Sets the orbital enenergies for on the reference of the free case.
By setting the desired local populations on every orbital.
Then generate the necesary operators to respect such configuraion | [
"Sets",
"the",
"orbital",
"enenergies",
"for",
"on",
"the",
"reference",
"of",
"the",
"free",
"case",
".",
"By",
"setting",
"the",
"desired",
"local",
"populations",
"on",
"every",
"orbital",
".",
"Then",
"generate",
"the",
"necesary",
"operators",
"to",
"re... | python | train | 53.823529 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L771-L777 | def start_date(self) -> Optional[datetime.date]:
"""
Returns the start date of the set of intervals, or ``None`` if empty.
"""
if not self.intervals:
return None
return self.start_datetime().date() | [
"def",
"start_date",
"(",
"self",
")",
"->",
"Optional",
"[",
"datetime",
".",
"date",
"]",
":",
"if",
"not",
"self",
".",
"intervals",
":",
"return",
"None",
"return",
"self",
".",
"start_datetime",
"(",
")",
".",
"date",
"(",
")"
] | Returns the start date of the set of intervals, or ``None`` if empty. | [
"Returns",
"the",
"start",
"date",
"of",
"the",
"set",
"of",
"intervals",
"or",
"None",
"if",
"empty",
"."
] | python | train | 34.714286 |
llazzaro/analyzerstrategies | analyzerstrategies/sma_portfolio_strategy.py | https://github.com/llazzaro/analyzerstrategies/blob/3c647802f582bf2f06c6793f282bee0d26514cd6/analyzerstrategies/sma_portfolio_strategy.py#L131-L150 | def __placeSellShortOrder(self, tick):
''' place short sell order'''
share=math.floor(self.__strategy.getAccountCopy().getCash() / float(tick.close))
sellShortOrder=Order(accountId=self.__strategy.accountId,
action=Action.SELL_SHORT,
... | [
"def",
"__placeSellShortOrder",
"(",
"self",
",",
"tick",
")",
":",
"share",
"=",
"math",
".",
"floor",
"(",
"self",
".",
"__strategy",
".",
"getAccountCopy",
"(",
")",
".",
"getCash",
"(",
")",
"/",
"float",
"(",
"tick",
".",
"close",
")",
")",
"sel... | place short sell order | [
"place",
"short",
"sell",
"order"
] | python | train | 45.5 |
pydata/xarray | xarray/core/groupby.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/groupby.py#L482-L488 | def _iter_grouped_shortcut(self):
"""Fast version of `_iter_grouped` that yields Variables without
metadata
"""
var = self._obj.variable
for indices in self._group_indices:
yield var[{self._group_dim: indices}] | [
"def",
"_iter_grouped_shortcut",
"(",
"self",
")",
":",
"var",
"=",
"self",
".",
"_obj",
".",
"variable",
"for",
"indices",
"in",
"self",
".",
"_group_indices",
":",
"yield",
"var",
"[",
"{",
"self",
".",
"_group_dim",
":",
"indices",
"}",
"]"
] | Fast version of `_iter_grouped` that yields Variables without
metadata | [
"Fast",
"version",
"of",
"_iter_grouped",
"that",
"yields",
"Variables",
"without",
"metadata"
] | python | train | 36.571429 |
KelSolaar/Foundations | foundations/io.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/io.py#L122-L132 | def content(self, value):
"""
Setter for **self.__content** attribute.
:param value: Attribute value.
:type value: list
"""
if value is not None:
assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format("content", value)
self._... | [
"def",
"content",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"list",
",",
"\"'{0}' attribute: '{1}' type is not 'list'!\"",
".",
"format",
"(",
"\"content\"",
",",
"value",
")",
... | Setter for **self.__content** attribute.
:param value: Attribute value.
:type value: list | [
"Setter",
"for",
"**",
"self",
".",
"__content",
"**",
"attribute",
"."
] | python | train | 29.636364 |
project-rig/rig | rig/place_and_route/route/ner.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/route/ner.py#L413-L433 | def route_has_dead_links(root, machine):
"""Quickly determine if a route uses any dead links.
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
mach... | [
"def",
"route_has_dead_links",
"(",
"root",
",",
"machine",
")",
":",
"for",
"direction",
",",
"(",
"x",
",",
"y",
")",
",",
"routes",
"in",
"root",
".",
"traverse",
"(",
")",
":",
"for",
"route",
"in",
"routes",
":",
"if",
"(",
"x",
",",
"y",
",... | Quickly determine if a route uses any dead links.
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing but RoutingTrees
(i.e. no vertices and links).
machine : :py:class:`~rig.place_and_route.Machine`
... | [
"Quickly",
"determine",
"if",
"a",
"route",
"uses",
"any",
"dead",
"links",
"."
] | python | train | 32.380952 |
radjkarl/appBase | appbase/Session.py | https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L483-L503 | def _save(self, stateName, path):
"""save into 'stateName' to pyz-path"""
print('saving...')
state = {'session': dict(self.opts),
'dialogs': self.dialogs.saveState()}
self.sigSave.emit(state)
self.saveThread.prepare(stateName, path, self.tmp_dir_session... | [
"def",
"_save",
"(",
"self",
",",
"stateName",
",",
"path",
")",
":",
"print",
"(",
"'saving...'",
")",
"state",
"=",
"{",
"'session'",
":",
"dict",
"(",
"self",
".",
"opts",
")",
",",
"'dialogs'",
":",
"self",
".",
"dialogs",
".",
"saveState",
"(",
... | save into 'stateName' to pyz-path | [
"save",
"into",
"stateName",
"to",
"pyz",
"-",
"path"
] | python | train | 31.047619 |
googlefonts/glyphsLib | Lib/glyphsLib/glyphdata.py | https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/glyphdata.py#L282-L384 | def _construct_production_name(glyph_name, data=None):
"""Return the production name for a glyph name from the GlyphData.xml
database according to the AGL specification.
This should be run only if there is no official entry with a production
name in it.
Handles single glyphs (e.g. "brevecomb") and... | [
"def",
"_construct_production_name",
"(",
"glyph_name",
",",
"data",
"=",
"None",
")",
":",
"# At this point, we have already checked the data for the full glyph name, so",
"# directly go to the base name here (e.g. when looking at \"fi.alt\").",
"base_name",
",",
"dot",
",",
"suffix... | Return the production name for a glyph name from the GlyphData.xml
database according to the AGL specification.
This should be run only if there is no official entry with a production
name in it.
Handles single glyphs (e.g. "brevecomb") and ligatures (e.g.
"brevecomb_acutecomb"). Returns None when... | [
"Return",
"the",
"production",
"name",
"for",
"a",
"glyph",
"name",
"from",
"the",
"GlyphData",
".",
"xml",
"database",
"according",
"to",
"the",
"AGL",
"specification",
"."
] | python | train | 42.873786 |
pandas-dev/pandas | pandas/core/missing.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L314-L355 | def _from_derivatives(xi, yi, x, order=None, der=0, extrapolate=False):
"""
Convenience function for interpolate.BPoly.from_derivatives.
Construct a piecewise polynomial in the Bernstein basis, compatible
with the specified values and derivatives at breakpoints.
Parameters
----------
xi : ... | [
"def",
"_from_derivatives",
"(",
"xi",
",",
"yi",
",",
"x",
",",
"order",
"=",
"None",
",",
"der",
"=",
"0",
",",
"extrapolate",
"=",
"False",
")",
":",
"from",
"scipy",
"import",
"interpolate",
"# return the method for compat with scipy version & backwards compat... | Convenience function for interpolate.BPoly.from_derivatives.
Construct a piecewise polynomial in the Bernstein basis, compatible
with the specified values and derivatives at breakpoints.
Parameters
----------
xi : array_like
sorted 1D array of x-coordinates
yi : array_like or list of a... | [
"Convenience",
"function",
"for",
"interpolate",
".",
"BPoly",
".",
"from_derivatives",
"."
] | python | train | 35.428571 |
holtjma/msbwt | MUS/MultiStringBWT.py | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L169-L209 | def recoverString(self, strIndex, withIndex=False):
'''
This will return the string that starts at the given index
@param strIndex - the index of the string we want to recover
@return - string that we found starting at the specified '$' index
'''
retNums = []
indi... | [
"def",
"recoverString",
"(",
"self",
",",
"strIndex",
",",
"withIndex",
"=",
"False",
")",
":",
"retNums",
"=",
"[",
"]",
"indices",
"=",
"[",
"]",
"#figure out the first hop backwards",
"currIndex",
"=",
"strIndex",
"prevChar",
"=",
"self",
".",
"getCharAtInd... | This will return the string that starts at the given index
@param strIndex - the index of the string we want to recover
@return - string that we found starting at the specified '$' index | [
"This",
"will",
"return",
"the",
"string",
"that",
"starts",
"at",
"the",
"given",
"index"
] | python | train | 34.829268 |
edwards-lab/libGWAS | libgwas/impute_parser.py | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/impute_parser.py#L178-L200 | def load_genotypes(self):
"""Prepares the files for genotype parsing.
:return: None
"""
if self.file_index < len(self.archives):
self.current_file = self.archives[self.file_index]
info_filename = self.current_file.replace(Parser.gen_ext, Parser.info_ext)
... | [
"def",
"load_genotypes",
"(",
"self",
")",
":",
"if",
"self",
".",
"file_index",
"<",
"len",
"(",
"self",
".",
"archives",
")",
":",
"self",
".",
"current_file",
"=",
"self",
".",
"archives",
"[",
"self",
".",
"file_index",
"]",
"info_filename",
"=",
"... | Prepares the files for genotype parsing.
:return: None | [
"Prepares",
"the",
"files",
"for",
"genotype",
"parsing",
"."
] | python | train | 36.73913 |
spyder-ide/spyder | spyder/plugins/editor/widgets/editor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/editor.py#L737-L787 | def setup_editorstack(self, parent, layout):
"""Setup editorstack's layout"""
layout.setSpacing(1)
self.fname_label = QLabel()
self.fname_label.setStyleSheet(
"QLabel {margin: 0px; padding: 3px;}")
layout.addWidget(self.fname_label)
menu_btn = creat... | [
"def",
"setup_editorstack",
"(",
"self",
",",
"parent",
",",
"layout",
")",
":",
"layout",
".",
"setSpacing",
"(",
"1",
")",
"self",
".",
"fname_label",
"=",
"QLabel",
"(",
")",
"self",
".",
"fname_label",
".",
"setStyleSheet",
"(",
"\"QLabel {margin: 0px; p... | Setup editorstack's layout | [
"Setup",
"editorstack",
"s",
"layout"
] | python | train | 42.215686 |
twisted/txaws | txaws/client/discover/entry_point.py | https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/client/discover/entry_point.py#L63-L114 | def parse_options(arguments):
"""Parse command line arguments.
The parsing logic is fairly simple. It can only parse long-style
parameters of the form::
--key value
Several parameters can be defined in the environment and will be used
unless explicitly overridden with command-line argument... | [
"def",
"parse_options",
"(",
"arguments",
")",
":",
"arguments",
"=",
"arguments",
"[",
"1",
":",
"]",
"options",
"=",
"{",
"}",
"while",
"arguments",
":",
"key",
"=",
"arguments",
".",
"pop",
"(",
"0",
")",
"if",
"key",
"in",
"(",
"\"-h\"",
",",
"... | Parse command line arguments.
The parsing logic is fairly simple. It can only parse long-style
parameters of the form::
--key value
Several parameters can be defined in the environment and will be used
unless explicitly overridden with command-line arguments. The access key,
secret and en... | [
"Parse",
"command",
"line",
"arguments",
"."
] | python | train | 40 |
miguelgrinberg/Flask-Migrate | flask_migrate/templates/flask-multidb/env.py | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/templates/flask-multidb/env.py#L55-L91 | def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | [
"def",
"run_migrations_offline",
"(",
")",
":",
"# for the --sql use case, run migrations for each URL into",
"# individual files.",
"engines",
"=",
"{",
"''",
":",
"{",
"'url'",
":",
"context",
".",
"config",
".",
"get_main_option",
"(",
"'sqlalchemy.url'",
")",
"}",
... | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | [
"Run",
"migrations",
"in",
"offline",
"mode",
"."
] | python | train | 32.72973 |
palantir/conjure-python-client | conjure_python_client/_serde/decoder.py | https://github.com/palantir/conjure-python-client/blob/e6814a80bae3ec01fa147d5fd445538a677b1349/conjure_python_client/_serde/decoder.py#L166-L181 | def decode_list(cls, obj, element_type):
# type: (List[Any], ConjureTypeType) -> List[Any]
"""Decodes json into a list, handling conversion of the elements.
Args:
obj: the json object to decode
element_type: a class object which is the conjure type of
the... | [
"def",
"decode_list",
"(",
"cls",
",",
"obj",
",",
"element_type",
")",
":",
"# type: (List[Any], ConjureTypeType) -> List[Any]",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"raise",
"Exception",
"(",
"\"expected a python list\"",
")",
"return",
... | Decodes json into a list, handling conversion of the elements.
Args:
obj: the json object to decode
element_type: a class object which is the conjure type of
the elements in this list.
Returns:
A python list where the elements are instances of type
... | [
"Decodes",
"json",
"into",
"a",
"list",
"handling",
"conversion",
"of",
"the",
"elements",
"."
] | python | train | 38.6875 |
eecs-autograder/autograder-sandbox | autograder_sandbox/autograder_sandbox.py | https://github.com/eecs-autograder/autograder-sandbox/blob/230e806e3740e2aaf5f5568dd6a265558f165c63/autograder_sandbox/autograder_sandbox.py#L347-L356 | def add_and_rename_file(self, filename: str, new_filename: str) -> None:
"""
Copies the specified file into the working directory of this
sandbox and renames it to new_filename.
"""
dest = os.path.join(
self.name + ':' + SANDBOX_WORKING_DIR_NAME,
new_filen... | [
"def",
"add_and_rename_file",
"(",
"self",
",",
"filename",
":",
"str",
",",
"new_filename",
":",
"str",
")",
"->",
"None",
":",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"name",
"+",
"':'",
"+",
"SANDBOX_WORKING_DIR_NAME",
",",
"n... | Copies the specified file into the working directory of this
sandbox and renames it to new_filename. | [
"Copies",
"the",
"specified",
"file",
"into",
"the",
"working",
"directory",
"of",
"this",
"sandbox",
"and",
"renames",
"it",
"to",
"new_filename",
"."
] | python | test | 42.1 |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L513-L522 | def get_suppliers_per_page(self, per_page=1000, page=1, params=None):
"""
Get suppliers per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
... | [
"def",
"get_suppliers_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"SUPPLIERS",
",",
"per_page",
"=",
"per_page",
"... | Get suppliers per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"suppliers",
"per",
"page"
] | python | train | 41 |
wonambi-python/wonambi | wonambi/detect/slowwave.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/slowwave.py#L124-L187 | def detect_Massimini2004(dat_orig, s_freq, time, opts):
"""Slow wave detection based on Massimini et al., 2004.
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
time : ndarray (dtype='float')
... | [
"def",
"detect_Massimini2004",
"(",
"dat_orig",
",",
"s_freq",
",",
"time",
",",
"opts",
")",
":",
"if",
"opts",
".",
"invert",
":",
"dat_orig",
"=",
"-",
"dat_orig",
"dat_det",
"=",
"transform_signal",
"(",
"dat_orig",
",",
"s_freq",
",",
"'double_butter'",... | Slow wave detection based on Massimini et al., 2004.
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
time : ndarray (dtype='float')
vector with the time points for each sample
opts : instance... | [
"Slow",
"wave",
"detection",
"based",
"on",
"Massimini",
"et",
"al",
".",
"2004",
"."
] | python | train | 32.09375 |
assamite/creamas | creamas/nx.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/nx.py#L119-L143 | def _edges2conns(G, edge_data=False):
"""Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.... | [
"def",
"_edges2conns",
"(",
"G",
",",
"edge_data",
"=",
"False",
")",
":",
"cm",
"=",
"{",
"}",
"for",
"n",
"in",
"G",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"if",
"edge_data",
":",
"cm",
"[",
"n",
"[",
"1",
"]",
"[",
"'addr'",
"]"... | Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.
:returns:
A dictionary where ke... | [
"Create",
"a",
"mapping",
"from",
"graph",
"edges",
"to",
"agent",
"connections",
"to",
"be",
"created",
"."
] | python | train | 33.36 |
materialsvirtuallab/monty | monty/operator.py | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/operator.py#L9-L36 | def operator_from_str(op):
"""
Return the operator associated to the given string `op`.
raises:
`KeyError` if invalid string.
>>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2
"""
d = {"==": operator.eq,
"!=": operator.ne,
">": operator.gt,... | [
"def",
"operator_from_str",
"(",
"op",
")",
":",
"d",
"=",
"{",
"\"==\"",
":",
"operator",
".",
"eq",
",",
"\"!=\"",
":",
"operator",
".",
"ne",
",",
"\">\"",
":",
"operator",
".",
"gt",
",",
"\">=\"",
":",
"operator",
".",
"ge",
",",
"\"<\"",
":",... | Return the operator associated to the given string `op`.
raises:
`KeyError` if invalid string.
>>> assert operator_from_str("==")(1, 1) and operator_from_str("+")(1,1) == 2 | [
"Return",
"the",
"operator",
"associated",
"to",
"the",
"given",
"string",
"op",
"."
] | python | train | 22.464286 |
erans/fabric-gce-tools | fabric_gce_tools/__init__.py | https://github.com/erans/fabric-gce-tools/blob/0c9af7a683db47e203d4e487fa8610da6459ca83/fabric_gce_tools/__init__.py#L205-L228 | def update_roles_gce(use_cache=True, cache_expiration=86400, cache_path="~/.gcetools/instances", group_name=None, region=None, zone=None):
"""
Dynamically update fabric's roles by using assigning the tags associated with
each machine in Google Compute Engine.
use_cache - will store a local cache in ~/.... | [
"def",
"update_roles_gce",
"(",
"use_cache",
"=",
"True",
",",
"cache_expiration",
"=",
"86400",
",",
"cache_path",
"=",
"\"~/.gcetools/instances\"",
",",
"group_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"zone",
"=",
"None",
")",
":",
"data",
"=",... | Dynamically update fabric's roles by using assigning the tags associated with
each machine in Google Compute Engine.
use_cache - will store a local cache in ~/.gcetools/
cache_expiration - cache expiration in seconds (default: 1 day)
cache_path - the path to store instances data (default: ~/.gcetools/i... | [
"Dynamically",
"update",
"fabric",
"s",
"roles",
"by",
"using",
"assigning",
"the",
"tags",
"associated",
"with",
"each",
"machine",
"in",
"Google",
"Compute",
"Engine",
"."
] | python | train | 51.208333 |
iotile/coretools | iotilecore/iotile/core/utilities/kvstore_json.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/kvstore_json.py#L48-L58 | def _load_file(self):
"""Load all entries from json backing file
"""
if not os.path.exists(self.file):
return {}
with open(self.file, "r") as infile:
data = json.load(infile)
return data | [
"def",
"_load_file",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"file",
")",
":",
"return",
"{",
"}",
"with",
"open",
"(",
"self",
".",
"file",
",",
"\"r\"",
")",
"as",
"infile",
":",
"data",
"=",
"j... | Load all entries from json backing file | [
"Load",
"all",
"entries",
"from",
"json",
"backing",
"file"
] | python | train | 22.090909 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L825-L847 | def write_index_and_rst_files(self, overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes both the individual RST files and the index.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't
... | [
"def",
"write_index_and_rst_files",
"(",
"self",
",",
"overwrite",
":",
"bool",
"=",
"False",
",",
"mock",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"for",
"f",
"in",
"self",
".",
"files_to_index",
":",
"if",
"isinstance",
"(",
"f",
",",
"File... | Writes both the individual RST files and the index.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't | [
"Writes",
"both",
"the",
"individual",
"RST",
"files",
"and",
"the",
"index",
"."
] | python | train | 41.913043 |
williamFalcon/test-tube | examples/pytorch_hpc_example.py | https://github.com/williamFalcon/test-tube/blob/db5a47067a854f76d89f8066582023c1e184bccb/examples/pytorch_hpc_example.py#L8-L30 | def train(hparams, *args):
"""Train your awesome model.
:param hparams: The arguments to run the model with.
"""
# Initialize experiments and track all the hyperparameters
exp = Experiment(
name=hparams.test_tube_exp_name,
# Location to save the metrics.
save_dir=hparams.log... | [
"def",
"train",
"(",
"hparams",
",",
"*",
"args",
")",
":",
"# Initialize experiments and track all the hyperparameters",
"exp",
"=",
"Experiment",
"(",
"name",
"=",
"hparams",
".",
"test_tube_exp_name",
",",
"# Location to save the metrics.",
"save_dir",
"=",
"hparams"... | Train your awesome model.
:param hparams: The arguments to run the model with. | [
"Train",
"your",
"awesome",
"model",
"."
] | python | test | 26.347826 |
chimera0/accel-brain-code | Reinforcement-Learning/pyqlearning/deep_q_learning.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/deep_q_learning.py#L72-L123 | def learn(self, state_arr, limit=1000):
'''
Learning and searching the optimal solution.
Args:
state_arr: `np.ndarray` of initial state.
limit: The maximum number of iterative updates based on value iteration algorithms.
'''
while se... | [
"def",
"learn",
"(",
"self",
",",
"state_arr",
",",
"limit",
"=",
"1000",
")",
":",
"while",
"self",
".",
"t",
"<=",
"limit",
":",
"# Draw samples of next possible actions from any distribution.",
"next_action_arr",
"=",
"self",
".",
"extract_possible_actions",
"(",... | Learning and searching the optimal solution.
Args:
state_arr: `np.ndarray` of initial state.
limit: The maximum number of iterative updates based on value iteration algorithms. | [
"Learning",
"and",
"searching",
"the",
"optimal",
"solution",
".",
"Args",
":",
"state_arr",
":",
"np",
".",
"ndarray",
"of",
"initial",
"state",
".",
"limit",
":",
"The",
"maximum",
"number",
"of",
"iterative",
"updates",
"based",
"on",
"value",
"iteration"... | python | train | 44.557692 |
SheffieldML/GPyOpt | GPyOpt/util/general.py | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L86-L96 | def get_moments(model,x):
'''
Moments (mean and sdev.) of a GP model at x
'''
input_dim = model.X.shape[1]
x = reshape(x,input_dim)
fmin = min(model.predict(model.X)[0])
m, v = model.predict(x)
s = np.sqrt(np.clip(v, 0, np.inf))
return (m,s, fmin) | [
"def",
"get_moments",
"(",
"model",
",",
"x",
")",
":",
"input_dim",
"=",
"model",
".",
"X",
".",
"shape",
"[",
"1",
"]",
"x",
"=",
"reshape",
"(",
"x",
",",
"input_dim",
")",
"fmin",
"=",
"min",
"(",
"model",
".",
"predict",
"(",
"model",
".",
... | Moments (mean and sdev.) of a GP model at x | [
"Moments",
"(",
"mean",
"and",
"sdev",
".",
")",
"of",
"a",
"GP",
"model",
"at",
"x"
] | python | train | 24.909091 |
slarse/pdfebc-core | pdfebc_core/compress.py | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/compress.py#L87-L105 | def compress_multiple_pdfs(source_directory, output_directory, ghostscript_binary):
"""Compress all PDF files in the current directory and place the output in the
given output directory. This is a generator function that first yields the amount
of files to be compressed, and then yields the output path of e... | [
"def",
"compress_multiple_pdfs",
"(",
"source_directory",
",",
"output_directory",
",",
"ghostscript_binary",
")",
":",
"source_paths",
"=",
"_get_pdf_filenames_at",
"(",
"source_directory",
")",
"yield",
"len",
"(",
"source_paths",
")",
"for",
"source_path",
"in",
"s... | Compress all PDF files in the current directory and place the output in the
given output directory. This is a generator function that first yields the amount
of files to be compressed, and then yields the output path of each file.
Args:
source_directory (str): Filepath to the source directory.
... | [
"Compress",
"all",
"PDF",
"files",
"in",
"the",
"current",
"directory",
"and",
"place",
"the",
"output",
"in",
"the",
"given",
"output",
"directory",
".",
"This",
"is",
"a",
"generator",
"function",
"that",
"first",
"yields",
"the",
"amount",
"of",
"files",
... | python | train | 45.526316 |
google/grr | grr/server/grr_response_server/hunts/implementation.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/hunts/implementation.py#L892-L897 | def _Complete(self):
"""Marks the hunt as completed."""
self._RemoveForemanRule()
if "w" in self.hunt_obj.mode:
self.hunt_obj.Set(self.hunt_obj.Schema.STATE("COMPLETED"))
self.hunt_obj.Flush() | [
"def",
"_Complete",
"(",
"self",
")",
":",
"self",
".",
"_RemoveForemanRule",
"(",
")",
"if",
"\"w\"",
"in",
"self",
".",
"hunt_obj",
".",
"mode",
":",
"self",
".",
"hunt_obj",
".",
"Set",
"(",
"self",
".",
"hunt_obj",
".",
"Schema",
".",
"STATE",
"(... | Marks the hunt as completed. | [
"Marks",
"the",
"hunt",
"as",
"completed",
"."
] | python | train | 35.166667 |
larryng/narwal | narwal/reddit.py | https://github.com/larryng/narwal/blob/58c409a475c8ed865579a61d7010162ed8cef597/narwal/reddit.py#L645-L658 | def compose(self, to, subject, text):
"""Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/compose/``
:param to: username or :class`things.A... | [
"def",
"compose",
"(",
"self",
",",
"to",
",",
"subject",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"to",
",",
"Account",
")",
":",
"to",
"=",
"to",
".",
"name",
"data",
"=",
"dict",
"(",
"to",
"=",
"to",
",",
"subject",
"=",
"subject",
"... | Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/compose/``
:param to: username or :class`things.Account` of user to send to
:param subject... | [
"Login",
"required",
".",
"Sends",
"POST",
"to",
"send",
"a",
"message",
"to",
"a",
"user",
".",
"Returns",
"True",
"or",
"raises",
":",
"class",
":",
"exceptions",
".",
"UnexpectedResponse",
"if",
"non",
"-",
"truthy",
"value",
"in",
"response",
".",
"U... | python | train | 44.714286 |
lowandrew/OLCTools | databasesetup/database_setup.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/databasesetup/database_setup.py#L136-L144 | def mob_suite_targets(self, database_name='mob_suite'):
"""
Download MOB-suite databases
:param database_name: name of current database
"""
logging.info('Download MOB-suite databases')
# NOTE: This requires mob_suite >=1.4.9.1. Versions before that don't have the -d optio... | [
"def",
"mob_suite_targets",
"(",
"self",
",",
"database_name",
"=",
"'mob_suite'",
")",
":",
"logging",
".",
"info",
"(",
"'Download MOB-suite databases'",
")",
"# NOTE: This requires mob_suite >=1.4.9.1. Versions before that don't have the -d option.",
"cmd",
"=",
"'mob_init -... | Download MOB-suite databases
:param database_name: name of current database | [
"Download",
"MOB",
"-",
"suite",
"databases",
":",
"param",
"database_name",
":",
"name",
"of",
"current",
"database"
] | python | train | 48.777778 |
spacetelescope/pysynphot | commissioning/genscience.py | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/commissioning/genscience.py#L28-L65 | def genstis(outname):
""" Generate TestCases from cmdfile according to the pattern in patternfile"""
pattern="""class stisS%d(countrateCase):
def setUp(self):
self.obsmode="%s"
self.spectrum="%s"
self.setglobal(__file__)
self.runpy()\n"""
speclist=['/grp/hst/cdbs/calspec... | [
"def",
"genstis",
"(",
"outname",
")",
":",
"pattern",
"=",
"\"\"\"class stisS%d(countrateCase):\n def setUp(self):\n self.obsmode=\"%s\"\n self.spectrum=\"%s\"\n self.setglobal(__file__)\n self.runpy()\\n\"\"\"",
"speclist",
"=",
"[",
"'/grp/hst/cdbs/calspec/g... | Generate TestCases from cmdfile according to the pattern in patternfile | [
"Generate",
"TestCases",
"from",
"cmdfile",
"according",
"to",
"the",
"pattern",
"in",
"patternfile"
] | python | train | 28.263158 |
TestInABox/stackInABox | stackinabox/stack.py | https://github.com/TestInABox/stackInABox/blob/63ee457401e9a88d987f85f513eb512dcb12d984/stackinabox/stack.py#L45-L54 | def register_service(cls, service):
"""Add a service to the thread's StackInABox instance.
:param service: StackInABoxService instance to add to the test
For return value and errors see StackInABox.register()
"""
logger.debug('Registering service {0}'.format(service.name))
... | [
"def",
"register_service",
"(",
"cls",
",",
"service",
")",
":",
"logger",
".",
"debug",
"(",
"'Registering service {0}'",
".",
"format",
"(",
"service",
".",
"name",
")",
")",
"return",
"local_store",
".",
"instance",
".",
"register",
"(",
"service",
")"
] | Add a service to the thread's StackInABox instance.
:param service: StackInABoxService instance to add to the test
For return value and errors see StackInABox.register() | [
"Add",
"a",
"service",
"to",
"the",
"thread",
"s",
"StackInABox",
"instance",
"."
] | python | train | 36.1 |
frawau/aiolifx | aiolifx/aiolifx.py | https://github.com/frawau/aiolifx/blob/9bd8c5e6d291f4c79314989402f7e2c6476d5851/aiolifx/aiolifx.py#L861-L892 | def set_color(self, value, callb=None, duration=0, rapid=False):
"""Convenience method to set the colour status of the device
This method will send a LightSetColor message to the device, and request callb be executed
when an ACK is received. The default callback will simply cache the value.
... | [
"def",
"set_color",
"(",
"self",
",",
"value",
",",
"callb",
"=",
"None",
",",
"duration",
"=",
"0",
",",
"rapid",
"=",
"False",
")",
":",
"if",
"len",
"(",
"value",
")",
"==",
"4",
":",
"mypartial",
"=",
"partial",
"(",
"self",
".",
"resp_set_ligh... | Convenience method to set the colour status of the device
This method will send a LightSetColor message to the device, and request callb be executed
when an ACK is received. The default callback will simply cache the value.
:param value: The new state, a dictionary onf int with 4 keys Hue,... | [
"Convenience",
"method",
"to",
"set",
"the",
"colour",
"status",
"of",
"the",
"device"
] | python | train | 47.8125 |
mediawiki-utilities/python-mwreverts | mwreverts/api.py | https://github.com/mediawiki-utilities/python-mwreverts/blob/d379ac941e14e235ad82a48bd445a3dfa6cc022e/mwreverts/api.py#L210-L286 | def check_deleted(session, rev_id, title=None, timestamp=None,
radius=defaults.RADIUS, before=None, window=None,
rvprop=None):
"""
Checks the revert status of a deleted revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by... | [
"def",
"check_deleted",
"(",
"session",
",",
"rev_id",
",",
"title",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"radius",
"=",
"defaults",
".",
"RADIUS",
",",
"before",
"=",
"None",
",",
"window",
"=",
"None",
",",
"rvprop",
"=",
"None",
")",
"... | Checks the revert status of a deleted revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Session`
An API session to make use of
rev_id... | [
"Checks",
"the",
"revert",
"status",
"of",
"a",
"deleted",
"revision",
".",
"With",
"this",
"method",
"you",
"can",
"determine",
"whether",
"an",
"edit",
"is",
"a",
"reverting",
"edit",
"was",
"reverted",
"by",
"another",
"edit",
"and",
"/",
"or",
"was",
... | python | train | 38.090909 |
althonos/pronto | pronto/utils.py | https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/utils.py#L55-L63 | def nowarnings(func):
"""Create a function wrapped in a context that ignores warnings.
"""
@functools.wraps(func)
def new_func(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return func(*args, **kwargs)
return new_func | [
"def",
"nowarnings",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefi... | Create a function wrapped in a context that ignores warnings. | [
"Create",
"a",
"function",
"wrapped",
"in",
"a",
"context",
"that",
"ignores",
"warnings",
"."
] | python | train | 33 |
rodluger/everest | everest/gp.py | https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/gp.py#L92-L192 | def GetKernelParams(time, flux, errors, kernel='Basic', mask=[],
giter=3, gmaxf=200, guess=None):
'''
Optimizes the GP by training it on the current de-trended light curve.
Returns the white noise amplitude, red noise amplitude,
and red noise timescale.
:param array_like time: T... | [
"def",
"GetKernelParams",
"(",
"time",
",",
"flux",
",",
"errors",
",",
"kernel",
"=",
"'Basic'",
",",
"mask",
"=",
"[",
"]",
",",
"giter",
"=",
"3",
",",
"gmaxf",
"=",
"200",
",",
"guess",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"Optim... | Optimizes the GP by training it on the current de-trended light curve.
Returns the white noise amplitude, red noise amplitude,
and red noise timescale.
:param array_like time: The time array
:param array_like flux: The flux array
:param array_like errors: The flux errors array
:param array_like... | [
"Optimizes",
"the",
"GP",
"by",
"training",
"it",
"on",
"the",
"current",
"de",
"-",
"trended",
"light",
"curve",
".",
"Returns",
"the",
"white",
"noise",
"amplitude",
"red",
"noise",
"amplitude",
"and",
"red",
"noise",
"timescale",
"."
] | python | train | 38.029703 |
tensorflow/datasets | tensorflow_datasets/core/download/extractor.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/download/extractor.py#L84-L100 | def _sync_extract(self, from_path, method, to_path):
"""Returns `to_path` once resource has been extracted there."""
to_path_tmp = '%s%s_%s' % (to_path, constants.INCOMPLETE_SUFFIX,
uuid.uuid4().hex)
try:
for path, handle in iter_archive(from_path, method):
_copy... | [
"def",
"_sync_extract",
"(",
"self",
",",
"from_path",
",",
"method",
",",
"to_path",
")",
":",
"to_path_tmp",
"=",
"'%s%s_%s'",
"%",
"(",
"to_path",
",",
"constants",
".",
"INCOMPLETE_SUFFIX",
",",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
")",
"try",... | Returns `to_path` once resource has been extracted there. | [
"Returns",
"to_path",
"once",
"resource",
"has",
"been",
"extracted",
"there",
"."
] | python | train | 47.941176 |
VasilyStepanov/pywidl | pywidl/grammar.py | https://github.com/VasilyStepanov/pywidl/blob/8d84b2e53157bfe276bf16301c19e8b6b32e861e/pywidl/grammar.py#L291-L293 | def p_ConstValue_float(p):
"""ConstValue : FLOAT"""
p[0] = model.Value(type=model.Value.FLOAT, value=p[1]) | [
"def",
"p_ConstValue_float",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"model",
".",
"Value",
"(",
"type",
"=",
"model",
".",
"Value",
".",
"FLOAT",
",",
"value",
"=",
"p",
"[",
"1",
"]",
")"
] | ConstValue : FLOAT | [
"ConstValue",
":",
"FLOAT"
] | python | train | 36 |
Clinical-Genomics/scout | scout/commands/view/transcripts.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/commands/view/transcripts.py#L13-L32 | def transcripts(context, build, hgnc_id, json):
"""Show all transcripts in the database"""
LOG.info("Running scout view transcripts")
adapter = context.obj['adapter']
if not json:
click.echo("Chromosome\tstart\tend\ttranscript_id\thgnc_id\trefseq\tis_primary")
for tx_obj in adapter.transcri... | [
"def",
"transcripts",
"(",
"context",
",",
"build",
",",
"hgnc_id",
",",
"json",
")",
":",
"LOG",
".",
"info",
"(",
"\"Running scout view transcripts\"",
")",
"adapter",
"=",
"context",
".",
"obj",
"[",
"'adapter'",
"]",
"if",
"not",
"json",
":",
"click",
... | Show all transcripts in the database | [
"Show",
"all",
"transcripts",
"in",
"the",
"database"
] | python | test | 35.8 |
kwikteam/phy | phy/gui/actions.py | https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/gui/actions.py#L136-L146 | def _show_shortcuts(shortcuts, name=None):
"""Display shortcuts."""
name = name or ''
print('')
if name:
name = ' for ' + name
print('Keyboard shortcuts' + name)
for name in sorted(shortcuts):
shortcut = _get_shortcut_string(shortcuts[name])
if not name.startswith('_'):
... | [
"def",
"_show_shortcuts",
"(",
"shortcuts",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"''",
"print",
"(",
"''",
")",
"if",
"name",
":",
"name",
"=",
"' for '",
"+",
"name",
"print",
"(",
"'Keyboard shortcuts'",
"+",
"name",
")",
... | Display shortcuts. | [
"Display",
"shortcuts",
"."
] | python | train | 33.545455 |
openid/python-openid | openid/store/sqlstore.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L469-L485 | def db_set_assoc(self, server_url, handle, secret, issued, lifetime, assoc_type):
"""
Set an association. This is implemented as a method because
REPLACE INTO is not supported by PostgreSQL (and is not
standard SQL).
"""
result = self.db_get_assoc(server_url, handle)
... | [
"def",
"db_set_assoc",
"(",
"self",
",",
"server_url",
",",
"handle",
",",
"secret",
",",
"issued",
",",
"lifetime",
",",
"assoc_type",
")",
":",
"result",
"=",
"self",
".",
"db_get_assoc",
"(",
"server_url",
",",
"handle",
")",
"rows",
"=",
"self",
".",... | Set an association. This is implemented as a method because
REPLACE INTO is not supported by PostgreSQL (and is not
standard SQL). | [
"Set",
"an",
"association",
".",
"This",
"is",
"implemented",
"as",
"a",
"method",
"because",
"REPLACE",
"INTO",
"is",
"not",
"supported",
"by",
"PostgreSQL",
"(",
"and",
"is",
"not",
"standard",
"SQL",
")",
"."
] | python | train | 47 |
jrxFive/python-nomad | nomad/api/client.py | https://github.com/jrxFive/python-nomad/blob/37df37e4de21e6f8ac41c6154e7f1f44f1800020/nomad/api/client.py#L43-L59 | def list_files(self, id=None, path="/"):
""" List files in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-ls.html
arguments:
- id
- path
returns: list
raises:
- nomad.api.exceptions.Bas... | [
"def",
"list_files",
"(",
"self",
",",
"id",
"=",
"None",
",",
"path",
"=",
"\"/\"",
")",
":",
"if",
"id",
":",
"return",
"self",
".",
"request",
"(",
"id",
",",
"params",
"=",
"{",
"\"path\"",
":",
"path",
"}",
",",
"method",
"=",
"\"get\"",
")"... | List files in an allocation directory.
https://www.nomadproject.io/docs/http/client-fs-ls.html
arguments:
- id
- path
returns: list
raises:
- nomad.api.exceptions.BaseNomadException
- nomad.api.exceptions.... | [
"List",
"files",
"in",
"an",
"allocation",
"directory",
"."
] | python | test | 34.058824 |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_entry.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L671-L705 | def _TSKFileTimeCopyToStatTimeTuple(self, tsk_file, time_value):
"""Copies a SleuthKit file object time value to a stat timestamp tuple.
Args:
tsk_file (pytsk3.File): TSK file.
time_value (str): name of the time value.
Returns:
tuple[int, int]: number of seconds since 1970-01-01 00:00:00... | [
"def",
"_TSKFileTimeCopyToStatTimeTuple",
"(",
"self",
",",
"tsk_file",
",",
"time_value",
")",
":",
"if",
"(",
"not",
"tsk_file",
"or",
"not",
"tsk_file",
".",
"info",
"or",
"not",
"tsk_file",
".",
"info",
".",
"meta",
"or",
"not",
"tsk_file",
".",
"info"... | Copies a SleuthKit file object time value to a stat timestamp tuple.
Args:
tsk_file (pytsk3.File): TSK file.
time_value (str): name of the time value.
Returns:
tuple[int, int]: number of seconds since 1970-01-01 00:00:00 and fraction
of second in 100 nano seconds intervals. The num... | [
"Copies",
"a",
"SleuthKit",
"file",
"object",
"time",
"value",
"to",
"a",
"stat",
"timestamp",
"tuple",
"."
] | python | train | 41 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.