repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
sjkingo/python-freshdesk | freshdesk/v2/api.py | https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v2/api.py#L456-L459 | def _put(self, url, data={}):
"""Wrapper around request.put() to use the API prefix. Returns a JSON response."""
req = self._session.put(self._api_prefix + url, data=data)
return self._action(req) | [
"def",
"_put",
"(",
"self",
",",
"url",
",",
"data",
"=",
"{",
"}",
")",
":",
"req",
"=",
"self",
".",
"_session",
".",
"put",
"(",
"self",
".",
"_api_prefix",
"+",
"url",
",",
"data",
"=",
"data",
")",
"return",
"self",
".",
"_action",
"(",
"r... | Wrapper around request.put() to use the API prefix. Returns a JSON response. | [
"Wrapper",
"around",
"request",
".",
"put",
"()",
"to",
"use",
"the",
"API",
"prefix",
".",
"Returns",
"a",
"JSON",
"response",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/helpers/volume_scanner.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/helpers/volume_scanner.py#L400-L458 | def GetBasePathSpecs(self, source_path):
"""Determines the base path specifications.
Args:
source_path (str): source path.
Returns:
list[PathSpec]: path specifications.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directo... | [
"def",
"GetBasePathSpecs",
"(",
"self",
",",
"source_path",
")",
":",
"if",
"not",
"source_path",
":",
"raise",
"errors",
".",
"ScannerError",
"(",
"'Invalid source path.'",
")",
"# Note that os.path.exists() does not support Windows device paths.",
"if",
"(",
"not",
"s... | Determines the base path specifications.
Args:
source_path (str): source path.
Returns:
list[PathSpec]: path specifications.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
... | [
"Determines",
"the",
"base",
"path",
"specifications",
"."
] | python | train |
google/grr | grr/server/grr_response_server/databases/db_compat.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/db_compat.py#L154-L166 | def ProcessHuntClientCrash(flow_obj, client_crash_info):
"""Processes client crash triggerted by a given hunt-induced flow."""
if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id):
hunt.StopHuntIfCrashLimitExceeded(flow_obj.parent_hunt_id)
return
hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt... | [
"def",
"ProcessHuntClientCrash",
"(",
"flow_obj",
",",
"client_crash_info",
")",
":",
"if",
"not",
"hunt",
".",
"IsLegacyHunt",
"(",
"flow_obj",
".",
"parent_hunt_id",
")",
":",
"hunt",
".",
"StopHuntIfCrashLimitExceeded",
"(",
"flow_obj",
".",
"parent_hunt_id",
"... | Processes client crash triggerted by a given hunt-induced flow. | [
"Processes",
"client",
"crash",
"triggerted",
"by",
"a",
"given",
"hunt",
"-",
"induced",
"flow",
"."
] | python | train |
cltl/KafNafParserPy | KafNafParserPy/KafNafParserMod.py | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L621-L629 | def get_properties(self):
"""
Returns all the properties of the features layer (iterator)
@rtype: L{Cproperty}
@return: list of properties
"""
if self.features_layer is not None:
for property in self.features_layer.get_properties():
yield prope... | [
"def",
"get_properties",
"(",
"self",
")",
":",
"if",
"self",
".",
"features_layer",
"is",
"not",
"None",
":",
"for",
"property",
"in",
"self",
".",
"features_layer",
".",
"get_properties",
"(",
")",
":",
"yield",
"propertyfound_entities",
".",
"get",
"(",
... | Returns all the properties of the features layer (iterator)
@rtype: L{Cproperty}
@return: list of properties | [
"Returns",
"all",
"the",
"properties",
"of",
"the",
"features",
"layer",
"(",
"iterator",
")"
] | python | train |
guaix-ucm/numina | numina/array/wavecalib/__main__.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/__main__.py#L208-L379 | def find_fxpeaks(sp,
times_sigma_threshold,
minimum_threshold,
nwinwidth_initial,
nwinwidth_refined,
npix_avoid_border,
nbrightlines,
sigma_gaussian_filtering,
minimum_gaussian_filteri... | [
"def",
"find_fxpeaks",
"(",
"sp",
",",
"times_sigma_threshold",
",",
"minimum_threshold",
",",
"nwinwidth_initial",
",",
"nwinwidth_refined",
",",
"npix_avoid_border",
",",
"nbrightlines",
",",
"sigma_gaussian_filtering",
",",
"minimum_gaussian_filtering",
",",
"plottitle",... | Locate line peaks in array coordinates (from 0 to naxis1-1).
Parameters
----------
sp : 1d numpy array
Spectrum to be wavelength calibrated.
times_sigma_threshold : float
Times robust sigma above the median to detect line peaks.
minimum_threshold : float or None
Minimum ... | [
"Locate",
"line",
"peaks",
"in",
"array",
"coordinates",
"(",
"from",
"0",
"to",
"naxis1",
"-",
"1",
")",
"."
] | python | train |
jmgilman/Neolib | neolib/pyamf/codec.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/codec.py#L391-L409 | def writeSequence(self, iterable):
"""
Encodes an iterable. The default is to write If the iterable has an al
"""
try:
alias = self.context.getClassAlias(iterable.__class__)
except (AttributeError, pyamf.UnknownClassAlias):
self.writeList(iterable)
... | [
"def",
"writeSequence",
"(",
"self",
",",
"iterable",
")",
":",
"try",
":",
"alias",
"=",
"self",
".",
"context",
".",
"getClassAlias",
"(",
"iterable",
".",
"__class__",
")",
"except",
"(",
"AttributeError",
",",
"pyamf",
".",
"UnknownClassAlias",
")",
":... | Encodes an iterable. The default is to write If the iterable has an al | [
"Encodes",
"an",
"iterable",
".",
"The",
"default",
"is",
"to",
"write",
"If",
"the",
"iterable",
"has",
"an",
"al"
] | python | train |
pyQode/pyqode.core | pyqode/core/widgets/menu_recents.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/menu_recents.py#L44-L72 | def get_value(self, key, default=None):
"""
Reads value from QSettings
:param key: value key
:param default: default value.
:return: value
"""
def unique(seq, idfun=None):
if idfun is None:
def idfun(x):
return x
... | [
"def",
"get_value",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"def",
"unique",
"(",
"seq",
",",
"idfun",
"=",
"None",
")",
":",
"if",
"idfun",
"is",
"None",
":",
"def",
"idfun",
"(",
"x",
")",
":",
"return",
"x",
"# order pr... | Reads value from QSettings
:param key: value key
:param default: default value.
:return: value | [
"Reads",
"value",
"from",
"QSettings",
":",
"param",
"key",
":",
"value",
"key",
":",
"param",
"default",
":",
"default",
"value",
".",
":",
"return",
":",
"value"
] | python | train |
erinxocon/requests-xml | requests_xml.py | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L115-L122 | def lxml(self) -> _LXML:
"""`lxml <http://lxml.de>`_ representation of the
:class:`Element <Element>` or :class:`XML <XML>`.
"""
if self._lxml is None:
self._lxml = etree.fromstring(self.raw_xml)
return self._lxml | [
"def",
"lxml",
"(",
"self",
")",
"->",
"_LXML",
":",
"if",
"self",
".",
"_lxml",
"is",
"None",
":",
"self",
".",
"_lxml",
"=",
"etree",
".",
"fromstring",
"(",
"self",
".",
"raw_xml",
")",
"return",
"self",
".",
"_lxml"
] | `lxml <http://lxml.de>`_ representation of the
:class:`Element <Element>` or :class:`XML <XML>`. | [
"lxml",
"<http",
":",
"//",
"lxml",
".",
"de",
">",
"_",
"representation",
"of",
"the",
":",
"class",
":",
"Element",
"<Element",
">",
"or",
":",
"class",
":",
"XML",
"<XML",
">",
"."
] | python | train |
titusjan/argos | argos/widgets/mainwindow.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/widgets/mainwindow.py#L241-L261 | def __createInspectorActionGroup(self, parent):
""" Creates an action group with 'set inspector' actions for all installed inspector.
"""
actionGroup = QtWidgets.QActionGroup(parent)
actionGroup.setExclusive(True)
sortedItems = sorted(self.argosApplication.inspectorRegistry.item... | [
"def",
"__createInspectorActionGroup",
"(",
"self",
",",
"parent",
")",
":",
"actionGroup",
"=",
"QtWidgets",
".",
"QActionGroup",
"(",
"parent",
")",
"actionGroup",
".",
"setExclusive",
"(",
"True",
")",
"sortedItems",
"=",
"sorted",
"(",
"self",
".",
"argosA... | Creates an action group with 'set inspector' actions for all installed inspector. | [
"Creates",
"an",
"action",
"group",
"with",
"set",
"inspector",
"actions",
"for",
"all",
"installed",
"inspector",
"."
] | python | train |
inveniosoftware/invenio-files-rest | invenio_files_rest/storage/base.py | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/storage/base.py#L92-L124 | def send_file(self, filename, mimetype=None, restricted=True,
checksum=None, trusted=False, chunk_size=None,
as_attachment=False):
"""Send the file to the client."""
try:
fp = self.open(mode='rb')
except Exception as e:
raise StorageErr... | [
"def",
"send_file",
"(",
"self",
",",
"filename",
",",
"mimetype",
"=",
"None",
",",
"restricted",
"=",
"True",
",",
"checksum",
"=",
"None",
",",
"trusted",
"=",
"False",
",",
"chunk_size",
"=",
"None",
",",
"as_attachment",
"=",
"False",
")",
":",
"t... | Send the file to the client. | [
"Send",
"the",
"file",
"to",
"the",
"client",
"."
] | python | train |
portfors-lab/sparkle | sparkle/gui/dialogs/comment_dlg.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/dialogs/comment_dlg.py#L22-L30 | def setComment(self, msg):
"""Sets the widget text to *msg*
:param msg: overwrites any existing text with *msg*
:type msg: str
"""
self.ui.commentTxtedt.setPlainText(msg)
# move text cursor to end
self.ui.commentTxtedt.moveCursor(QtGui.QTextCursor.End) | [
"def",
"setComment",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"ui",
".",
"commentTxtedt",
".",
"setPlainText",
"(",
"msg",
")",
"# move text cursor to end",
"self",
".",
"ui",
".",
"commentTxtedt",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
... | Sets the widget text to *msg*
:param msg: overwrites any existing text with *msg*
:type msg: str | [
"Sets",
"the",
"widget",
"text",
"to",
"*",
"msg",
"*"
] | python | train |
pecan/pecan | pecan/commands/shell.py | https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/commands/shell.py#L108-L148 | def run(self, args):
"""
Load the pecan app, prepare the locals, sets the
banner, and invokes the python shell.
"""
super(ShellCommand, self).run(args)
# load the application
app = self.load_app()
# prepare the locals
locs = dict(__name__='pecan-... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"super",
"(",
"ShellCommand",
",",
"self",
")",
".",
"run",
"(",
"args",
")",
"# load the application",
"app",
"=",
"self",
".",
"load_app",
"(",
")",
"# prepare the locals",
"locs",
"=",
"dict",
"(",
"... | Load the pecan app, prepare the locals, sets the
banner, and invokes the python shell. | [
"Load",
"the",
"pecan",
"app",
"prepare",
"the",
"locals",
"sets",
"the",
"banner",
"and",
"invokes",
"the",
"python",
"shell",
"."
] | python | train |
FutunnOpen/futuquant | futuquant/quote/open_quote_context.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/quote/open_quote_context.py#L847-L892 | def get_plate_stock(self, plate_code):
"""
获取特定板块下的股票列表
:param plate_code: 板块代码, string, 例如,”SH.BK0001”,”SH.BK0002”,先利用获取子版块列表函数获取子版块代码
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
... | [
"def",
"get_plate_stock",
"(",
"self",
",",
"plate_code",
")",
":",
"if",
"plate_code",
"is",
"None",
"or",
"is_str",
"(",
"plate_code",
")",
"is",
"False",
":",
"error_str",
"=",
"ERROR_STR_PREFIX",
"+",
"\"the type of code is wrong\"",
"return",
"RET_ERROR",
"... | 获取特定板块下的股票列表
:param plate_code: 板块代码, string, 例如,”SH.BK0001”,”SH.BK0002”,先利用获取子版块列表函数获取子版块代码
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== =====================... | [
"获取特定板块下的股票列表"
] | python | train |
rigetti/quantumflow | quantumflow/dagcircuit.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/dagcircuit.py#L97-L113 | def depth(self, local: bool = True) -> int:
"""Return the circuit depth.
Args:
local: If True include local one-qubit gates in depth
calculation. Else return the multi-qubit gate depth.
"""
G = self.graph
if not local:
def remove_local(da... | [
"def",
"depth",
"(",
"self",
",",
"local",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"G",
"=",
"self",
".",
"graph",
"if",
"not",
"local",
":",
"def",
"remove_local",
"(",
"dagc",
":",
"DAGCircuit",
")",
"->",
"Generator",
"[",
"Operation",
... | Return the circuit depth.
Args:
local: If True include local one-qubit gates in depth
calculation. Else return the multi-qubit gate depth. | [
"Return",
"the",
"circuit",
"depth",
"."
] | python | train |
clinicedc/edc-auth | edc_auth/views/login_view.py | https://github.com/clinicedc/edc-auth/blob/e633a5461139d3799f389f7bed0e02c9d2c1e103/edc_auth/views/login_view.py#L13-L21 | def get_context_data(self, **kwargs):
"""Tests cookies.
"""
self.request.session.set_test_cookie()
if not self.request.session.test_cookie_worked():
messages.add_message(
self.request, messages.ERROR, "Please enable cookies.")
self.request.session.dele... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"request",
".",
"session",
".",
"set_test_cookie",
"(",
")",
"if",
"not",
"self",
".",
"request",
".",
"session",
".",
"test_cookie_worked",
"(",
")",
":",
"messages"... | Tests cookies. | [
"Tests",
"cookies",
"."
] | python | train |
bninja/pilo | pilo/context.py | https://github.com/bninja/pilo/blob/32b7298a47e33fb7383103017b4f3b59ad76ea6f/pilo/context.py#L117-L122 | def reset(self):
"""
Used if you need to recursively parse forms.
"""
self.stack.append(Frame(src=None, src_path=None))
return Close(functools.partial(self.restore)) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"Frame",
"(",
"src",
"=",
"None",
",",
"src_path",
"=",
"None",
")",
")",
"return",
"Close",
"(",
"functools",
".",
"partial",
"(",
"self",
".",
"restore",
")",
")"
] | Used if you need to recursively parse forms. | [
"Used",
"if",
"you",
"need",
"to",
"recursively",
"parse",
"forms",
"."
] | python | train |
maxcountryman/atomos | atomos/atomic.py | https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atomic.py#L111-L119 | def add_and_get(self, delta):
'''
Atomically adds `delta` to the current value.
:param delta: The delta to add.
'''
with self._lock.exclusive:
self._value += delta
return self._value | [
"def",
"add_and_get",
"(",
"self",
",",
"delta",
")",
":",
"with",
"self",
".",
"_lock",
".",
"exclusive",
":",
"self",
".",
"_value",
"+=",
"delta",
"return",
"self",
".",
"_value"
] | Atomically adds `delta` to the current value.
:param delta: The delta to add. | [
"Atomically",
"adds",
"delta",
"to",
"the",
"current",
"value",
"."
] | python | train |
MagicTheGathering/mtg-sdk-python | mtgsdk/querybuilder.py | https://github.com/MagicTheGathering/mtg-sdk-python/blob/3d28fe209d72356a559321355d3f7e53ca78a9cc/mtgsdk/querybuilder.py#L93-L100 | def array(self):
"""Get all resources and return the result as an array
Returns:
array of str: Array of resources
"""
url = "{}/{}".format(__endpoint__, self.type.RESOURCE)
return RestClient.get(url, self.params)[self.type.RESOURCE] | [
"def",
"array",
"(",
"self",
")",
":",
"url",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"__endpoint__",
",",
"self",
".",
"type",
".",
"RESOURCE",
")",
"return",
"RestClient",
".",
"get",
"(",
"url",
",",
"self",
".",
"params",
")",
"[",
"self",
".",
"... | Get all resources and return the result as an array
Returns:
array of str: Array of resources | [
"Get",
"all",
"resources",
"and",
"return",
"the",
"result",
"as",
"an",
"array"
] | python | train |
sckott/habanero | habanero/crossref/crossref.py | https://github.com/sckott/habanero/blob/a17d87070378786bbb138e1c9712ecad9aacf38e/habanero/crossref/crossref.py#L627-L659 | def licenses(self, query = None, offset = None,
limit = None, sample = None, sort = None,
order = None, facet = None, **kwargs):
'''
Search Crossref licenses
:param query: [String] A query string
:param offset: [Fixnum] Number of record to start at, from 1 to... | [
"def",
"licenses",
"(",
"self",
",",
"query",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"sample",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"order",
"=",
"None",
",",
"facet",
"=",
"None",
",",
"*",
"*",
"kwargs",... | Search Crossref licenses
:param query: [String] A query string
:param offset: [Fixnum] Number of record to start at, from 1 to 10000
:param limit: [Fixnum] Number of results to return. Not relevant when searching with specific dois. Default: 20. Max: 1000
:param sort: [String] Field to ... | [
"Search",
"Crossref",
"licenses"
] | python | train |
ska-sa/katcp-python | katcp/server.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L2422-L2440 | def level_name(self, level=None):
"""Return the name of the given level value.
If level is None, return the name of the current level.
Parameters
----------
level : logging level constant
The logging level constant whose name to retrieve.
Returns
--... | [
"def",
"level_name",
"(",
"self",
",",
"level",
"=",
"None",
")",
":",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"self",
".",
"_log_level",
"return",
"self",
".",
"LEVELS",
"[",
"level",
"]"
] | Return the name of the given level value.
If level is None, return the name of the current level.
Parameters
----------
level : logging level constant
The logging level constant whose name to retrieve.
Returns
-------
level_name : str
Th... | [
"Return",
"the",
"name",
"of",
"the",
"given",
"level",
"value",
"."
] | python | train |
PyCQA/pyflakes | pyflakes/api.py | https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L81-L99 | def checkPath(filename, reporter=None):
"""
Check the given path, printing out any warnings detected.
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: the number of warnings printed
"""
if reporter is None:
reporter = modReporter._ma... | [
"def",
"checkPath",
"(",
"filename",
",",
"reporter",
"=",
"None",
")",
":",
"if",
"reporter",
"is",
"None",
":",
"reporter",
"=",
"modReporter",
".",
"_makeDefaultReporter",
"(",
")",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
... | Check the given path, printing out any warnings detected.
@param reporter: A L{Reporter} instance, where errors and warnings will be
reported.
@return: the number of warnings printed | [
"Check",
"the",
"given",
"path",
"printing",
"out",
"any",
"warnings",
"detected",
"."
] | python | train |
cloudnull/cloudlib | cloudlib/http.py | https://github.com/cloudnull/cloudlib/blob/5038111ce02521caa2558117e3bae9e1e806d315/cloudlib/http.py#L155-L171 | def post(self, url, headers=None, body=None, kwargs=None):
"""Make a POST request.
To make a POST request pass, ``url``
:param url: ``str``
:param headers: ``dict``
:param body: ``object``
:param kwargs: ``dict``
"""
return self._request(
met... | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"return",
"self",
".",
"_request",
"(",
"method",
"=",
"'post'",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"he... | Make a POST request.
To make a POST request pass, ``url``
:param url: ``str``
:param headers: ``dict``
:param body: ``object``
:param kwargs: ``dict`` | [
"Make",
"a",
"POST",
"request",
"."
] | python | train |
google/transitfeed | transitfeed/schedule.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L1169-L1203 | def ValidateStopTimesForTrip(self, problems, trip, stop_times):
"""Checks for the stop times of a trip.
Ensure that a trip does not have too many consecutive stop times with the
same departure/arrival time."""
prev_departure_secs = -1
consecutive_stop_times_with_potentially_same_time = 0
consec... | [
"def",
"ValidateStopTimesForTrip",
"(",
"self",
",",
"problems",
",",
"trip",
",",
"stop_times",
")",
":",
"prev_departure_secs",
"=",
"-",
"1",
"consecutive_stop_times_with_potentially_same_time",
"=",
"0",
"consecutive_stop_times_with_fully_specified_same_time",
"=",
"0",... | Checks for the stop times of a trip.
Ensure that a trip does not have too many consecutive stop times with the
same departure/arrival time. | [
"Checks",
"for",
"the",
"stop",
"times",
"of",
"a",
"trip",
"."
] | python | train |
nephila/djangocms-blog | djangocms_blog/admin.py | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L387-L451 | def get_fieldsets(self, request, obj=None):
"""
Fieldsets configuration
"""
return [
(None, {
'fields': ('type', 'namespace', 'app_title', 'object_name')
}),
(_('Generic'), {
'fields': (
'config.defau... | [
"def",
"get_fieldsets",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"return",
"[",
"(",
"None",
",",
"{",
"'fields'",
":",
"(",
"'type'",
",",
"'namespace'",
",",
"'app_title'",
",",
"'object_name'",
")",
"}",
")",
",",
"(",
"_",
... | Fieldsets configuration | [
"Fieldsets",
"configuration"
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/proxy/pn_counter.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/pn_counter.py#L105-L117 | def get_and_subtract(self, delta):
"""
Subtracts the given value from the current value and returns the previous value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less than 3.10.
... | [
"def",
"get_and_subtract",
"(",
"self",
",",
"delta",
")",
":",
"return",
"self",
".",
"_invoke_internal",
"(",
"pn_counter_add_codec",
",",
"delta",
"=",
"-",
"1",
"*",
"delta",
",",
"get_before_update",
"=",
"True",
")"
] | Subtracts the given value from the current value and returns the previous value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less than 3.10.
:raises ConsistencyLostError: if the session guaran... | [
"Subtracts",
"the",
"given",
"value",
"from",
"the",
"current",
"value",
"and",
"returns",
"the",
"previous",
"value",
"."
] | python | train |
singnet/snet-cli | snet_cli/utils_config.py | https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/utils_config.py#L3-L31 | def get_contract_address(cmd, contract_name, error_message = None):
"""
We try to get config address from the different sources.
The order of priorioty is following:
- command line argument (at)
- command line argument (<contract_name>_at)
- current session configuration (current_<contract_name>... | [
"def",
"get_contract_address",
"(",
"cmd",
",",
"contract_name",
",",
"error_message",
"=",
"None",
")",
":",
"# try to get from command line argument at or contractname_at",
"a",
"=",
"\"at\"",
"if",
"(",
"hasattr",
"(",
"cmd",
".",
"args",
",",
"a",
")",
"and",
... | We try to get config address from the different sources.
The order of priorioty is following:
- command line argument (at)
- command line argument (<contract_name>_at)
- current session configuration (current_<contract_name>_at)
- networks/*json | [
"We",
"try",
"to",
"get",
"config",
"address",
"from",
"the",
"different",
"sources",
".",
"The",
"order",
"of",
"priorioty",
"is",
"following",
":",
"-",
"command",
"line",
"argument",
"(",
"at",
")",
"-",
"command",
"line",
"argument",
"(",
"<contract_na... | python | train |
andrenarchy/krypy | krypy/recycling/evaluators.py | https://github.com/andrenarchy/krypy/blob/4883ec9a61d64ea56489e15c35cc40f0633ab2f1/krypy/recycling/evaluators.py#L76-L135 | def _estimate_eval_intervals(ritz, indices, indices_remaining,
eps_min=0,
eps_max=0,
eps_res=None):
'''Estimate evals based on eval inclusion theorem + heuristic.
:returns: Intervals object with inclusion... | [
"def",
"_estimate_eval_intervals",
"(",
"ritz",
",",
"indices",
",",
"indices_remaining",
",",
"eps_min",
"=",
"0",
",",
"eps_max",
"=",
"0",
",",
"eps_res",
"=",
"None",
")",
":",
"if",
"len",
"(",
"indices",
")",
"==",
"0",
":",
"return",
"utils",
".... | Estimate evals based on eval inclusion theorem + heuristic.
:returns: Intervals object with inclusion intervals for eigenvalues | [
"Estimate",
"evals",
"based",
"on",
"eval",
"inclusion",
"theorem",
"+",
"heuristic",
"."
] | python | train |
awacha/sastool | sastool/misc/basicfit.py | https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/misc/basicfit.py#L18-L38 | def findpeak(x, y, dy=None, position=None, hwhm=None, baseline=None, amplitude=None, curve='Lorentz'):
"""Find a (positive) peak in the dataset.
This function is deprecated, please consider using findpeak_single() instead.
Inputs:
x, y, dy: abscissa, ordinate and the error of the ordinate (can... | [
"def",
"findpeak",
"(",
"x",
",",
"y",
",",
"dy",
"=",
"None",
",",
"position",
"=",
"None",
",",
"hwhm",
"=",
"None",
",",
"baseline",
"=",
"None",
",",
"amplitude",
"=",
"None",
",",
"curve",
"=",
"'Lorentz'",
")",
":",
"warnings",
".",
"warn",
... | Find a (positive) peak in the dataset.
This function is deprecated, please consider using findpeak_single() instead.
Inputs:
x, y, dy: abscissa, ordinate and the error of the ordinate (can be None)
position, hwhm, baseline, amplitude: first guesses for the named parameters
curve: '... | [
"Find",
"a",
"(",
"positive",
")",
"peak",
"in",
"the",
"dataset",
".",
"This",
"function",
"is",
"deprecated",
"please",
"consider",
"using",
"findpeak_single",
"()",
"instead",
"."
] | python | train |
riverrun/drat | drat/analysis.py | https://github.com/riverrun/drat/blob/50cbbf69c022b6ca6641cd55386813b0695c21f5/drat/analysis.py#L30-L43 | def load_common(self, wlist):
"""Create the dictionary of common words."""
self.com_dict = os.path.join(self.base_dir, 'dicts', 'EN_vocab.txt')
with open(self.com_dict) as words_file:
data = words_file.read()
self.common_words = set(data.splitlines())
if wlist:
... | [
"def",
"load_common",
"(",
"self",
",",
"wlist",
")",
":",
"self",
".",
"com_dict",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base_dir",
",",
"'dicts'",
",",
"'EN_vocab.txt'",
")",
"with",
"open",
"(",
"self",
".",
"com_dict",
")",
"as"... | Create the dictionary of common words. | [
"Create",
"the",
"dictionary",
"of",
"common",
"words",
"."
] | python | train |
ioos/compliance-checker | compliance_checker/ioos.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/ioos.py#L57-L73 | def check_time_period(self, ds):
"""
Check that time period attributes are both set.
"""
start = self.std_check(ds, 'time_coverage_start')
end = self.std_check(ds, 'time_coverage_end')
msgs = []
count = 2
if not start:
count -= 1
m... | [
"def",
"check_time_period",
"(",
"self",
",",
"ds",
")",
":",
"start",
"=",
"self",
".",
"std_check",
"(",
"ds",
",",
"'time_coverage_start'",
")",
"end",
"=",
"self",
".",
"std_check",
"(",
"ds",
",",
"'time_coverage_end'",
")",
"msgs",
"=",
"[",
"]",
... | Check that time period attributes are both set. | [
"Check",
"that",
"time",
"period",
"attributes",
"are",
"both",
"set",
"."
] | python | train |
acorg/dark-matter | dark/blast/hacks.py | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/hacks.py#L4-L32 | def printBlastRecordForDerek(record):
"""
This is a hacked version of printBlastRecord that I wrote in
Addenbrookes hospital so Derek could try hacking on the reads
that had low e values. It's called by bin/print-blast-xml-for-derek.py
"""
if len(record.alignments) == 0:
return 0
if... | [
"def",
"printBlastRecordForDerek",
"(",
"record",
")",
":",
"if",
"len",
"(",
"record",
".",
"alignments",
")",
"==",
"0",
":",
"return",
"0",
"if",
"record",
".",
"descriptions",
"[",
"0",
"]",
".",
"e",
">",
"1e-120",
":",
"return",
"0",
"print",
"... | This is a hacked version of printBlastRecord that I wrote in
Addenbrookes hospital so Derek could try hacking on the reads
that had low e values. It's called by bin/print-blast-xml-for-derek.py | [
"This",
"is",
"a",
"hacked",
"version",
"of",
"printBlastRecord",
"that",
"I",
"wrote",
"in",
"Addenbrookes",
"hospital",
"so",
"Derek",
"could",
"try",
"hacking",
"on",
"the",
"reads",
"that",
"had",
"low",
"e",
"values",
".",
"It",
"s",
"called",
"by",
... | python | train |
ruipgil/TrackToTrip | tracktotrip/similarity.py | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/similarity.py#L217-L259 | def segment_similarity(A, B, T=CLOSE_DISTANCE_THRESHOLD):
"""Computes the similarity between two segments
Args:
A (:obj:`Segment`)
B (:obj:`Segment`)
Returns:
float: between 0 and 1. Where 1 is very similar and 0 is completely different
"""
l_a = len(A.points)
l_b = len(... | [
"def",
"segment_similarity",
"(",
"A",
",",
"B",
",",
"T",
"=",
"CLOSE_DISTANCE_THRESHOLD",
")",
":",
"l_a",
"=",
"len",
"(",
"A",
".",
"points",
")",
"l_b",
"=",
"len",
"(",
"B",
".",
"points",
")",
"idx",
"=",
"index",
".",
"Index",
"(",
")",
"... | Computes the similarity between two segments
Args:
A (:obj:`Segment`)
B (:obj:`Segment`)
Returns:
float: between 0 and 1. Where 1 is very similar and 0 is completely different | [
"Computes",
"the",
"similarity",
"between",
"two",
"segments"
] | python | train |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/main.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/main.py#L15-L25 | def print_version():
"""Print the environment versions."""
click.echo("Versions:")
click.secho(
"CLI Package Version: %(version)s"
% {"version": click.style(get_cli_version(), bold=True)}
)
click.secho(
"API Package Version: %(version)s"
% {"version": click.style(get_... | [
"def",
"print_version",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"Versions:\"",
")",
"click",
".",
"secho",
"(",
"\"CLI Package Version: %(version)s\"",
"%",
"{",
"\"version\"",
":",
"click",
".",
"style",
"(",
"get_cli_version",
"(",
")",
",",
"bold",
"=... | Print the environment versions. | [
"Print",
"the",
"environment",
"versions",
"."
] | python | train |
LordDarkula/chess_py | chess_py/game/game_state.py | https://github.com/LordDarkula/chess_py/blob/14bebc2f8c49ae25c59375cc83d0b38d8ff7281d/chess_py/game/game_state.py#L13-L21 | def no_moves(position):
"""
Finds if the game is over.
:type: position: Board
:rtype: bool
"""
return position.no_moves(color.white) \
or position.no_moves(color.black) | [
"def",
"no_moves",
"(",
"position",
")",
":",
"return",
"position",
".",
"no_moves",
"(",
"color",
".",
"white",
")",
"or",
"position",
".",
"no_moves",
"(",
"color",
".",
"black",
")"
] | Finds if the game is over.
:type: position: Board
:rtype: bool | [
"Finds",
"if",
"the",
"game",
"is",
"over",
"."
] | python | train |
nephila/python-taiga | taiga/models/models.py | https://github.com/nephila/python-taiga/blob/5b471d6b8b59e5d410162a6f1c2f0d4188445a56/taiga/models/models.py#L1217-L1231 | def add_milestone(self, name, estimated_start, estimated_finish, **attrs):
"""
Add a Milestone to the project and returns a :class:`Milestone` object.
:param name: name of the :class:`Milestone`
:param estimated_start: estimated start time of the
:class:`... | [
"def",
"add_milestone",
"(",
"self",
",",
"name",
",",
"estimated_start",
",",
"estimated_finish",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"Milestones",
"(",
"self",
".",
"requester",
")",
".",
"create",
"(",
"self",
".",
"id",
",",
"name",
",",
"e... | Add a Milestone to the project and returns a :class:`Milestone` object.
:param name: name of the :class:`Milestone`
:param estimated_start: estimated start time of the
:class:`Milestone`
:param estimated_finish: estimated finish time of the
... | [
"Add",
"a",
"Milestone",
"to",
"the",
"project",
"and",
"returns",
"a",
":",
"class",
":",
"Milestone",
"object",
"."
] | python | train |
HazyResearch/fonduer | src/fonduer/utils/logging/tensorboard_writer.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/logging/tensorboard_writer.py#L12-L14 | def add_scalar(self, name, value, step):
"""Log a scalar variable."""
self.writer.add_scalar(name, value, step) | [
"def",
"add_scalar",
"(",
"self",
",",
"name",
",",
"value",
",",
"step",
")",
":",
"self",
".",
"writer",
".",
"add_scalar",
"(",
"name",
",",
"value",
",",
"step",
")"
] | Log a scalar variable. | [
"Log",
"a",
"scalar",
"variable",
"."
] | python | train |
SheffieldML/GPy | GPy/likelihoods/gaussian.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/likelihoods/gaussian.py#L121-L137 | def pdf_link(self, link_f, y, Y_metadata=None):
"""
Likelihood function given link(f)
.. math::
\\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2}
:param link_f: late... | [
"def",
"pdf_link",
"(",
"self",
",",
"link_f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"#Assumes no covariance, exp, sum, log for numerical stability",
"return",
"np",
".",
"exp",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"log",
"(",
"stats",
".",
... | Likelihood function given link(f)
.. math::
\\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2}
:param link_f: latent variables link(f)
:type link_f: Nx1 array
:param ... | [
"Likelihood",
"function",
"given",
"link",
"(",
"f",
")"
] | python | train |
maas/python-libmaas | maas/client/flesh/tabular.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/tabular.py#L185-L193 | def _filter_rows(self, rows, visible_columns=None):
"""Filter `rows` based on the visible columns."""
if visible_columns is None:
visible_columns = self.visible_columns
filtered_row = []
for idx, name in enumerate(self.columns.keys()):
if name in self.visible_colu... | [
"def",
"_filter_rows",
"(",
"self",
",",
"rows",
",",
"visible_columns",
"=",
"None",
")",
":",
"if",
"visible_columns",
"is",
"None",
":",
"visible_columns",
"=",
"self",
".",
"visible_columns",
"filtered_row",
"=",
"[",
"]",
"for",
"idx",
",",
"name",
"i... | Filter `rows` based on the visible columns. | [
"Filter",
"rows",
"based",
"on",
"the",
"visible",
"columns",
"."
] | python | train |
rigetti/quantumflow | quantumflow/decompositions.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/decompositions.py#L161-L259 | def canonical_decomposition(gate: Gate) -> Circuit:
"""Decompose a 2-qubit gate by removing local 1-qubit gates to leave
the non-local canonical two-qubit gate. [1]_ [2]_ [3]_ [4]_
Returns: A Circuit of 5 gates: two initial 1-qubit gates; a CANONICAL
gate, with coordinates in the Weyl chamber; two fina... | [
"def",
"canonical_decomposition",
"(",
"gate",
":",
"Gate",
")",
"->",
"Circuit",
":",
"# Implementation note: The canonical decomposition is easy. Constraining",
"# canonical coordinates to the Weyl chamber is easy. But doing the",
"# canonical decomposition with the canonical gate in the W... | Decompose a 2-qubit gate by removing local 1-qubit gates to leave
the non-local canonical two-qubit gate. [1]_ [2]_ [3]_ [4]_
Returns: A Circuit of 5 gates: two initial 1-qubit gates; a CANONICAL
gate, with coordinates in the Weyl chamber; two final 1-qubit gates
The canonical coordinates can be found... | [
"Decompose",
"a",
"2",
"-",
"qubit",
"gate",
"by",
"removing",
"local",
"1",
"-",
"qubit",
"gates",
"to",
"leave",
"the",
"non",
"-",
"local",
"canonical",
"two",
"-",
"qubit",
"gate",
".",
"[",
"1",
"]",
"_",
"[",
"2",
"]",
"_",
"[",
"3",
"]",
... | python | train |
iotile/coretools | iotilecore/iotile/core/utilities/command_file.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L80-L109 | def FromString(cls, indata):
"""Load a CommandFile from a string.
The string should be produced from a previous call to
encode.
Args:
indata (str): The encoded input data.
Returns:
CommandFile: The decoded CommandFile object.
"""
lines ... | [
"def",
"FromString",
"(",
"cls",
",",
"indata",
")",
":",
"lines",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"indata",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"not",
"x",
".",
"startswith",
"(",
"'#'",
")",
"and",
"not",
"x",
".... | Load a CommandFile from a string.
The string should be produced from a previous call to
encode.
Args:
indata (str): The encoded input data.
Returns:
CommandFile: The decoded CommandFile object. | [
"Load",
"a",
"CommandFile",
"from",
"a",
"string",
"."
] | python | train |
nabetama/slacky | slacky/rest/rest.py | https://github.com/nabetama/slacky/blob/dde62ce49af9b8f581729c36d2ac790310b570e4/slacky/rest/rest.py#L562-L570 | def set_topic(self, group_name, topic):
""" https://api.slack.com/methods/groups.setTopic
"""
group_id = self.get_group_id(group_name)
self.params.update({
'channel': group_id,
'topic': topic,
})
return FromUrl('https://slack.com/api/groups.s... | [
"def",
"set_topic",
"(",
"self",
",",
"group_name",
",",
"topic",
")",
":",
"group_id",
"=",
"self",
".",
"get_group_id",
"(",
"group_name",
")",
"self",
".",
"params",
".",
"update",
"(",
"{",
"'channel'",
":",
"group_id",
",",
"'topic'",
":",
"topic",
... | https://api.slack.com/methods/groups.setTopic | [
"https",
":",
"//",
"api",
".",
"slack",
".",
"com",
"/",
"methods",
"/",
"groups",
".",
"setTopic"
] | python | train |
dw/mitogen | ansible_mitogen/affinity.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/affinity.py#L250-L259 | def _mask_to_bytes(self, mask):
"""
Convert the (type long) mask to a cpu_set_t.
"""
chunks = []
shiftmask = (2 ** 64) - 1
for x in range(16):
chunks.append(struct.pack('<Q', mask & shiftmask))
mask >>= 64
return mitogen.core.b('').join(chu... | [
"def",
"_mask_to_bytes",
"(",
"self",
",",
"mask",
")",
":",
"chunks",
"=",
"[",
"]",
"shiftmask",
"=",
"(",
"2",
"**",
"64",
")",
"-",
"1",
"for",
"x",
"in",
"range",
"(",
"16",
")",
":",
"chunks",
".",
"append",
"(",
"struct",
".",
"pack",
"(... | Convert the (type long) mask to a cpu_set_t. | [
"Convert",
"the",
"(",
"type",
"long",
")",
"mask",
"to",
"a",
"cpu_set_t",
"."
] | python | train |
saschpe/rapport | rapport/plugin.py | https://github.com/saschpe/rapport/blob/ccceb8f84bd7e8add88ab5e137cdab6424aa4683/rapport/plugin.py#L94-L101 | def _get_plugin_dirs():
"""Return a list of directories where plugins may be located.
"""
plugin_dirs = [
os.path.expanduser(os.path.join(USER_CONFIG_DIR, "plugins")),
os.path.join("rapport", "plugins") # Local dev tree
]
return plugin_dirs | [
"def",
"_get_plugin_dirs",
"(",
")",
":",
"plugin_dirs",
"=",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"join",
"(",
"USER_CONFIG_DIR",
",",
"\"plugins\"",
")",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"\"rapport\"",... | Return a list of directories where plugins may be located. | [
"Return",
"a",
"list",
"of",
"directories",
"where",
"plugins",
"may",
"be",
"located",
"."
] | python | train |
genialis/resolwe | resolwe/flow/migration_ops.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L408-L438 | def migrate_process_schema(self, process, schema, from_state):
"""Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise
"""
... | [
"def",
"migrate_process_schema",
"(",
"self",
",",
"process",
",",
"schema",
",",
"from_state",
")",
":",
"container",
"=",
"dict_dot",
"(",
"schema",
",",
"'.'",
".",
"join",
"(",
"self",
".",
"field",
"[",
":",
"-",
"1",
"]",
")",
",",
"default",
"... | Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise | [
"Migrate",
"process",
"schema",
"."
] | python | train |
ToFuProject/tofu | tofu/pathfile.py | https://github.com/ToFuProject/tofu/blob/39d6b2e7ced9e13666572dfd37e19403f1d6ff8d/tofu/pathfile.py#L374-L386 | def set_USRdict(self,USRdict={}):
""" Set the USRdict, containing user-defined info about the instance
Useful for arbitrary info (e.g.: manufacturing date, material...)
Parameters
----------
USRdict : dict
A user-defined dictionary containing info about the instan... | [
"def",
"set_USRdict",
"(",
"self",
",",
"USRdict",
"=",
"{",
"}",
")",
":",
"self",
".",
"_check_inputs",
"(",
"USRdict",
"=",
"USRdict",
")",
"self",
".",
"_USRdict",
"=",
"USRdict"
] | Set the USRdict, containing user-defined info about the instance
Useful for arbitrary info (e.g.: manufacturing date, material...)
Parameters
----------
USRdict : dict
A user-defined dictionary containing info about the instance | [
"Set",
"the",
"USRdict",
"containing",
"user",
"-",
"defined",
"info",
"about",
"the",
"instance"
] | python | train |
cni/MRS | MRS/utils.py | https://github.com/cni/MRS/blob/16098b3cf4830780efd787fee9efa46513850283/MRS/utils.py#L479-L490 | def two_lorentzian(freq, freq0_1, freq0_2, area1, area2, hwhm1, hwhm2, phase1,
phase2, offset, drift):
"""
A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and pha... | [
"def",
"two_lorentzian",
"(",
"freq",
",",
"freq0_1",
",",
"freq0_2",
",",
"area1",
",",
"area2",
",",
"hwhm1",
",",
"hwhm2",
",",
"phase1",
",",
"phase2",
",",
"offset",
",",
"drift",
")",
":",
"return",
"(",
"lorentzian",
"(",
"freq",
",",
"freq0_1",... | A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and phase, but they share common offset and drift parameters. | [
"A",
"two",
"-",
"Lorentzian",
"model",
"."
] | python | train |
krischer/django-plugins | djangoplugins/point.py | https://github.com/krischer/django-plugins/blob/0064e3306a7ed7af83f1ff51231acdf7478215fe/djangoplugins/point.py#L63-L86 | def get_model(cls, name=None, status=ENABLED):
"""
Returns model instance of plugin point or plugin, depending from which
class this methos is called.
Example::
plugin_model_instance = MyPlugin.get_model()
plugin_model_instance = MyPluginPoint.get_model('plugin-... | [
"def",
"get_model",
"(",
"cls",
",",
"name",
"=",
"None",
",",
"status",
"=",
"ENABLED",
")",
":",
"ppath",
"=",
"cls",
".",
"get_pythonpath",
"(",
")",
"if",
"is_plugin_point",
"(",
"cls",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"kwargs",
... | Returns model instance of plugin point or plugin, depending from which
class this methos is called.
Example::
plugin_model_instance = MyPlugin.get_model()
plugin_model_instance = MyPluginPoint.get_model('plugin-name')
plugin_point_model_instance = MyPluginPoint.get_... | [
"Returns",
"model",
"instance",
"of",
"plugin",
"point",
"or",
"plugin",
"depending",
"from",
"which",
"class",
"this",
"methos",
"is",
"called",
"."
] | python | train |
MisterY/gnucash-portfolio | gnucash_portfolio/accounts.py | https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L327-L330 | def get_by_name(self, name: str) -> List[Account]:
""" Searches accounts by name """
# return self.query.filter(Account.name == name).all()
return self.get_by_name_from(self.book.root, name) | [
"def",
"get_by_name",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"List",
"[",
"Account",
"]",
":",
"# return self.query.filter(Account.name == name).all()",
"return",
"self",
".",
"get_by_name_from",
"(",
"self",
".",
"book",
".",
"root",
",",
"name",
")... | Searches accounts by name | [
"Searches",
"accounts",
"by",
"name"
] | python | train |
getpelican/pelican-plugins | photos/photos.py | https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/photos/photos.py#L592-L600 | def register():
"""Uses the new style of registration based on GitHub Pelican issue #314."""
signals.initialized.connect(initialized)
try:
signals.content_object_init.connect(detect_content)
signals.all_generators_finalized.connect(detect_images_and_galleries)
signals.article_writer_... | [
"def",
"register",
"(",
")",
":",
"signals",
".",
"initialized",
".",
"connect",
"(",
"initialized",
")",
"try",
":",
"signals",
".",
"content_object_init",
".",
"connect",
"(",
"detect_content",
")",
"signals",
".",
"all_generators_finalized",
".",
"connect",
... | Uses the new style of registration based on GitHub Pelican issue #314. | [
"Uses",
"the",
"new",
"style",
"of",
"registration",
"based",
"on",
"GitHub",
"Pelican",
"issue",
"#314",
"."
] | python | train |
stevelittlefish/littlefish | littlefish/validation.py | https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/validation.py#L22-L38 | def luhn_check(card_number):
""" checks to make sure that the card passes a luhn mod-10 checksum """
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(0, num_digits):
digit = int(card_number[count])
if not ((count & 1) ^ oddeven):
digit *... | [
"def",
"luhn_check",
"(",
"card_number",
")",
":",
"sum",
"=",
"0",
"num_digits",
"=",
"len",
"(",
"card_number",
")",
"oddeven",
"=",
"num_digits",
"&",
"1",
"for",
"count",
"in",
"range",
"(",
"0",
",",
"num_digits",
")",
":",
"digit",
"=",
"int",
... | checks to make sure that the card passes a luhn mod-10 checksum | [
"checks",
"to",
"make",
"sure",
"that",
"the",
"card",
"passes",
"a",
"luhn",
"mod",
"-",
"10",
"checksum"
] | python | test |
CiscoDevNet/webexteamssdk | webexteamssdk/models/mixins/webhook.py | https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/models/mixins/webhook.py#L113-L119 | def created(self):
"""Creation date and time in ISO8601 format."""
created = self._json_data.get('created')
if created:
return WebexTeamsDateTime.strptime(created)
else:
return None | [
"def",
"created",
"(",
"self",
")",
":",
"created",
"=",
"self",
".",
"_json_data",
".",
"get",
"(",
"'created'",
")",
"if",
"created",
":",
"return",
"WebexTeamsDateTime",
".",
"strptime",
"(",
"created",
")",
"else",
":",
"return",
"None"
] | Creation date and time in ISO8601 format. | [
"Creation",
"date",
"and",
"time",
"in",
"ISO8601",
"format",
"."
] | python | test |
dw/mitogen | mitogen/parent.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/parent.py#L1705-L1718 | def call(self, fn, *args, **kwargs):
"""
Like :meth:`call_async`, but block until the return value is available.
Equivalent to::
call_async(fn, *args, **kwargs).get().unpickle()
:returns:
The function's return value.
:raises mitogen.core.CallError:
... | [
"def",
"call",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"receiver",
"=",
"self",
".",
"call_async",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"receiver",
".",
"get",
"(",
")",
".",
... | Like :meth:`call_async`, but block until the return value is available.
Equivalent to::
call_async(fn, *args, **kwargs).get().unpickle()
:returns:
The function's return value.
:raises mitogen.core.CallError:
An exception was raised in the remote context duri... | [
"Like",
":",
"meth",
":",
"call_async",
"but",
"block",
"until",
"the",
"return",
"value",
"is",
"available",
".",
"Equivalent",
"to",
"::"
] | python | train |
materialsproject/pymatgen | pymatgen/io/lammps/utils.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/lammps/utils.py#L349-L360 | def _set_residue_map(self):
"""
map each residue to the corresponding molecule.
"""
self.map_residue_to_mol = {}
lookup = {}
for idx, mol in enumerate(self.mols):
if not mol.formula in lookup:
mol.translate_sites(indices=range(len(mol)),
... | [
"def",
"_set_residue_map",
"(",
"self",
")",
":",
"self",
".",
"map_residue_to_mol",
"=",
"{",
"}",
"lookup",
"=",
"{",
"}",
"for",
"idx",
",",
"mol",
"in",
"enumerate",
"(",
"self",
".",
"mols",
")",
":",
"if",
"not",
"mol",
".",
"formula",
"in",
... | map each residue to the corresponding molecule. | [
"map",
"each",
"residue",
"to",
"the",
"corresponding",
"molecule",
"."
] | python | train |
umutbozkurt/django-rest-framework-mongoengine | rest_framework_mongoengine/serializers.py | https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/2fe6de53907b31a5e8b742e4c6b728942b5fa4f0/rest_framework_mongoengine/serializers.py#L839-L861 | def _get_dynamic_data(self, validated_data):
"""
Returns dict of data, not declared in serializer fields.
Should be called after self.is_valid().
"""
result = {}
for key in self.initial_data:
if key not in validated_data:
try:
... | [
"def",
"_get_dynamic_data",
"(",
"self",
",",
"validated_data",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"initial_data",
":",
"if",
"key",
"not",
"in",
"validated_data",
":",
"try",
":",
"field",
"=",
"self",
".",
"fields",
"... | Returns dict of data, not declared in serializer fields.
Should be called after self.is_valid(). | [
"Returns",
"dict",
"of",
"data",
"not",
"declared",
"in",
"serializer",
"fields",
".",
"Should",
"be",
"called",
"after",
"self",
".",
"is_valid",
"()",
"."
] | python | train |
trustar/trustar-python | trustar/tag_client.py | https://github.com/trustar/trustar-python/blob/707d51adc58d68aed7de12a4ca37949cb75cf122/trustar/tag_client.py#L52-L65 | def delete_enclave_tag(self, report_id, tag_id, id_type=None):
"""
Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or... | [
"def",
"delete_enclave_tag",
"(",
"self",
",",
"report_id",
",",
"tag_id",
",",
"id_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'idType'",
":",
"id_type",
"}",
"self",
".",
"_client",
".",
"delete",
"(",
"\"reports/%s/tags/%s\"",
"%",
"(",
"report_i... | Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or an external ID provided by the user
:return: The response body. | [
"Deletes",
"a",
"tag",
"from",
"a",
"specific",
"report",
"in",
"a",
"specific",
"enclave",
"."
] | python | train |
transifex/transifex-python-library | txlib/api/base.py | https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L213-L236 | def save(self, **fields):
"""Save the instance to the remote Transifex server.
If it was pre-populated, it updates the instance on the server,
otherwise it creates a new object.
Any values given in `fields` will be attempted to be saved
on the object. The same goes for any othe... | [
"def",
"save",
"(",
"self",
",",
"*",
"*",
"fields",
")",
":",
"for",
"field",
"in",
"fields",
":",
"if",
"field",
"in",
"self",
".",
"writable_fields",
":",
"setattr",
"(",
"self",
",",
"field",
",",
"fields",
"[",
"field",
"]",
")",
"else",
":",
... | Save the instance to the remote Transifex server.
If it was pre-populated, it updates the instance on the server,
otherwise it creates a new object.
Any values given in `fields` will be attempted to be saved
on the object. The same goes for any other values already set
to the o... | [
"Save",
"the",
"instance",
"to",
"the",
"remote",
"Transifex",
"server",
"."
] | python | train |
SetBased/py-stratum | pystratum/Connection.py | https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/Connection.py#L28-L50 | def _get_option(config, supplement, section, option, fallback=None):
"""
Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name... | [
"def",
"_get_option",
"(",
"config",
",",
"supplement",
",",
"section",
",",
"option",
",",
"fallback",
"=",
"None",
")",
":",
"if",
"supplement",
":",
"return_value",
"=",
"supplement",
".",
"get",
"(",
"section",
",",
"option",
",",
"fallback",
"=",
"c... | Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name of the section op the option.
:param str option: The name of the option.
... | [
"Reads",
"an",
"option",
"for",
"a",
"configuration",
"file",
"."
] | python | train |
aleju/imgaug | imgaug/imgaug.py | https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1619-L1647 | def avg_pool(arr, block_size, cval=0, preserve_dtype=True):
"""
Resize an array using average pooling.
dtype support::
See :func:`imgaug.imgaug.pool`.
Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
Image-like array to pool. See :func:`imgaug.pool` for details.
... | [
"def",
"avg_pool",
"(",
"arr",
",",
"block_size",
",",
"cval",
"=",
"0",
",",
"preserve_dtype",
"=",
"True",
")",
":",
"return",
"pool",
"(",
"arr",
",",
"block_size",
",",
"np",
".",
"average",
",",
"cval",
"=",
"cval",
",",
"preserve_dtype",
"=",
"... | Resize an array using average pooling.
dtype support::
See :func:`imgaug.imgaug.pool`.
Parameters
----------
arr : (H,W) ndarray or (H,W,C) ndarray
Image-like array to pool. See :func:`imgaug.pool` for details.
block_size : int or tuple of int or tuple of int
Size of each... | [
"Resize",
"an",
"array",
"using",
"average",
"pooling",
"."
] | python | valid |
fermiPy/fermipy | fermipy/tsmap.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L104-L262 | def convert_tscube_old(infile, outfile):
"""Convert between old and new TSCube formats."""
inhdulist = fits.open(infile)
# If already in the new-style format just write and exit
if 'DLOGLIKE_SCAN' in inhdulist['SCANDATA'].columns.names:
if infile != outfile:
inhdulist.writeto(outfil... | [
"def",
"convert_tscube_old",
"(",
"infile",
",",
"outfile",
")",
":",
"inhdulist",
"=",
"fits",
".",
"open",
"(",
"infile",
")",
"# If already in the new-style format just write and exit",
"if",
"'DLOGLIKE_SCAN'",
"in",
"inhdulist",
"[",
"'SCANDATA'",
"]",
".",
"col... | Convert between old and new TSCube formats. | [
"Convert",
"between",
"old",
"and",
"new",
"TSCube",
"formats",
"."
] | python | train |
AmesCornish/buttersink | buttersink/SSHStore.py | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/SSHStore.py#L258-L267 | def send(self, diff):
""" Return Context Manager for a file-like (stream) object to send a diff. """
if Store.skipDryRun(logger, self.dryrun)("send %s", diff):
return None
(diffTo, diffFrom) = self.toArg.diff(diff)
self._client.send(diffTo, diffFrom)
progress = Disp... | [
"def",
"send",
"(",
"self",
",",
"diff",
")",
":",
"if",
"Store",
".",
"skipDryRun",
"(",
"logger",
",",
"self",
".",
"dryrun",
")",
"(",
"\"send %s\"",
",",
"diff",
")",
":",
"return",
"None",
"(",
"diffTo",
",",
"diffFrom",
")",
"=",
"self",
".",... | Return Context Manager for a file-like (stream) object to send a diff. | [
"Return",
"Context",
"Manager",
"for",
"a",
"file",
"-",
"like",
"(",
"stream",
")",
"object",
"to",
"send",
"a",
"diff",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/image_transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/image_transformer.py#L828-L838 | def imagetransformer_sep_channels_8l_8h():
"""separate rgb embeddings."""
hparams = imagetransformer_base()
hparams.num_heads = 8
hparams.batch_size = 1
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 512
hparams.filter_size = 512
hparams.num_hidden_layers = 8... | [
"def",
"imagetransformer_sep_channels_8l_8h",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_base",
"(",
")",
"hparams",
".",
"num_heads",
"=",
"8",
"hparams",
".",
"batch_size",
"=",
"1",
"hparams",
".",
"attention_key_channels",
"=",
"hparams",
".",
"attention... | separate rgb embeddings. | [
"separate",
"rgb",
"embeddings",
"."
] | python | train |
wbond/oscrypto | oscrypto/_openssl/util.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_openssl/util.py#L123-L243 | def pkcs12_kdf(hash_algorithm, password, salt, iterations, key_length, id_):
"""
KDF from RFC7292 appendix B.2 - https://tools.ietf.org/html/rfc7292#page-19
:param hash_algorithm:
The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512"
:param passwor... | [
"def",
"pkcs12_kdf",
"(",
"hash_algorithm",
",",
"password",
",",
"salt",
",",
"iterations",
",",
"key_length",
",",
"id_",
")",
":",
"if",
"not",
"isinstance",
"(",
"password",
",",
"byte_cls",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"... | KDF from RFC7292 appendix B.2 - https://tools.ietf.org/html/rfc7292#page-19
:param hash_algorithm:
The string name of the hash algorithm to use: "md5", "sha1", "sha224", "sha256", "sha384", "sha512"
:param password:
A byte string of the password to use an input to the KDF
:param salt:
... | [
"KDF",
"from",
"RFC7292",
"appendix",
"B",
".",
"2",
"-",
"https",
":",
"//",
"tools",
".",
"ietf",
".",
"org",
"/",
"html",
"/",
"rfc7292#page",
"-",
"19"
] | python | valid |
chaoss/grimoirelab-elk | grimoire_elk/enriched/sortinghat_gelk.py | https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/sortinghat_gelk.py#L157-L166 | def unique_identities(cls, sh_db):
"""List the unique identities available in SortingHat.
:param sh_db: SortingHat database
"""
try:
for unique_identity in api.unique_identities(sh_db):
yield unique_identity
except Exception as e:
logger.d... | [
"def",
"unique_identities",
"(",
"cls",
",",
"sh_db",
")",
":",
"try",
":",
"for",
"unique_identity",
"in",
"api",
".",
"unique_identities",
"(",
"sh_db",
")",
":",
"yield",
"unique_identity",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"debug",
... | List the unique identities available in SortingHat.
:param sh_db: SortingHat database | [
"List",
"the",
"unique",
"identities",
"available",
"in",
"SortingHat",
"."
] | python | train |
ultrabug/py3status | py3status/modules/timer.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/timer.py#L70-L81 | def _time_up(self):
"""
Called when the timer expires
"""
self.running = False
self.color = self.py3.COLOR_BAD
self.time_left = 0
self.done = True
if self.sound:
self.py3.play_sound(self.sound)
self.alarm = True
self.timer() | [
"def",
"_time_up",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"False",
"self",
".",
"color",
"=",
"self",
".",
"py3",
".",
"COLOR_BAD",
"self",
".",
"time_left",
"=",
"0",
"self",
".",
"done",
"=",
"True",
"if",
"self",
".",
"sound",
":",
... | Called when the timer expires | [
"Called",
"when",
"the",
"timer",
"expires"
] | python | train |
kislyuk/aegea | aegea/packages/github3/repos/repo.py | https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/repos/repo.py#L1312-L1361 | def iter_issues(self,
milestone=None,
state=None,
assignee=None,
mentioned=None,
labels=None,
sort=None,
direction=None,
since=None,
number=... | [
"def",
"iter_issues",
"(",
"self",
",",
"milestone",
"=",
"None",
",",
"state",
"=",
"None",
",",
"assignee",
"=",
"None",
",",
"mentioned",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"since... | Iterate over issues on this repo based upon parameters passed.
.. versionchanged:: 0.9.0
The ``state`` parameter now accepts 'all' in addition to 'open'
and 'closed'.
:param int milestone: (optional), 'none', or '*'
:param str state: (optional), accepted values: ('all'... | [
"Iterate",
"over",
"issues",
"on",
"this",
"repo",
"based",
"upon",
"parameters",
"passed",
"."
] | python | train |
BerkeleyAutomation/perception | perception/primesense_sensor.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/primesense_sensor.py#L360-L369 | def _read_depth_images(self, num_images):
""" Reads depth images from the device """
depth_images = self._ros_read_images(self._depth_image_buffer, num_images, self.staleness_limit)
for i in range(0, num_images):
depth_images[i] = depth_images[i] * MM_TO_METERS # convert to meters
... | [
"def",
"_read_depth_images",
"(",
"self",
",",
"num_images",
")",
":",
"depth_images",
"=",
"self",
".",
"_ros_read_images",
"(",
"self",
".",
"_depth_image_buffer",
",",
"num_images",
",",
"self",
".",
"staleness_limit",
")",
"for",
"i",
"in",
"range",
"(",
... | Reads depth images from the device | [
"Reads",
"depth",
"images",
"from",
"the",
"device"
] | python | train |
lawsie/guizero | guizero/Window.py | https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Window.py#L39-L45 | def show(self, wait = False):
"""Show the window."""
self.tk.deiconify()
self._visible = True
self._modal = wait
if self._modal:
self.tk.grab_set() | [
"def",
"show",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"self",
".",
"tk",
".",
"deiconify",
"(",
")",
"self",
".",
"_visible",
"=",
"True",
"self",
".",
"_modal",
"=",
"wait",
"if",
"self",
".",
"_modal",
":",
"self",
".",
"tk",
".",
... | Show the window. | [
"Show",
"the",
"window",
"."
] | python | train |
vimalloc/flask-jwt-extended | examples/database_blacklist/blacklist_helpers.py | https://github.com/vimalloc/flask-jwt-extended/blob/569d3b89eb5d2586d0cff4581a346229c623cefc/examples/database_blacklist/blacklist_helpers.py#L91-L103 | def prune_database():
"""
Delete tokens that have expired from the database.
How (and if) you call this is entirely up you. You could expose it to an
endpoint that only administrators could call, you could run it as a cron,
set it up with flask cli, etc.
"""
now = datetime.now()
expired... | [
"def",
"prune_database",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"expired",
"=",
"TokenBlacklist",
".",
"query",
".",
"filter",
"(",
"TokenBlacklist",
".",
"expires",
"<",
"now",
")",
".",
"all",
"(",
")",
"for",
"token",
"in",
"... | Delete tokens that have expired from the database.
How (and if) you call this is entirely up you. You could expose it to an
endpoint that only administrators could call, you could run it as a cron,
set it up with flask cli, etc. | [
"Delete",
"tokens",
"that",
"have",
"expired",
"from",
"the",
"database",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xlockbutton.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlockbutton.py#L53-L60 | def setChecked(self, state):
"""
Sets whether or not this button is in its locked state.
:param state | <bool>
"""
super(XLockButton, self).setChecked(state)
self.updateState() | [
"def",
"setChecked",
"(",
"self",
",",
"state",
")",
":",
"super",
"(",
"XLockButton",
",",
"self",
")",
".",
"setChecked",
"(",
"state",
")",
"self",
".",
"updateState",
"(",
")"
] | Sets whether or not this button is in its locked state.
:param state | <bool> | [
"Sets",
"whether",
"or",
"not",
"this",
"button",
"is",
"in",
"its",
"locked",
"state",
".",
":",
"param",
"state",
"|",
"<bool",
">"
] | python | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L333-L359 | def _handle_join_dags(self, request):
""" The handler for the join_dags request.
If dag names are given in the payload only return a valid Response if none of
the dags specified by the names are running anymore. If no dag names are given,
wait for all dags except one, which by design is... | [
"def",
"_handle_join_dags",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"payload",
"[",
"'names'",
"]",
"is",
"None",
":",
"send_response",
"=",
"len",
"(",
"self",
".",
"_dags_running",
")",
"<=",
"1",
"else",
":",
"send_response",
"=",... | The handler for the join_dags request.
If dag names are given in the payload only return a valid Response if none of
the dags specified by the names are running anymore. If no dag names are given,
wait for all dags except one, which by design is the one that issued the request,
to be fi... | [
"The",
"handler",
"for",
"the",
"join_dags",
"request",
"."
] | python | train |
django-treebeard/django-treebeard | treebeard/numconv.py | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/numconv.py#L56-L81 | def int2str(self, num):
"""Converts an integer into a string.
:param num: A numeric value to be converted to another base as a
string.
:rtype: string
:raise TypeError: when *num* isn't an integer
:raise ValueError: when *num* isn't positive
"""
... | [
"def",
"int2str",
"(",
"self",
",",
"num",
")",
":",
"if",
"int",
"(",
"num",
")",
"!=",
"num",
":",
"raise",
"TypeError",
"(",
"'number must be an integer'",
")",
"if",
"num",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'number must be positive'",
")",
... | Converts an integer into a string.
:param num: A numeric value to be converted to another base as a
string.
:rtype: string
:raise TypeError: when *num* isn't an integer
:raise ValueError: when *num* isn't positive | [
"Converts",
"an",
"integer",
"into",
"a",
"string",
"."
] | python | train |
saltstack/salt | salt/modules/yumpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L139-L153 | def _yum():
'''
Determine package manager name (yum or dnf),
depending on the system version.
'''
contextkey = 'yum_bin'
if contextkey not in __context__:
if ('fedora' in __grains__['os'].lower()
and int(__grains__['osrelease']) >= 22):
__context__[contextkey] = 'd... | [
"def",
"_yum",
"(",
")",
":",
"contextkey",
"=",
"'yum_bin'",
"if",
"contextkey",
"not",
"in",
"__context__",
":",
"if",
"(",
"'fedora'",
"in",
"__grains__",
"[",
"'os'",
"]",
".",
"lower",
"(",
")",
"and",
"int",
"(",
"__grains__",
"[",
"'osrelease'",
... | Determine package manager name (yum or dnf),
depending on the system version. | [
"Determine",
"package",
"manager",
"name",
"(",
"yum",
"or",
"dnf",
")",
"depending",
"on",
"the",
"system",
"version",
"."
] | python | train |
astropy/photutils | photutils/segmentation/core.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/core.py#L611-L680 | def reassign_label(self, label, new_label, relabel=False):
"""
Reassign a label number to a new number.
If ``new_label`` is already present in the segmentation image,
then it will be combined with the input ``label`` number.
Parameters
----------
labels : int
... | [
"def",
"reassign_label",
"(",
"self",
",",
"label",
",",
"new_label",
",",
"relabel",
"=",
"False",
")",
":",
"self",
".",
"reassign_labels",
"(",
"label",
",",
"new_label",
",",
"relabel",
"=",
"relabel",
")"
] | Reassign a label number to a new number.
If ``new_label`` is already present in the segmentation image,
then it will be combined with the input ``label`` number.
Parameters
----------
labels : int
The label number to reassign.
new_label : int
Th... | [
"Reassign",
"a",
"label",
"number",
"to",
"a",
"new",
"number",
"."
] | python | train |
ic-labs/django-icekit | icekit/admin_tools/polymorphic.py | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin_tools/polymorphic.py#L72-L85 | def get_child_models(self):
"""
Get child models from registered plugins. Fallback to the child model
admin and its base model if no plugins are registered.
"""
child_models = []
for plugin in self.child_model_plugin_class.get_plugins():
child_models.append((p... | [
"def",
"get_child_models",
"(",
"self",
")",
":",
"child_models",
"=",
"[",
"]",
"for",
"plugin",
"in",
"self",
".",
"child_model_plugin_class",
".",
"get_plugins",
"(",
")",
":",
"child_models",
".",
"append",
"(",
"(",
"plugin",
".",
"model",
",",
"plugi... | Get child models from registered plugins. Fallback to the child model
admin and its base model if no plugins are registered. | [
"Get",
"child",
"models",
"from",
"registered",
"plugins",
".",
"Fallback",
"to",
"the",
"child",
"model",
"admin",
"and",
"its",
"base",
"model",
"if",
"no",
"plugins",
"are",
"registered",
"."
] | python | train |
EricCrosson/stump | stump/stump.py | https://github.com/EricCrosson/stump/blob/eb4d9f0dbe2642f86d47ca1b5f51fb7801bb09ab/stump/stump.py#L350-L368 | def warning_ret(f, *args, **kwargs):
"""Automatically log progress on function entry and exit. Logging
value: warning. The function's return value will be included in the logs.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted ... | [
"def",
"warning_ret",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'log'",
":",
"logging",
".",
"WARNING",
"}",
")",
"kwargs",
".",
"update",
"(",
"{",
"'print_return'",
":",
"True",
"}",
")",
... | Automatically log progress on function entry and exit. Logging
value: warning. The function's return value will be included in the logs.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated ... | [
"Automatically",
"log",
"progress",
"on",
"function",
"entry",
"and",
"exit",
".",
"Logging",
"value",
":",
"warning",
".",
"The",
"function",
"s",
"return",
"value",
"will",
"be",
"included",
"in",
"the",
"logs",
"."
] | python | train |
deginner/mq-client | mq_client.py | https://github.com/deginner/mq-client/blob/a20ab50ea18870c01e8d142b049233c355858872/mq_client.py#L253-L261 | def on_exchange_declareok(self, unused_frame):
"""
Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
command.
:param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame
"""
self._logger.debug('Exchange declared')
self.setup_queue(s... | [
"def",
"on_exchange_declareok",
"(",
"self",
",",
"unused_frame",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Exchange declared'",
")",
"self",
".",
"setup_queue",
"(",
"self",
".",
"_queue",
")"
] | Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
command.
:param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame | [
"Invoked",
"by",
"pika",
"when",
"RabbitMQ",
"has",
"finished",
"the",
"Exchange",
".",
"Declare",
"RPC",
"command",
"."
] | python | train |
asphalt-framework/asphalt | asphalt/core/context.py | https://github.com/asphalt-framework/asphalt/blob/4114b3ac9743cbd9facb374a3f53e19d3afef22d/asphalt/core/context.py#L205-L223 | def add_teardown_callback(self, callback: Callable, pass_exception: bool = False) -> None:
"""
Add a callback to be called when this context closes.
This is intended for cleanup of resources, and the list of callbacks is processed in the
reverse order in which they were added, so the la... | [
"def",
"add_teardown_callback",
"(",
"self",
",",
"callback",
":",
"Callable",
",",
"pass_exception",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"assert",
"check_argument_types",
"(",
")",
"self",
".",
"_check_closed",
"(",
")",
"self",
".",
"_teardo... | Add a callback to be called when this context closes.
This is intended for cleanup of resources, and the list of callbacks is processed in the
reverse order in which they were added, so the last added callback will be called first.
The callback may return an awaitable. If it does, the awaitabl... | [
"Add",
"a",
"callback",
"to",
"be",
"called",
"when",
"this",
"context",
"closes",
"."
] | python | train |
metagriffin/fso | fso/filesystemoverlay.py | https://github.com/metagriffin/fso/blob/c37701fbfdfde359a2044eb9420abe569a7b35e4/fso/filesystemoverlay.py#L331-L335 | def _lstat(self, path):
'''IMPORTANT: expects `path`'s parent to already be deref()'erenced.'''
if path not in self.entries:
return OverlayStat(*self.originals['os:lstat'](path)[:10], st_overlay=0)
return self.entries[path].stat | [
"def",
"_lstat",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"entries",
":",
"return",
"OverlayStat",
"(",
"*",
"self",
".",
"originals",
"[",
"'os:lstat'",
"]",
"(",
"path",
")",
"[",
":",
"10",
"]",
",",
"st_overla... | IMPORTANT: expects `path`'s parent to already be deref()'erenced. | [
"IMPORTANT",
":",
"expects",
"path",
"s",
"parent",
"to",
"already",
"be",
"deref",
"()",
"erenced",
"."
] | python | valid |
note35/sinon | sinon/lib/stub.py | https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/stub.py#L332-L343 | def throws(self, exception=Exception):
"""
Customizes the stub function to raise an exception. If conditions like withArgs or onCall
were specified, then the return value will only be returned when the conditions are met.
Args: exception (by default=Exception, it could be any customized... | [
"def",
"throws",
"(",
"self",
",",
"exception",
"=",
"Exception",
")",
":",
"def",
"exception_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"exception",
"self",
".",
"_copy",
".",
"_append_condition",
"(",
"self",
",",
"excepti... | Customizes the stub function to raise an exception. If conditions like withArgs or onCall
were specified, then the return value will only be returned when the conditions are met.
Args: exception (by default=Exception, it could be any customized exception)
Return: a SinonStub object (able to be ... | [
"Customizes",
"the",
"stub",
"function",
"to",
"raise",
"an",
"exception",
".",
"If",
"conditions",
"like",
"withArgs",
"or",
"onCall",
"were",
"specified",
"then",
"the",
"return",
"value",
"will",
"only",
"be",
"returned",
"when",
"the",
"conditions",
"are",... | python | train |
annoviko/pyclustering | pyclustering/cluster/__init__.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/__init__.py#L135-L157 | def append_cluster(self, cluster, data = None, marker = '.', markersize = None, color = None):
"""!
@brief Appends cluster for visualization.
@param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself.
@param[in] data (list): If defines... | [
"def",
"append_cluster",
"(",
"self",
",",
"cluster",
",",
"data",
"=",
"None",
",",
"marker",
"=",
"'.'",
",",
"markersize",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"if",
"len",
"(",
"cluster",
")",
"==",
"0",
":",
"raise",
"ValueError",
... | !
@brief Appends cluster for visualization.
@param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself.
@param[in] data (list): If defines that each element of cluster is considered as a index of object from the data.
@param[in] marker ... | [
"!"
] | python | valid |
twilio/twilio-python | twilio/rest/pricing/v2/voice/number.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/pricing/v2/voice/number.py#L123-L144 | def fetch(self, origination_number=values.unset):
"""
Fetch a NumberInstance
:param unicode origination_number: The origination number for which to fetch pricing information
:returns: Fetched NumberInstance
:rtype: twilio.rest.pricing.v2.voice.number.NumberInstance
"""
... | [
"def",
"fetch",
"(",
"self",
",",
"origination_number",
"=",
"values",
".",
"unset",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"'OriginationNumber'",
":",
"origination_number",
",",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"f... | Fetch a NumberInstance
:param unicode origination_number: The origination number for which to fetch pricing information
:returns: Fetched NumberInstance
:rtype: twilio.rest.pricing.v2.voice.number.NumberInstance | [
"Fetch",
"a",
"NumberInstance"
] | python | train |
Alignak-monitoring/alignak | alignak/scheduler.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L437-L465 | def run_external_commands(self, cmds):
"""Run external commands Arbiter/Receiver sent
:param cmds: commands to run
:type cmds: list
:return: None
"""
if not self.external_commands_manager:
return
try:
_t0 = time.time()
logger.... | [
"def",
"run_external_commands",
"(",
"self",
",",
"cmds",
")",
":",
"if",
"not",
"self",
".",
"external_commands_manager",
":",
"return",
"try",
":",
"_t0",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Scheduler '%s' got %d commands\"",
... | Run external commands Arbiter/Receiver sent
:param cmds: commands to run
:type cmds: list
:return: None | [
"Run",
"external",
"commands",
"Arbiter",
"/",
"Receiver",
"sent"
] | python | train |
Esri/ArcREST | src/arcrest/ags/_networkservice.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_networkservice.py#L538-L799 | def solve(self,stops,
method="POST",
barriers=None,
polylineBarriers=None,
polygonBarriers=None,
travelMode=None,
attributeParameterValues=None,
returnDirections=None,
returnRoutes=True,
returnS... | [
"def",
"solve",
"(",
"self",
",",
"stops",
",",
"method",
"=",
"\"POST\"",
",",
"barriers",
"=",
"None",
",",
"polylineBarriers",
"=",
"None",
",",
"polygonBarriers",
"=",
"None",
",",
"travelMode",
"=",
"None",
",",
"attributeParameterValues",
"=",
"None",
... | The solve operation is performed on a network layer resource.
The solve operation is supported on a network layer whose layerType
is esriNAServerRouteLayer. You can provide arguments to the solve
route operation as query parameters.
Inputs:
stops - The set of stops loaded as ... | [
"The",
"solve",
"operation",
"is",
"performed",
"on",
"a",
"network",
"layer",
"resource",
".",
"The",
"solve",
"operation",
"is",
"supported",
"on",
"a",
"network",
"layer",
"whose",
"layerType",
"is",
"esriNAServerRouteLayer",
".",
"You",
"can",
"provide",
"... | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/object_detector/object_detector.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/object_detector/object_detector.py#L920-L932 | def _canonize_input(self, dataset):
"""
Takes input and returns tuple of the input in canonical form (SFrame)
along with an unpack callback function that can be applied to
prediction results to "undo" the canonization.
"""
unpack = lambda x: x
if isinstance(datase... | [
"def",
"_canonize_input",
"(",
"self",
",",
"dataset",
")",
":",
"unpack",
"=",
"lambda",
"x",
":",
"x",
"if",
"isinstance",
"(",
"dataset",
",",
"_tc",
".",
"SArray",
")",
":",
"dataset",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"self",
".",
"feature",
... | Takes input and returns tuple of the input in canonical form (SFrame)
along with an unpack callback function that can be applied to
prediction results to "undo" the canonization. | [
"Takes",
"input",
"and",
"returns",
"tuple",
"of",
"the",
"input",
"in",
"canonical",
"form",
"(",
"SFrame",
")",
"along",
"with",
"an",
"unpack",
"callback",
"function",
"that",
"can",
"be",
"applied",
"to",
"prediction",
"results",
"to",
"undo",
"the",
"... | python | train |
guaix-ucm/numina | numina/core/tagexpr.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/tagexpr.py#L137-L146 | def fill_placeholders(self, tags):
"""Substitute Placeholder nodes by its value in tags"""
def change_p_node_tags(node, children):
if isinstance(node, Placeholder):
value = ConstExpr(tags[node.name])
return value
else:
return node.c... | [
"def",
"fill_placeholders",
"(",
"self",
",",
"tags",
")",
":",
"def",
"change_p_node_tags",
"(",
"node",
",",
"children",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"Placeholder",
")",
":",
"value",
"=",
"ConstExpr",
"(",
"tags",
"[",
"node",
".",
... | Substitute Placeholder nodes by its value in tags | [
"Substitute",
"Placeholder",
"nodes",
"by",
"its",
"value",
"in",
"tags"
] | python | train |
pypa/pipenv | pipenv/vendor/distlib/database.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/database.py#L1127-L1136 | def add_missing(self, distribution, requirement):
"""
Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str... | [
"def",
"add_missing",
"(",
"self",
",",
"distribution",
",",
"requirement",
")",
":",
"logger",
".",
"debug",
"(",
"'%s missing %r'",
",",
"distribution",
",",
"requirement",
")",
"self",
".",
"missing",
".",
"setdefault",
"(",
"distribution",
",",
"[",
"]",... | Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str`` | [
"Add",
"a",
"missing",
"*",
"requirement",
"*",
"for",
"the",
"given",
"*",
"distribution",
"*",
"."
] | python | train |
drj11/pypng | code/png.py | https://github.com/drj11/pypng/blob/b8220ca9f58e4c5bc1d507e713744fcb8c049225/code/png.py#L1468-L1518 | def _deinterlace(self, raw):
"""
Read raw pixel data, undo filters, deinterlace, and flatten.
Return a single array of values.
"""
# Values per row (of the target image)
vpr = self.width * self.planes
# Values per image
vpi = vpr * self.height
# ... | [
"def",
"_deinterlace",
"(",
"self",
",",
"raw",
")",
":",
"# Values per row (of the target image)",
"vpr",
"=",
"self",
".",
"width",
"*",
"self",
".",
"planes",
"# Values per image",
"vpi",
"=",
"vpr",
"*",
"self",
".",
"height",
"# Interleaving writes to the out... | Read raw pixel data, undo filters, deinterlace, and flatten.
Return a single array of values. | [
"Read",
"raw",
"pixel",
"data",
"undo",
"filters",
"deinterlace",
"and",
"flatten",
".",
"Return",
"a",
"single",
"array",
"of",
"values",
"."
] | python | train |
Datary/scrapbag | scrapbag/csvs.py | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/csvs.py#L88-L111 | def get_row_headers(rows, row_headers_count_value=0, column_headers_count=1):
"""
Return row headers.
Assume that by default it has one column header.
Assume that there is only one father row header.
"""
# TODO: REFACTOR ALGORITHM NEEDED
partial_headers = []
if row_headers_count_value:
... | [
"def",
"get_row_headers",
"(",
"rows",
",",
"row_headers_count_value",
"=",
"0",
",",
"column_headers_count",
"=",
"1",
")",
":",
"# TODO: REFACTOR ALGORITHM NEEDED",
"partial_headers",
"=",
"[",
"]",
"if",
"row_headers_count_value",
":",
"# Take partial data",
"for",
... | Return row headers.
Assume that by default it has one column header.
Assume that there is only one father row header. | [
"Return",
"row",
"headers",
".",
"Assume",
"that",
"by",
"default",
"it",
"has",
"one",
"column",
"header",
".",
"Assume",
"that",
"there",
"is",
"only",
"one",
"father",
"row",
"header",
"."
] | python | train |
mbedmicro/pyOCD | pyocd/coresight/ap.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/ap.py#L136-L144 | def _locked(func):
"""! Decorator to automatically lock an AccessPort method."""
def _locking(self, *args, **kwargs):
try:
self.lock()
return func(self, *args, **kwargs)
finally:
self.unlock()
return _locking | [
"def",
"_locked",
"(",
"func",
")",
":",
"def",
"_locking",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"lock",
"(",
")",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | ! Decorator to automatically lock an AccessPort method. | [
"!",
"Decorator",
"to",
"automatically",
"lock",
"an",
"AccessPort",
"method",
"."
] | python | train |
Dallinger/Dallinger | dallinger/deployment.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/deployment.py#L464-L473 | def notify(self, message):
"""Callback function which checks lines of output, tries to match
against regex defined in subclass's "dispatch" dict, and passes through
to a handler on match.
"""
for regex, handler in self.dispatch.items():
match = re.search(regex, messag... | [
"def",
"notify",
"(",
"self",
",",
"message",
")",
":",
"for",
"regex",
",",
"handler",
"in",
"self",
".",
"dispatch",
".",
"items",
"(",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"message",
")",
"if",
"match",
":",
"handler",... | Callback function which checks lines of output, tries to match
against regex defined in subclass's "dispatch" dict, and passes through
to a handler on match. | [
"Callback",
"function",
"which",
"checks",
"lines",
"of",
"output",
"tries",
"to",
"match",
"against",
"regex",
"defined",
"in",
"subclass",
"s",
"dispatch",
"dict",
"and",
"passes",
"through",
"to",
"a",
"handler",
"on",
"match",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py#L353-L362 | def hosting_devices_removed(self, context, payload):
"""Deal with hosting device removed RPC message."""
try:
if payload['hosting_data']:
if payload['hosting_data'].keys():
self.process_services(removed_devices_info=payload)
except KeyError as e:
... | [
"def",
"hosting_devices_removed",
"(",
"self",
",",
"context",
",",
"payload",
")",
":",
"try",
":",
"if",
"payload",
"[",
"'hosting_data'",
"]",
":",
"if",
"payload",
"[",
"'hosting_data'",
"]",
".",
"keys",
"(",
")",
":",
"self",
".",
"process_services",... | Deal with hosting device removed RPC message. | [
"Deal",
"with",
"hosting",
"device",
"removed",
"RPC",
"message",
"."
] | python | train |
opencast/pyCA | pyca/config.py | https://github.com/opencast/pyCA/blob/c89b168d4780d157e1b3f7676628c1b131956a88/pyca/config.py#L75-L97 | def update_configuration(cfgfile=None):
'''Update configuration from file.
:param cfgfile: Configuration file to load.
'''
configobj.DEFAULT_INTERPOLATION = 'template'
cfgfile = configuration_file(cfgfile)
cfg = configobj.ConfigObj(cfgfile, configspec=cfgspec, encoding='utf-8')
validator = ... | [
"def",
"update_configuration",
"(",
"cfgfile",
"=",
"None",
")",
":",
"configobj",
".",
"DEFAULT_INTERPOLATION",
"=",
"'template'",
"cfgfile",
"=",
"configuration_file",
"(",
"cfgfile",
")",
"cfg",
"=",
"configobj",
".",
"ConfigObj",
"(",
"cfgfile",
",",
"config... | Update configuration from file.
:param cfgfile: Configuration file to load. | [
"Update",
"configuration",
"from",
"file",
"."
] | python | test |
manrajgrover/halo | halo/halo.py | https://github.com/manrajgrover/halo/blob/0ac5149dea965b27b09f0776df9095ebf013fb4d/halo/halo.py#L347-L357 | def render(self):
"""Runs the render until thread flag is set.
Returns
-------
self
"""
while not self._stop_spinner.is_set():
self._render_frame()
time.sleep(0.001 * self._interval)
return self | [
"def",
"render",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_stop_spinner",
".",
"is_set",
"(",
")",
":",
"self",
".",
"_render_frame",
"(",
")",
"time",
".",
"sleep",
"(",
"0.001",
"*",
"self",
".",
"_interval",
")",
"return",
"self"
] | Runs the render until thread flag is set.
Returns
-------
self | [
"Runs",
"the",
"render",
"until",
"thread",
"flag",
"is",
"set",
".",
"Returns",
"-------",
"self"
] | python | train |
edx/edx-val | edxval/utils.py | https://github.com/edx/edx-val/blob/30df48061e77641edb5272895b7c7f7f25eb7aa7/edxval/utils.py#L175-L186 | def get_video_transcript_storage():
"""
Return the configured django storage backend for video transcripts.
"""
if hasattr(settings, 'VIDEO_TRANSCRIPTS_SETTINGS'):
return get_storage_class(
settings.VIDEO_TRANSCRIPTS_SETTINGS.get('STORAGE_CLASS'),
)(**settings.VIDEO_TRANSCRIP... | [
"def",
"get_video_transcript_storage",
"(",
")",
":",
"if",
"hasattr",
"(",
"settings",
",",
"'VIDEO_TRANSCRIPTS_SETTINGS'",
")",
":",
"return",
"get_storage_class",
"(",
"settings",
".",
"VIDEO_TRANSCRIPTS_SETTINGS",
".",
"get",
"(",
"'STORAGE_CLASS'",
")",
",",
")... | Return the configured django storage backend for video transcripts. | [
"Return",
"the",
"configured",
"django",
"storage",
"backend",
"for",
"video",
"transcripts",
"."
] | python | train |
fozzle/python-brotherprint | brotherprint/brotherprint.py | https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L669-L708 | def select_font(self, font):
'''Select font type
Choices are:
<Bit map fonts>
'brougham'
'lettergothicbold'
'brusselsbit'
'helsinkibit'
'sandiego'
<Outline fonts>
'lettergothic'
'brusselsoutline'
'helsinkioutline'
... | [
"def",
"select_font",
"(",
"self",
",",
"font",
")",
":",
"fonts",
"=",
"{",
"'brougham'",
":",
"0",
",",
"'lettergothicbold'",
":",
"1",
",",
"'brusselsbit'",
":",
"2",
",",
"'helsinkibit'",
":",
"3",
",",
"'sandiego'",
":",
"4",
",",
"'lettergothic'",
... | Select font type
Choices are:
<Bit map fonts>
'brougham'
'lettergothicbold'
'brusselsbit'
'helsinkibit'
'sandiego'
<Outline fonts>
'lettergothic'
'brusselsoutline'
'helsinkioutline'
Args:
font:... | [
"Select",
"font",
"type",
"Choices",
"are",
":",
"<Bit",
"map",
"fonts",
">",
"brougham",
"lettergothicbold",
"brusselsbit",
"helsinkibit",
"sandiego",
"<Outline",
"fonts",
">",
"lettergothic",
"brusselsoutline",
"helsinkioutline",
"Args",
":",
"font",
":",
"font",
... | python | train |
ambitioninc/python-logentries-api | logentries_api/logs.py | https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/logs.py#L15-L40 | def list(self):
"""
Get all log sets
:return: Returns a dictionary where the key is the hostname or log set,
and the value is a list of the log keys
:rtype: dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException... | [
"def",
"list",
"(",
"self",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base_url",
")",
"if",
"not",
"response",
".",
"ok",
":",
"raise",
"ServerException",
"(",
"'{}: {}'",
".",
"format",
"(",
"response",
".",
"status_code",
... | Get all log sets
:return: Returns a dictionary where the key is the hostname or log set,
and the value is a list of the log keys
:rtype: dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException>`
if there is an error ... | [
"Get",
"all",
"log",
"sets"
] | python | test |
SatelliteQE/nailgun | nailgun/entities.py | https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L7246-L7271 | def read(self, entity=None, attrs=None, ignore=None, params=None):
"""Provide a default value for ``entity``.
By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a
default value for ``entity`` like so::
entity = type(self)()
However, :class:`SyncPlan` requi... | [
"def",
"read",
"(",
"self",
",",
"entity",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"# read() should not change the state of the object it's called on, but",
"# super() alters the attributes of any entity ... | Provide a default value for ``entity``.
By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a
default value for ``entity`` like so::
entity = type(self)()
However, :class:`SyncPlan` requires that an ``organization`` be
provided, so this technique will not w... | [
"Provide",
"a",
"default",
"value",
"for",
"entity",
"."
] | python | train |
tanghaibao/jcvi | jcvi/apps/base.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/base.py#L868-L886 | def mkdir(dirname, overwrite=False):
"""
Wraps around os.mkdir(), but checks for existence first.
"""
if op.isdir(dirname):
if overwrite:
shutil.rmtree(dirname)
os.mkdir(dirname)
logging.debug("Overwrite folder `{0}`.".format(dirname))
else:
... | [
"def",
"mkdir",
"(",
"dirname",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"op",
".",
"isdir",
"(",
"dirname",
")",
":",
"if",
"overwrite",
":",
"shutil",
".",
"rmtree",
"(",
"dirname",
")",
"os",
".",
"mkdir",
"(",
"dirname",
")",
"logging",
... | Wraps around os.mkdir(), but checks for existence first. | [
"Wraps",
"around",
"os",
".",
"mkdir",
"()",
"but",
"checks",
"for",
"existence",
"first",
"."
] | python | train |
nsavch/python-xonotic-db | xon_db/cli.py | https://github.com/nsavch/python-xonotic-db/blob/339fe4c2c74880fd66712ae32789d7e9ae3e8f02/xon_db/cli.py#L18-L25 | def dump(file_name, pattern):
"""
Print all keys and values where key matches PATTERN. Default pattern is * (all keys)
"""
db = XonoticDB.load_path(file_name)
items = sorted(db.filter(pattern), key=lambda x: natural_sort_key(x[0]))
for k, v in items:
click.echo('%s: %s' % (k, v)) | [
"def",
"dump",
"(",
"file_name",
",",
"pattern",
")",
":",
"db",
"=",
"XonoticDB",
".",
"load_path",
"(",
"file_name",
")",
"items",
"=",
"sorted",
"(",
"db",
".",
"filter",
"(",
"pattern",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"natural_sort_key",
... | Print all keys and values where key matches PATTERN. Default pattern is * (all keys) | [
"Print",
"all",
"keys",
"and",
"values",
"where",
"key",
"matches",
"PATTERN",
".",
"Default",
"pattern",
"is",
"*",
"(",
"all",
"keys",
")"
] | python | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/visualise.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/visualise.py#L52-L272 | def _plot_future(time, data, legend=None, title=None, y_axis_label=None, hor_lines=None,
hor_lines_leg=None, vert_lines=None, vert_lines_leg=None,
apply_opensignals_style=True, show_plot=True, warn_print=False, **kwargs):
"""
Plotting function intended for an easy representation ... | [
"def",
"_plot_future",
"(",
"time",
",",
"data",
",",
"legend",
"=",
"None",
",",
"title",
"=",
"None",
",",
"y_axis_label",
"=",
"None",
",",
"hor_lines",
"=",
"None",
",",
"hor_lines_leg",
"=",
"None",
",",
"vert_lines",
"=",
"None",
",",
"vert_lines_l... | Plotting function intended for an easy representation of OpenSignals acquired data.
----------
Parameters
----------
time : list or list of lists
List that contains the time axis samples or a list of lists, when it is intended to present
data in a gridplot format. When the input is a li... | [
"Plotting",
"function",
"intended",
"for",
"an",
"easy",
"representation",
"of",
"OpenSignals",
"acquired",
"data",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.