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 |
|---|---|---|---|---|---|---|---|---|
ejeschke/ginga | ginga/rv/Control.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1464-L1501 | def delete_channel(self, chname):
"""Delete a given channel from viewer."""
name = chname.lower()
if len(self.channel_names) < 1:
self.logger.error('Delete channel={0} failed. '
'No channels left.'.format(chname))
return
with self.l... | [
"def",
"delete_channel",
"(",
"self",
",",
"chname",
")",
":",
"name",
"=",
"chname",
".",
"lower",
"(",
")",
"if",
"len",
"(",
"self",
".",
"channel_names",
")",
"<",
"1",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Delete channel={0} failed. '",
... | Delete a given channel from viewer. | [
"Delete",
"a",
"given",
"channel",
"from",
"viewer",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L538-L554 | def Var(self, mu=None):
"""Computes the variance of a PMF.
Args:
mu: the point around which the variance is computed;
if omitted, computes the mean
Returns:
float variance
"""
if mu is None:
mu = self.Mean()
var = 0.0... | [
"def",
"Var",
"(",
"self",
",",
"mu",
"=",
"None",
")",
":",
"if",
"mu",
"is",
"None",
":",
"mu",
"=",
"self",
".",
"Mean",
"(",
")",
"var",
"=",
"0.0",
"for",
"x",
",",
"p",
"in",
"self",
".",
"d",
".",
"iteritems",
"(",
")",
":",
"var",
... | Computes the variance of a PMF.
Args:
mu: the point around which the variance is computed;
if omitted, computes the mean
Returns:
float variance | [
"Computes",
"the",
"variance",
"of",
"a",
"PMF",
"."
] | python | train |
collectiveacuity/labPack | labpack/platforms/docker.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L118-L156 | def _validate_virtualbox(self):
'''
a method to validate that virtualbox is running on Win 7/8 machines
:return: boolean indicating whether virtualbox is running
'''
# validate operating system
if self.localhost.os.sysname != 'Windows':
return Fal... | [
"def",
"_validate_virtualbox",
"(",
"self",
")",
":",
"# validate operating system\r",
"if",
"self",
".",
"localhost",
".",
"os",
".",
"sysname",
"!=",
"'Windows'",
":",
"return",
"False",
"win_release",
"=",
"float",
"(",
"self",
".",
"localhost",
".",
"os",
... | a method to validate that virtualbox is running on Win 7/8 machines
:return: boolean indicating whether virtualbox is running | [
"a",
"method",
"to",
"validate",
"that",
"virtualbox",
"is",
"running",
"on",
"Win",
"7",
"/",
"8",
"machines",
":",
"return",
":",
"boolean",
"indicating",
"whether",
"virtualbox",
"is",
"running"
] | python | train |
dmlc/gluon-nlp | scripts/bert/staticbert/static_bert.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L481-L512 | def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None):
# pylint: disable=arguments-differ
# pylint: disable=unused-argument
"""Generate the representation given the inputs.
This is used in training or fine-tuning a static (hybridized) BERT model.
... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"inputs",
",",
"token_types",
",",
"valid_length",
"=",
"None",
",",
"masked_positions",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"# pylint: disable=unused-argument",
"outputs",
"=",
"[",
"]",
... | Generate the representation given the inputs.
This is used in training or fine-tuning a static (hybridized) BERT model. | [
"Generate",
"the",
"representation",
"given",
"the",
"inputs",
"."
] | python | train |
nugget/python-insteonplm | insteonplm/states/onOff.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/states/onOff.py#L792-L828 | def _create_set_property_msg(self, prop, cmd, val):
"""Create an extended message to set a property.
Create an extended message with:
cmd1: 0x2e
cmd2: 0x00
flags: Direct Extended
d1: group
d2: cmd
d3: val
d4 - d14: 0x00... | [
"def",
"_create_set_property_msg",
"(",
"self",
",",
"prop",
",",
"cmd",
",",
"val",
")",
":",
"user_data",
"=",
"Userdata",
"(",
"{",
"'d1'",
":",
"self",
".",
"group",
",",
"'d2'",
":",
"cmd",
",",
"'d3'",
":",
"val",
"}",
")",
"msg",
"=",
"Exten... | Create an extended message to set a property.
Create an extended message with:
cmd1: 0x2e
cmd2: 0x00
flags: Direct Extended
d1: group
d2: cmd
d3: val
d4 - d14: 0x00
Parameters:
prop: Property name to update... | [
"Create",
"an",
"extended",
"message",
"to",
"set",
"a",
"property",
"."
] | python | train |
peepall/FancyLogger | FancyLogger/__init__.py | https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/__init__.py#L365-L374 | def info(self, text):
"""
Posts an info message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their ti... | [
"def",
"info",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"queue",
".",
"put",
"(",
"dill",
".",
"dumps",
"(",
"LogMessageCommand",
"(",
"text",
"=",
"text",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
")",
")"
] | Posts an info message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their timestamp will be captured at the right time... | [
"Posts",
"an",
"info",
"message",
"adding",
"a",
"timestamp",
"and",
"logging",
"level",
"to",
"it",
"for",
"both",
"file",
"and",
"console",
"handlers",
".",
"Logger",
"uses",
"a",
"redraw",
"rate",
"because",
"of",
"console",
"flickering",
".",
"That",
"... | python | train |
dhermes/bezier | docs/make_images.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L677-L709 | def curve_specialize(curve, new_curve):
"""Image for :meth`.Curve.specialize` docstring."""
if NO_IMAGES:
return
ax = curve.plot(256)
interval = r"$\left[0, 1\right]$"
line = ax.lines[-1]
line.set_label(interval)
color1 = line.get_color()
new_curve.plot(256, ax=ax)
interval ... | [
"def",
"curve_specialize",
"(",
"curve",
",",
"new_curve",
")",
":",
"if",
"NO_IMAGES",
":",
"return",
"ax",
"=",
"curve",
".",
"plot",
"(",
"256",
")",
"interval",
"=",
"r\"$\\left[0, 1\\right]$\"",
"line",
"=",
"ax",
".",
"lines",
"[",
"-",
"1",
"]",
... | Image for :meth`.Curve.specialize` docstring. | [
"Image",
"for",
":",
"meth",
".",
"Curve",
".",
"specialize",
"docstring",
"."
] | python | train |
linkhub-sdk/popbill.py | popbill/taxinvoiceService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/taxinvoiceService.py#L287-L310 | def cancelSend(self, CorpNum, MgtKeyType, MgtKey, Memo=None, UserID=None):
""" 승인요청 취소
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
Memo : 처리 메모
UserID : 팝빌 회원아이디
... | [
"def",
"cancelSend",
"(",
"self",
",",
"CorpNum",
",",
"MgtKeyType",
",",
"MgtKey",
",",
"Memo",
"=",
"None",
",",
"UserID",
"=",
"None",
")",
":",
"if",
"MgtKeyType",
"not",
"in",
"self",
".",
"__MgtKeyTypes",
":",
"raise",
"PopbillException",
"(",
"-",... | 승인요청 취소
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
Memo : 처리 메모
UserID : 팝빌 회원아이디
return
처리결과. consist of code and message
raise
... | [
"승인요청",
"취소",
"args",
"CorpNum",
":",
"회원",
"사업자",
"번호",
"MgtKeyType",
":",
"관리번호",
"유형",
"one",
"of",
"[",
"SELL",
"BUY",
"TRUSTEE",
"]",
"MgtKey",
":",
"파트너",
"관리번호",
"Memo",
":",
"처리",
"메모",
"UserID",
":",
"팝빌",
"회원아이디",
"return",
"처리결과",
".",
"... | python | train |
zendesk/connect_python_sdk | outbound/__init__.py | https://github.com/zendesk/connect_python_sdk/blob/6d7c1a539dcf23c1b1942e9bf6c9084c929df7e6/outbound/__init__.py#L280-L372 | def track(user_id, event, first_name=None, last_name=None, email=None,
phone_number=None, apns_tokens=None, gcm_tokens=None,
user_attributes=None, properties=None, on_error=None, on_success=None, timestamp=None):
""" For any event you want to track, when a user triggers that event you
would call... | [
"def",
"track",
"(",
"user_id",
",",
"event",
",",
"first_name",
"=",
"None",
",",
"last_name",
"=",
"None",
",",
"email",
"=",
"None",
",",
"phone_number",
"=",
"None",
",",
"apns_tokens",
"=",
"None",
",",
"gcm_tokens",
"=",
"None",
",",
"user_attribut... | For any event you want to track, when a user triggers that event you
would call this function.
You can do an identify and track call simultaneously by including all the
identifiable user information in the track call.
:param str | number user_id: the id you user who triggered the event.
:param st... | [
"For",
"any",
"event",
"you",
"want",
"to",
"track",
"when",
"a",
"user",
"triggers",
"that",
"event",
"you",
"would",
"call",
"this",
"function",
"."
] | python | train |
Nukesor/pueue | pueue/client/displaying.py | https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/client/displaying.py#L19-L105 | def execute_status(args, root_dir=None):
"""Print the status of the daemon.
This function displays the current status of the daemon as well
as the whole queue and all available information about every entry
in the queue.
`terminaltables` is used to format and display the queue contents.
`colorc... | [
"def",
"execute_status",
"(",
"args",
",",
"root_dir",
"=",
"None",
")",
":",
"status",
"=",
"command_factory",
"(",
"'status'",
")",
"(",
"{",
"}",
",",
"root_dir",
"=",
"root_dir",
")",
"# First rows, showing daemon status",
"if",
"status",
"[",
"'status'",
... | Print the status of the daemon.
This function displays the current status of the daemon as well
as the whole queue and all available information about every entry
in the queue.
`terminaltables` is used to format and display the queue contents.
`colorclass` is used to color format the various items ... | [
"Print",
"the",
"status",
"of",
"the",
"daemon",
"."
] | python | train |
mardix/Juice | juice/plugins/maintenance_page/__init__.py | https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/plugins/maintenance_page/__init__.py#L6-L33 | def view(template=None):
"""
Create the Maintenance view
Must be instantiated
import maintenance_view
MaintenanceView = maintenance_view()
:param template_: The directory containing the view pages
:return:
"""
if not template:
template = "Juice/Plugin/MaintenancePage/index.... | [
"def",
"view",
"(",
"template",
"=",
"None",
")",
":",
"if",
"not",
"template",
":",
"template",
"=",
"\"Juice/Plugin/MaintenancePage/index.html\"",
"class",
"Maintenance",
"(",
"View",
")",
":",
"@",
"classmethod",
"def",
"register",
"(",
"cls",
",",
"app",
... | Create the Maintenance view
Must be instantiated
import maintenance_view
MaintenanceView = maintenance_view()
:param template_: The directory containing the view pages
:return: | [
"Create",
"the",
"Maintenance",
"view",
"Must",
"be",
"instantiated"
] | python | train |
flo-compbio/genometools | genometools/expression/matrix.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L426-L466 | def read_tsv(cls, file_path: str, gene_table: ExpGeneTable = None,
encoding: str = 'UTF-8', sep: str = '\t'):
"""Read expression matrix from a tab-delimited text file.
Parameters
----------
file_path: str
The path of the text file.
gene_table: `ExpGe... | [
"def",
"read_tsv",
"(",
"cls",
",",
"file_path",
":",
"str",
",",
"gene_table",
":",
"ExpGeneTable",
"=",
"None",
",",
"encoding",
":",
"str",
"=",
"'UTF-8'",
",",
"sep",
":",
"str",
"=",
"'\\t'",
")",
":",
"# use pd.read_csv to parse the tsv file into a DataF... | Read expression matrix from a tab-delimited text file.
Parameters
----------
file_path: str
The path of the text file.
gene_table: `ExpGeneTable` object, optional
The set of valid genes. If given, the genes in the text file will
be filtered against th... | [
"Read",
"expression",
"matrix",
"from",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | python | train |
gbiggs/rtsprofile | rtsprofile/targets.py | https://github.com/gbiggs/rtsprofile/blob/fded6eddcb0b25fe9808b1b12336a4413ea00905/rtsprofile/targets.py#L303-L313 | def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a target execution context
into this object.
'''
super(TargetExecutionContext, self).parse_xml_node(node)
if node.hasAttributeNS(RTS_NS, 'id'):
self.id = node.getAttributeNS(RTS_NS, 'id')
... | [
"def",
"parse_xml_node",
"(",
"self",
",",
"node",
")",
":",
"super",
"(",
"TargetExecutionContext",
",",
"self",
")",
".",
"parse_xml_node",
"(",
"node",
")",
"if",
"node",
".",
"hasAttributeNS",
"(",
"RTS_NS",
",",
"'id'",
")",
":",
"self",
".",
"id",
... | Parse an xml.dom Node object representing a target execution context
into this object. | [
"Parse",
"an",
"xml",
".",
"dom",
"Node",
"object",
"representing",
"a",
"target",
"execution",
"context",
"into",
"this",
"object",
"."
] | python | train |
rigetti/quantumflow | quantumflow/channels.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L170-L175 | def join_channels(*channels: Channel) -> Channel:
"""Join two channels acting on different qubits into a single channel
acting on all qubits"""
vectors = [chan.vec for chan in channels]
vec = reduce(outer_product, vectors)
return Channel(vec.tensor, vec.qubits) | [
"def",
"join_channels",
"(",
"*",
"channels",
":",
"Channel",
")",
"->",
"Channel",
":",
"vectors",
"=",
"[",
"chan",
".",
"vec",
"for",
"chan",
"in",
"channels",
"]",
"vec",
"=",
"reduce",
"(",
"outer_product",
",",
"vectors",
")",
"return",
"Channel",
... | Join two channels acting on different qubits into a single channel
acting on all qubits | [
"Join",
"two",
"channels",
"acting",
"on",
"different",
"qubits",
"into",
"a",
"single",
"channel",
"acting",
"on",
"all",
"qubits"
] | python | train |
Zimbra-Community/python-zimbra | pythonzimbra/communication.py | https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/communication.py#L54-L84 | def gen_request(self, request_type="json", token=None, set_batch=False,
batch_onerror=None):
""" Convenience method to quickly generate a token
:param request_type: Type of request (defaults to json)
:param token: Authentication token
:param set_batch: Also set this... | [
"def",
"gen_request",
"(",
"self",
",",
"request_type",
"=",
"\"json\"",
",",
"token",
"=",
"None",
",",
"set_batch",
"=",
"False",
",",
"batch_onerror",
"=",
"None",
")",
":",
"if",
"request_type",
"==",
"\"json\"",
":",
"local_request",
"=",
"RequestJson",... | Convenience method to quickly generate a token
:param request_type: Type of request (defaults to json)
:param token: Authentication token
:param set_batch: Also set this request to batch mode?
:param batch_onerror: Onerror-parameter for batch mode
:return: The request | [
"Convenience",
"method",
"to",
"quickly",
"generate",
"a",
"token"
] | python | train |
lanpa/tensorboardX | examples/demo_caffe2.py | https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L130-L133 | def AddAccuracy(model, softmax, label):
"""Adds an accuracy op to the model"""
accuracy = brew.accuracy(model, [softmax, label], "accuracy")
return accuracy | [
"def",
"AddAccuracy",
"(",
"model",
",",
"softmax",
",",
"label",
")",
":",
"accuracy",
"=",
"brew",
".",
"accuracy",
"(",
"model",
",",
"[",
"softmax",
",",
"label",
"]",
",",
"\"accuracy\"",
")",
"return",
"accuracy"
] | Adds an accuracy op to the model | [
"Adds",
"an",
"accuracy",
"op",
"to",
"the",
"model"
] | python | train |
sdss/sdss_access | python/sdss_access/sync/rsync.py | https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/rsync.py#L28-L34 | def remote(self, username=None, password=None, inquire=None):
""" Configures remote access """
self.set_netloc(sdss=True) # simplifies things to have a single sdss machine in .netrc
self.set_auth(username=username, password=password, inquire=inquire)
self.set_netloc(dtn=not self.public... | [
"def",
"remote",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"inquire",
"=",
"None",
")",
":",
"self",
".",
"set_netloc",
"(",
"sdss",
"=",
"True",
")",
"# simplifies things to have a single sdss machine in .netrc",
"self",
".... | Configures remote access | [
"Configures",
"remote",
"access"
] | python | train |
googledatalab/pydatalab | datalab/bigquery/_sampling.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_sampling.py#L74-L88 | def sampling_query(sql, fields=None, count=5, sampling=None):
"""Returns a sampling query for the SQL object.
Args:
sql: the SQL object to sample
fields: an optional list of field names to retrieve.
count: an optional count of rows to retrieve which is used if a specific
sampling is... | [
"def",
"sampling_query",
"(",
"sql",
",",
"fields",
"=",
"None",
",",
"count",
"=",
"5",
",",
"sampling",
"=",
"None",
")",
":",
"if",
"sampling",
"is",
"None",
":",
"sampling",
"=",
"Sampling",
".",
"default",
"(",
"count",
"=",
"count",
",",
"field... | Returns a sampling query for the SQL object.
Args:
sql: the SQL object to sample
fields: an optional list of field names to retrieve.
count: an optional count of rows to retrieve which is used if a specific
sampling is not specified.
sampling: an optional sampling strategy to appl... | [
"Returns",
"a",
"sampling",
"query",
"for",
"the",
"SQL",
"object",
"."
] | python | train |
adrn/gala | gala/potential/potential/util.py | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/util.py#L18-L162 | def from_equation(expr, vars, pars, name=None, hessian=False):
r"""
Create a potential class from an expression for the potential.
.. note::
This utility requires having `Sympy <http://www.sympy.org/>`_ installed.
.. warning::
These potentials are *not* pickle-able and cannot be writ... | [
"def",
"from_equation",
"(",
"expr",
",",
"vars",
",",
"pars",
",",
"name",
"=",
"None",
",",
"hessian",
"=",
"False",
")",
":",
"try",
":",
"import",
"sympy",
"from",
"sympy",
".",
"utilities",
".",
"lambdify",
"import",
"lambdify",
"except",
"ImportErr... | r"""
Create a potential class from an expression for the potential.
.. note::
This utility requires having `Sympy <http://www.sympy.org/>`_ installed.
.. warning::
These potentials are *not* pickle-able and cannot be written
out to YAML files (using `~gala.potential.PotentialBase... | [
"r",
"Create",
"a",
"potential",
"class",
"from",
"an",
"expression",
"for",
"the",
"potential",
"."
] | python | train |
PyPSA/PyPSA | examples/scigrid-de/add_load_gen_trafos_to_scigrid.py | https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/examples/scigrid-de/add_load_gen_trafos_to_scigrid.py#L392-L406 | def generate_dummy_graph(network):
"""Generate a dummy graph to feed to the FIAS libraries.
It adds the "pos" attribute and removes the 380 kV duplicate
buses when the buses have been split, so that all load and generation
is attached to the 220kV bus."""
graph = pypsa.descriptors.OrderedGraph(... | [
"def",
"generate_dummy_graph",
"(",
"network",
")",
":",
"graph",
"=",
"pypsa",
".",
"descriptors",
".",
"OrderedGraph",
"(",
")",
"graph",
".",
"add_nodes_from",
"(",
"[",
"bus",
"for",
"bus",
"in",
"network",
".",
"buses",
".",
"index",
"if",
"bus",
"n... | Generate a dummy graph to feed to the FIAS libraries.
It adds the "pos" attribute and removes the 380 kV duplicate
buses when the buses have been split, so that all load and generation
is attached to the 220kV bus. | [
"Generate",
"a",
"dummy",
"graph",
"to",
"feed",
"to",
"the",
"FIAS",
"libraries",
".",
"It",
"adds",
"the",
"pos",
"attribute",
"and",
"removes",
"the",
"380",
"kV",
"duplicate",
"buses",
"when",
"the",
"buses",
"have",
"been",
"split",
"so",
"that",
"a... | python | train |
miquelo/resort | packages/resort/component/glassfish.py | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/component/glassfish.py#L315-L334 | def connector_connection_pool(self, name, res_adapter_name, conn_def_name,
props):
"""
Domain connector connection pool.
:param str name:
Resource name.
:param str res_adapter_name:
Resource adapter name.
:param str conn_def_name:
Resource connection definition name.
:param dict pro... | [
"def",
"connector_connection_pool",
"(",
"self",
",",
"name",
",",
"res_adapter_name",
",",
"conn_def_name",
",",
"props",
")",
":",
"return",
"ConnectorConnectionPool",
"(",
"self",
".",
"__endpoint",
",",
"name",
",",
"res_adapter_name",
",",
"conn_def_name",
",... | Domain connector connection pool.
:param str name:
Resource name.
:param str res_adapter_name:
Resource adapter name.
:param str conn_def_name:
Resource connection definition name.
:param dict props:
Connection pool properties.
:rtype:
ConnectorConnectionPool | [
"Domain",
"connector",
"connection",
"pool",
".",
":",
"param",
"str",
"name",
":",
"Resource",
"name",
".",
":",
"param",
"str",
"res_adapter_name",
":",
"Resource",
"adapter",
"name",
".",
":",
"param",
"str",
"conn_def_name",
":",
"Resource",
"connection",
... | python | train |
ajyoon/blur | blur/soft.py | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/soft.py#L102-L117 | def with_random_weights(cls, options):
"""
Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object... | [
"def",
"with_random_weights",
"(",
"cls",
",",
"options",
")",
":",
"return",
"cls",
"(",
"[",
"(",
"value",
",",
"random",
".",
"randint",
"(",
"1",
",",
"len",
"(",
"options",
")",
")",
")",
"for",
"value",
"in",
"options",
"]",
")"
] | Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object
can return with the ``get()`` method.
... | [
"Initialize",
"from",
"a",
"list",
"of",
"options",
"with",
"random",
"weights",
"."
] | python | train |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1810-L1826 | def umount(self, source):
"""
Unmount partion
:param source: Full partition path like /dev/sda1
"""
args = {
'source': source,
}
self._umount_chk.check(args)
response = self._client.raw('disk.umount', args)
result = response.get()
... | [
"def",
"umount",
"(",
"self",
",",
"source",
")",
":",
"args",
"=",
"{",
"'source'",
":",
"source",
",",
"}",
"self",
".",
"_umount_chk",
".",
"check",
"(",
"args",
")",
"response",
"=",
"self",
".",
"_client",
".",
"raw",
"(",
"'disk.umount'",
",",
... | Unmount partion
:param source: Full partition path like /dev/sda1 | [
"Unmount",
"partion",
":",
"param",
"source",
":",
"Full",
"partition",
"path",
"like",
"/",
"dev",
"/",
"sda1"
] | python | train |
apache/incubator-mxnet | example/rnn/large_word_lm/model.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/model.py#L130-L147 | def generate_samples(label, num_splits, sampler):
""" Split labels into `num_splits` and
generate candidates based on log-uniform distribution.
"""
def listify(x):
return x if isinstance(x, list) else [x]
label_splits = listify(label.split(num_splits, axis=0))
prob_samples = []
p... | [
"def",
"generate_samples",
"(",
"label",
",",
"num_splits",
",",
"sampler",
")",
":",
"def",
"listify",
"(",
"x",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
"else",
"[",
"x",
"]",
"label_splits",
"=",
"listify",
"(",
"la... | Split labels into `num_splits` and
generate candidates based on log-uniform distribution. | [
"Split",
"labels",
"into",
"num_splits",
"and",
"generate",
"candidates",
"based",
"on",
"log",
"-",
"uniform",
"distribution",
"."
] | python | train |
linuxsoftware/ls.joyous | ls/joyous/models/calendar.py | https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L438-L441 | def _getEventsOnDay(self, request, day):
"""Return all the events in this site for a given day."""
home = request.site.root_page
return getAllEventsByDay(request, day, day, home=home)[0] | [
"def",
"_getEventsOnDay",
"(",
"self",
",",
"request",
",",
"day",
")",
":",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"return",
"getAllEventsByDay",
"(",
"request",
",",
"day",
",",
"day",
",",
"home",
"=",
"home",
")",
"[",
"0",
"]"
] | Return all the events in this site for a given day. | [
"Return",
"all",
"the",
"events",
"in",
"this",
"site",
"for",
"a",
"given",
"day",
"."
] | python | train |
rocky/python-xdis | xdis/util.py | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/util.py#L69-L83 | def pretty_flags(flags):
"""Return pretty representation of code flags."""
names = []
result = "0x%08x" % flags
for i in range(32):
flag = 1 << i
if flags & flag:
names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
flags ^= flag
if not flags:
... | [
"def",
"pretty_flags",
"(",
"flags",
")",
":",
"names",
"=",
"[",
"]",
"result",
"=",
"\"0x%08x\"",
"%",
"flags",
"for",
"i",
"in",
"range",
"(",
"32",
")",
":",
"flag",
"=",
"1",
"<<",
"i",
"if",
"flags",
"&",
"flag",
":",
"names",
".",
"append"... | Return pretty representation of code flags. | [
"Return",
"pretty",
"representation",
"of",
"code",
"flags",
"."
] | python | train |
radjkarl/imgProcessor | imgProcessor/camera/LensDistortion.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/LensDistortion.py#L258-L275 | def writeToFile(self, filename, saveOpts=False):
'''
write the distortion coeffs to file
saveOpts --> Whether so save calibration options (and not just results)
'''
try:
if not filename.endswith('.%s' % self.ftype):
filename += '.%s' % self.ftyp... | [
"def",
"writeToFile",
"(",
"self",
",",
"filename",
",",
"saveOpts",
"=",
"False",
")",
":",
"try",
":",
"if",
"not",
"filename",
".",
"endswith",
"(",
"'.%s'",
"%",
"self",
".",
"ftype",
")",
":",
"filename",
"+=",
"'.%s'",
"%",
"self",
".",
"ftype"... | write the distortion coeffs to file
saveOpts --> Whether so save calibration options (and not just results) | [
"write",
"the",
"distortion",
"coeffs",
"to",
"file",
"saveOpts",
"--",
">",
"Whether",
"so",
"save",
"calibration",
"options",
"(",
"and",
"not",
"just",
"results",
")"
] | python | train |
zeromake/aiko | aiko/application.py | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/application.py#L253-L285 | def _handle(self, request: Request, response: Response) -> TypeGenerator[Any, None, None]:
"""
request 解析后的回调,调用中间件,并处理 headers, body 发送。
"""
# request.start_time = datetime.now().timestamp()
# 创建一个新的会话上下文
ctx = self._context(
cast(asyncio.AbstractEventLoop, s... | [
"def",
"_handle",
"(",
"self",
",",
"request",
":",
"Request",
",",
"response",
":",
"Response",
")",
"->",
"TypeGenerator",
"[",
"Any",
",",
"None",
",",
"None",
"]",
":",
"# request.start_time = datetime.now().timestamp()",
"# 创建一个新的会话上下文",
"ctx",
"=",
"self",... | request 解析后的回调,调用中间件,并处理 headers, body 发送。 | [
"request",
"解析后的回调,调用中间件,并处理",
"headers",
"body",
"发送。"
] | python | train |
saltstack/salt | salt/proxy/bluecoat_sslv.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/bluecoat_sslv.py#L201-L213 | def logout(session, cookies, csrf_token):
'''
Closes the session with the device.
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "logout",
"params": []
}
session.post(DETAILS['url'],
data=json.dumps(payload),
... | [
"def",
"logout",
"(",
"session",
",",
"cookies",
",",
"csrf_token",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"logout\"",
",",
"\"params\"",
":",
"[",
"]",
"}",
"session",
".",
... | Closes the session with the device. | [
"Closes",
"the",
"session",
"with",
"the",
"device",
"."
] | python | train |
jim-easterbrook/pywws | src/pywws/weatherstation.py | https://github.com/jim-easterbrook/pywws/blob/4e4d74cee5a3ac5bf42286feaa251cd2ffcaf02c/src/pywws/weatherstation.py#L665-L670 | def dec_ptr(self, ptr):
"""Get previous circular buffer data pointer."""
result = ptr - self.reading_len[self.ws_type]
if result < self.data_start:
result = 0x10000 - self.reading_len[self.ws_type]
return result | [
"def",
"dec_ptr",
"(",
"self",
",",
"ptr",
")",
":",
"result",
"=",
"ptr",
"-",
"self",
".",
"reading_len",
"[",
"self",
".",
"ws_type",
"]",
"if",
"result",
"<",
"self",
".",
"data_start",
":",
"result",
"=",
"0x10000",
"-",
"self",
".",
"reading_le... | Get previous circular buffer data pointer. | [
"Get",
"previous",
"circular",
"buffer",
"data",
"pointer",
"."
] | python | train |
ilgarm/pyzimbra | pyzimbra/z/admin.py | https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/admin.py#L66-L77 | def get_info(self, account, params={}):
"""
Gets account info.
@param account: account to get info for
@param params: parameters to retrieve
@return: AccountInfo
"""
res = self.invoke(zconstant.NS_ZIMBRA_ADMIN_URL,
sconstant.GetInfoReques... | [
"def",
"get_info",
"(",
"self",
",",
"account",
",",
"params",
"=",
"{",
"}",
")",
":",
"res",
"=",
"self",
".",
"invoke",
"(",
"zconstant",
".",
"NS_ZIMBRA_ADMIN_URL",
",",
"sconstant",
".",
"GetInfoRequest",
",",
"params",
")",
"return",
"res"
] | Gets account info.
@param account: account to get info for
@param params: parameters to retrieve
@return: AccountInfo | [
"Gets",
"account",
"info",
"."
] | python | train |
ungarj/mapchete | mapchete/formats/default/tile_directory.py | https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/tile_directory.py#L288-L330 | def read(
self,
validity_check=False,
indexes=None,
resampling=None,
dst_nodata=None,
gdal_opts=None,
**kwargs
):
"""
Read reprojected & resampled input data.
Parameters
----------
validity_check : bool
vect... | [
"def",
"read",
"(",
"self",
",",
"validity_check",
"=",
"False",
",",
"indexes",
"=",
"None",
",",
"resampling",
"=",
"None",
",",
"dst_nodata",
"=",
"None",
",",
"gdal_opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_r... | Read reprojected & resampled input data.
Parameters
----------
validity_check : bool
vector file: also run checks if reprojected geometry is valid,
otherwise throw RuntimeError (default: True)
indexes : list or int
raster file: a list of band numbers... | [
"Read",
"reprojected",
"&",
"resampled",
"input",
"data",
"."
] | python | valid |
buzzfeed/caliendo | caliendo/patch.py | https://github.com/buzzfeed/caliendo/blob/1628a10f7782ad67c0422b5cbc9bf4979ac40abc/caliendo/patch.py#L231-L282 | def patch(import_path, rvalue=UNDEFINED, side_effect=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, ctxt=UNDEFINED, subsequent_rvalue=UNDEFINED):
"""
Patches an attribute of a module referenced on import_path with a decorated
version that will use the caliendo cache if rvalue is None. Otherwise it will
... | [
"def",
"patch",
"(",
"import_path",
",",
"rvalue",
"=",
"UNDEFINED",
",",
"side_effect",
"=",
"UNDEFINED",
",",
"ignore",
"=",
"UNDEFINED",
",",
"callback",
"=",
"UNDEFINED",
",",
"ctxt",
"=",
"UNDEFINED",
",",
"subsequent_rvalue",
"=",
"UNDEFINED",
")",
":"... | Patches an attribute of a module referenced on import_path with a decorated
version that will use the caliendo cache if rvalue is None. Otherwise it will
patch the attribute of the module to return rvalue when called.
This class provides a context in which to use the patched module. After the
decorated... | [
"Patches",
"an",
"attribute",
"of",
"a",
"module",
"referenced",
"on",
"import_path",
"with",
"a",
"decorated",
"version",
"that",
"will",
"use",
"the",
"caliendo",
"cache",
"if",
"rvalue",
"is",
"None",
".",
"Otherwise",
"it",
"will",
"patch",
"the",
"attri... | python | train |
alphagov/gapy | gapy/client.py | https://github.com/alphagov/gapy/blob/5e8cc058c54d6034fa0f5177d5a6d3d2e71fa5ea/gapy/client.py#L62-L89 | def from_secrets_file(client_secrets, storage=None, flags=None,
storage_path=None, api_version="v3", readonly=False,
http_client=None, ga_hook=None):
"""Create a client for a web or installed application.
Create a client with a client secrets file.
Args:
... | [
"def",
"from_secrets_file",
"(",
"client_secrets",
",",
"storage",
"=",
"None",
",",
"flags",
"=",
"None",
",",
"storage_path",
"=",
"None",
",",
"api_version",
"=",
"\"v3\"",
",",
"readonly",
"=",
"False",
",",
"http_client",
"=",
"None",
",",
"ga_hook",
... | Create a client for a web or installed application.
Create a client with a client secrets file.
Args:
client_secrets: str, path to the client secrets file (downloadable from
Google API Console)
storage: oauth2client.client.Storage, a Storage implementation to store
... | [
"Create",
"a",
"client",
"for",
"a",
"web",
"or",
"installed",
"application",
"."
] | python | train |
pybel/pybel | src/pybel/struct/graph.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L728-L731 | def iter_equivalent_nodes(self, node: BaseEntity) -> Iterable[BaseEntity]:
"""Iterate over nodes that are equivalent to the given node, including the original."""
yield node
yield from self._equivalent_node_iterator_helper(node, {node}) | [
"def",
"iter_equivalent_nodes",
"(",
"self",
",",
"node",
":",
"BaseEntity",
")",
"->",
"Iterable",
"[",
"BaseEntity",
"]",
":",
"yield",
"node",
"yield",
"from",
"self",
".",
"_equivalent_node_iterator_helper",
"(",
"node",
",",
"{",
"node",
"}",
")"
] | Iterate over nodes that are equivalent to the given node, including the original. | [
"Iterate",
"over",
"nodes",
"that",
"are",
"equivalent",
"to",
"the",
"given",
"node",
"including",
"the",
"original",
"."
] | python | train |
woolfson-group/isambard | isambard/tools/file_parsing.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/tools/file_parsing.py#L300-L340 | def parse_PISCES_output(pisces_output, path=False):
""" Takes the output list of a PISCES cull and returns in a usable dictionary.
Notes
-----
Designed for outputs of protein sequence redundancy culls conducted using the PISCES server.
http://dunbrack.fccc.edu/PISCES.php
G. Wang and R. L. Dunbr... | [
"def",
"parse_PISCES_output",
"(",
"pisces_output",
",",
"path",
"=",
"False",
")",
":",
"pisces_dict",
"=",
"{",
"}",
"if",
"path",
":",
"pisces_path",
"=",
"Path",
"(",
"pisces_output",
")",
"pisces_content",
"=",
"pisces_path",
".",
"read_text",
"(",
")",... | Takes the output list of a PISCES cull and returns in a usable dictionary.
Notes
-----
Designed for outputs of protein sequence redundancy culls conducted using the PISCES server.
http://dunbrack.fccc.edu/PISCES.php
G. Wang and R. L. Dunbrack, Jr. PISCES: a protein sequence culling server. Bioinfor... | [
"Takes",
"the",
"output",
"list",
"of",
"a",
"PISCES",
"cull",
"and",
"returns",
"in",
"a",
"usable",
"dictionary",
"."
] | python | train |
samastur/pyimagediet | pyimagediet/process.py | https://github.com/samastur/pyimagediet/blob/480c6e171577df36e166590b031bc8891b3c9e7b/pyimagediet/process.py#L58-L101 | def parse_configuration(config):
'''
Parse and fix configuration:
- processed file should end up being same as input
- pipelines should contain CLI commands to run
- add missing sections
:param config: raw configuration object
:type config: dict
:return: configuration ready ... | [
"def",
"parse_configuration",
"(",
"config",
")",
":",
"new_config",
"=",
"copy",
".",
"deepcopy",
"(",
"config",
")",
"required_parts",
"=",
"(",
"'commands'",
",",
"'parameters'",
",",
"'pipelines'",
")",
"for",
"part",
"in",
"required_parts",
":",
"new_conf... | Parse and fix configuration:
- processed file should end up being same as input
- pipelines should contain CLI commands to run
- add missing sections
:param config: raw configuration object
:type config: dict
:return: configuration ready for `diet()`
:rtype: dict | [
"Parse",
"and",
"fix",
"configuration",
":",
"-",
"processed",
"file",
"should",
"end",
"up",
"being",
"same",
"as",
"input",
"-",
"pipelines",
"should",
"contain",
"CLI",
"commands",
"to",
"run",
"-",
"add",
"missing",
"sections"
] | python | train |
pandas-dev/pandas | pandas/core/arrays/timedeltas.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/timedeltas.py#L392-L402 | def _add_datetime_arraylike(self, other):
"""
Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray.
"""
if isinstance(other, np.ndarray):
# At this point we have already checked that dtype is datetime64
from pandas.core.arrays import DatetimeArray
... | [
"def",
"_add_datetime_arraylike",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"np",
".",
"ndarray",
")",
":",
"# At this point we have already checked that dtype is datetime64",
"from",
"pandas",
".",
"core",
".",
"arrays",
"import",
... | Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray. | [
"Add",
"DatetimeArray",
"/",
"Index",
"or",
"ndarray",
"[",
"datetime64",
"]",
"to",
"TimedeltaArray",
"."
] | python | train |
jxtech/wechatpy | wechatpy/client/api/invoice.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/invoice.py#L251-L271 | def set_pay_mch(self, mchid, s_pappid):
"""
关联商户号与开票平台,设置支付后开票
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1496561731_2Z55U
:param mchid: 微信支付商户号
:param s_pappid: 开票平台在微信的标识号,商户需要找开票平台提供
"""
return self._post(
'setbizattr',
params={
... | [
"def",
"set_pay_mch",
"(",
"self",
",",
"mchid",
",",
"s_pappid",
")",
":",
"return",
"self",
".",
"_post",
"(",
"'setbizattr'",
",",
"params",
"=",
"{",
"'action'",
":",
"'set_pay_mch'",
",",
"}",
",",
"data",
"=",
"{",
"'paymch_info'",
":",
"{",
"'mc... | 关联商户号与开票平台,设置支付后开票
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1496561731_2Z55U
:param mchid: 微信支付商户号
:param s_pappid: 开票平台在微信的标识号,商户需要找开票平台提供 | [
"关联商户号与开票平台,设置支付后开票",
"详情请参考",
"https",
":",
"//",
"mp",
".",
"weixin",
".",
"qq",
".",
"com",
"/",
"wiki?id",
"=",
"mp1496561731_2Z55U"
] | python | train |
AndresMWeber/Nomenclate | nomenclate/core/configurator.py | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L176-L190 | def _get_path_entry_from_list(self, query_path):
""" Returns the config entry at query path
:param query_path: list(str), config header path to follow for entry
:return: (list, str, dict, OrderedDict), config entry requested
:raises: exceptions.ResourceNotFoundError
"""
... | [
"def",
"_get_path_entry_from_list",
"(",
"self",
",",
"query_path",
")",
":",
"cur_data",
"=",
"self",
".",
"config_file_contents",
"try",
":",
"for",
"child",
"in",
"query_path",
":",
"cur_data",
"=",
"cur_data",
"[",
"child",
"]",
"return",
"cur_data",
"exce... | Returns the config entry at query path
:param query_path: list(str), config header path to follow for entry
:return: (list, str, dict, OrderedDict), config entry requested
:raises: exceptions.ResourceNotFoundError | [
"Returns",
"the",
"config",
"entry",
"at",
"query",
"path"
] | python | train |
insightindustry/validator-collection | validator_collection/checkers.py | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L152-L194 | def are_dicts_equivalent(*args, **kwargs):
"""Indicate if :ref:`dicts <python:dict>` passed to this function have identical
keys and values.
:param args: One or more values, passed as positional arguments.
:returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not.
:rtype: :cl... | [
"def",
"are_dicts_equivalent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"not",
"args",
":",
"return",
"False",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"return",
"True",
"if",
"not",
"... | Indicate if :ref:`dicts <python:dict>` passed to this function have identical
keys and values.
:param args: One or more values, passed as positional arguments.
:returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError:... | [
"Indicate",
"if",
":",
"ref",
":",
"dicts",
"<python",
":",
"dict",
">",
"passed",
"to",
"this",
"function",
"have",
"identical",
"keys",
"and",
"values",
"."
] | python | train |
sorgerlab/indra | indra/preassembler/grounding_mapper.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L499-L559 | def agent_texts_with_grounding(stmts):
"""Return agent text groundings in a list of statements with their counts
Parameters
----------
stmts: list of :py:class:`indra.statements.Statement`
Returns
-------
list of tuple
List of tuples of the form
(text: str, ((name_space: st... | [
"def",
"agent_texts_with_grounding",
"(",
"stmts",
")",
":",
"allag",
"=",
"all_agents",
"(",
"stmts",
")",
"# Convert PFAM-DEF lists into tuples so that they are hashable and can",
"# be tabulated with a Counter",
"for",
"ag",
"in",
"allag",
":",
"pfam_def",
"=",
"ag",
"... | Return agent text groundings in a list of statements with their counts
Parameters
----------
stmts: list of :py:class:`indra.statements.Statement`
Returns
-------
list of tuple
List of tuples of the form
(text: str, ((name_space: str, ID: str, count: int)...),
total_cou... | [
"Return",
"agent",
"text",
"groundings",
"in",
"a",
"list",
"of",
"statements",
"with",
"their",
"counts"
] | python | train |
dhondta/tinyscript | tinyscript/helpers/utils.py | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/utils.py#L57-L97 | def user_input(prompt="", choices=None, default=None, choices_str="",
required=False):
"""
Python2/3-compatible input method handling choices and default value.
:param prompt: prompt message
:param choices: list of possible choices or lambda function
:param default: default v... | [
"def",
"user_input",
"(",
"prompt",
"=",
"\"\"",
",",
"choices",
"=",
"None",
",",
"default",
"=",
"None",
",",
"choices_str",
"=",
"\"\"",
",",
"required",
"=",
"False",
")",
":",
"if",
"type",
"(",
"choices",
")",
"in",
"[",
"list",
",",
"tuple",
... | Python2/3-compatible input method handling choices and default value.
:param prompt: prompt message
:param choices: list of possible choices or lambda function
:param default: default value
:param required: make non-null user input mandatory
:return: handled user input | [
"Python2",
"/",
"3",
"-",
"compatible",
"input",
"method",
"handling",
"choices",
"and",
"default",
"value",
".",
":",
"param",
"prompt",
":",
"prompt",
"message",
":",
"param",
"choices",
":",
"list",
"of",
"possible",
"choices",
"or",
"lambda",
"function",... | python | train |
mitodl/pylti | pylti/flask.py | https://github.com/mitodl/pylti/blob/18a608282e0d5bc941beb2eaaeea3b7ad484b399/pylti/flask.py#L159-L213 | def lti(app=None, request='any', error=default_error, role='any',
*lti_args, **lti_kwargs):
"""
LTI decorator
:param: app - Flask App object (optional).
:py:attr:`flask.current_app` is used if no object is passed in.
:param: error - Callback if LTI throws exception (optional).
:... | [
"def",
"lti",
"(",
"app",
"=",
"None",
",",
"request",
"=",
"'any'",
",",
"error",
"=",
"default_error",
",",
"role",
"=",
"'any'",
",",
"*",
"lti_args",
",",
"*",
"*",
"lti_kwargs",
")",
":",
"def",
"_lti",
"(",
"function",
")",
":",
"\"\"\"\n ... | LTI decorator
:param: app - Flask App object (optional).
:py:attr:`flask.current_app` is used if no object is passed in.
:param: error - Callback if LTI throws exception (optional).
:py:attr:`pylti.flask.default_error` is the default.
:param: request - Request type from
:py:attr:`py... | [
"LTI",
"decorator"
] | python | train |
Opentrons/opentrons | api/src/opentrons/deck_calibration/endpoints.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/endpoints.py#L100-L124 | def init_pipette():
"""
Finds pipettes attached to the robot currently and chooses the correct one
to add to the session.
:return: The pipette type and mount chosen for deck calibration
"""
global session
pipette_info = set_current_mount(session.adapter, session)
pipette = pipette_info[... | [
"def",
"init_pipette",
"(",
")",
":",
"global",
"session",
"pipette_info",
"=",
"set_current_mount",
"(",
"session",
".",
"adapter",
",",
"session",
")",
"pipette",
"=",
"pipette_info",
"[",
"'pipette'",
"]",
"res",
"=",
"{",
"}",
"if",
"pipette",
":",
"se... | Finds pipettes attached to the robot currently and chooses the correct one
to add to the session.
:return: The pipette type and mount chosen for deck calibration | [
"Finds",
"pipettes",
"attached",
"to",
"the",
"robot",
"currently",
"and",
"chooses",
"the",
"correct",
"one",
"to",
"add",
"to",
"the",
"session",
"."
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/breakpoint.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L912-L932 | def __set_bp(self, aThread):
"""
Sets this breakpoint in the debug registers.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
if self.__slot is None:
aThread.suspend()
try:
ctx = aThread.get_context(win32.CONTEXT_DEBUG... | [
"def",
"__set_bp",
"(",
"self",
",",
"aThread",
")",
":",
"if",
"self",
".",
"__slot",
"is",
"None",
":",
"aThread",
".",
"suspend",
"(",
")",
"try",
":",
"ctx",
"=",
"aThread",
".",
"get_context",
"(",
"win32",
".",
"CONTEXT_DEBUG_REGISTERS",
")",
"se... | Sets this breakpoint in the debug registers.
@type aThread: L{Thread}
@param aThread: Thread object. | [
"Sets",
"this",
"breakpoint",
"in",
"the",
"debug",
"registers",
"."
] | python | train |
rjw57/starman | starman/kalman.py | https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/kalman.py#L131-L204 | def predict(self, control=None, control_matrix=None,
process_matrix=None, process_covariance=None):
"""
Predict the next *a priori* state mean and covariance given the last
posterior. As a special case the first call to this method will
initialise the posterior and prior ... | [
"def",
"predict",
"(",
"self",
",",
"control",
"=",
"None",
",",
"control_matrix",
"=",
"None",
",",
"process_matrix",
"=",
"None",
",",
"process_covariance",
"=",
"None",
")",
":",
"# Sanitise arguments",
"if",
"process_matrix",
"is",
"None",
":",
"process_ma... | Predict the next *a priori* state mean and covariance given the last
posterior. As a special case the first call to this method will
initialise the posterior and prior estimates from the
*initial_state_estimate* and *initial_covariance* arguments passed when
this object was created. In t... | [
"Predict",
"the",
"next",
"*",
"a",
"priori",
"*",
"state",
"mean",
"and",
"covariance",
"given",
"the",
"last",
"posterior",
".",
"As",
"a",
"special",
"case",
"the",
"first",
"call",
"to",
"this",
"method",
"will",
"initialise",
"the",
"posterior",
"and"... | python | train |
mrjoes/sockjs-tornado | sockjs/tornado/sessioncontainer.py | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/sessioncontainer.py#L82-L91 | def add(self, session):
"""Add session to the container.
`session`
Session object
"""
self._items[session.session_id] = session
if session.expiry is not None:
heappush(self._queue, session) | [
"def",
"add",
"(",
"self",
",",
"session",
")",
":",
"self",
".",
"_items",
"[",
"session",
".",
"session_id",
"]",
"=",
"session",
"if",
"session",
".",
"expiry",
"is",
"not",
"None",
":",
"heappush",
"(",
"self",
".",
"_queue",
",",
"session",
")"
... | Add session to the container.
`session`
Session object | [
"Add",
"session",
"to",
"the",
"container",
"."
] | python | train |
jazzband/django-ddp | dddp/websocket.py | https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/websocket.py#L431-L437 | def recv_method(self, method, params, id_, randomSeed=None):
"""DDP method handler."""
if randomSeed is not None:
this.random_streams.random_seed = randomSeed
this.alea_random = alea.Alea(randomSeed)
self.api.method(method, params, id_)
self.reply('updated', metho... | [
"def",
"recv_method",
"(",
"self",
",",
"method",
",",
"params",
",",
"id_",
",",
"randomSeed",
"=",
"None",
")",
":",
"if",
"randomSeed",
"is",
"not",
"None",
":",
"this",
".",
"random_streams",
".",
"random_seed",
"=",
"randomSeed",
"this",
".",
"alea_... | DDP method handler. | [
"DDP",
"method",
"handler",
"."
] | python | test |
MediaFire/mediafire-python-open-sdk | mediafire/uploader.py | https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L198-L289 | def upload(self, fd, name=None, folder_key=None, filedrop_key=None,
path=None, action_on_duplicate=None):
"""Upload file, returns UploadResult object
fd -- file-like object to upload from, expects exclusive access
name -- file name
folder_key -- folderkey of the target fo... | [
"def",
"upload",
"(",
"self",
",",
"fd",
",",
"name",
"=",
"None",
",",
"folder_key",
"=",
"None",
",",
"filedrop_key",
"=",
"None",
",",
"path",
"=",
"None",
",",
"action_on_duplicate",
"=",
"None",
")",
":",
"# Get file handle content length in the most reli... | Upload file, returns UploadResult object
fd -- file-like object to upload from, expects exclusive access
name -- file name
folder_key -- folderkey of the target folder
path -- path to file relative to folder_key
filedrop_key -- filedrop to use instead of folder_key
actio... | [
"Upload",
"file",
"returns",
"UploadResult",
"object"
] | python | train |
guaix-ucm/numina | numina/array/display/iofunctions.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/iofunctions.py#L7-L67 | def readc(prompt, default=None, valid=None, question_mark=True):
"""Return a single character read from keyboard
Parameters
----------
prompt : str
Prompt string.
default : str
Default value.
valid : str
String providing valid characters. If None, all characters are
... | [
"def",
"readc",
"(",
"prompt",
",",
"default",
"=",
"None",
",",
"valid",
"=",
"None",
",",
"question_mark",
"=",
"True",
")",
":",
"cresult",
"=",
"None",
"# Avoid PyCharm warning",
"# question mark",
"if",
"question_mark",
":",
"cquestion_mark",
"=",
"' ? '"... | Return a single character read from keyboard
Parameters
----------
prompt : str
Prompt string.
default : str
Default value.
valid : str
String providing valid characters. If None, all characters are
valid (default).
question_mark : bool
If True, display q... | [
"Return",
"a",
"single",
"character",
"read",
"from",
"keyboard"
] | python | train |
StyXman/ayrton | ayrton/parser/error.py | https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/error.py#L300-L312 | def get_traceback(self):
"""Calling this marks the PyTraceback as escaped, i.e. it becomes
accessible and inspectable by app-level Python code. For the JIT.
Note that this has no effect if there are already several traceback
frames recorded, because in this case they are already marked ... | [
"def",
"get_traceback",
"(",
"self",
")",
":",
"from",
"pypy",
".",
"interpreter",
".",
"pytraceback",
"import",
"PyTraceback",
"tb",
"=",
"self",
".",
"_application_traceback",
"if",
"tb",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"tb",
",",
"PyTraceba... | Calling this marks the PyTraceback as escaped, i.e. it becomes
accessible and inspectable by app-level Python code. For the JIT.
Note that this has no effect if there are already several traceback
frames recorded, because in this case they are already marked as
escaping by executioncont... | [
"Calling",
"this",
"marks",
"the",
"PyTraceback",
"as",
"escaped",
"i",
".",
"e",
".",
"it",
"becomes",
"accessible",
"and",
"inspectable",
"by",
"app",
"-",
"level",
"Python",
"code",
".",
"For",
"the",
"JIT",
".",
"Note",
"that",
"this",
"has",
"no",
... | python | train |
numberly/appnexus-client | appnexus/client.py | https://github.com/numberly/appnexus-client/blob/d6a813449ab6fd93bfbceaa937a168fa9a78b890/appnexus/client.py#L144-L146 | def get(self, service_name, **kwargs):
"""Retrieve data from AppNexus API"""
return self._send(requests.get, service_name, **kwargs) | [
"def",
"get",
"(",
"self",
",",
"service_name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_send",
"(",
"requests",
".",
"get",
",",
"service_name",
",",
"*",
"*",
"kwargs",
")"
] | Retrieve data from AppNexus API | [
"Retrieve",
"data",
"from",
"AppNexus",
"API"
] | python | train |
mgraffg/EvoDAG | EvoDAG/gp.py | https://github.com/mgraffg/EvoDAG/blob/e11fa1fd1ca9e69cca92696c86661a3dc7b3a1d5/EvoDAG/gp.py#L43-L56 | def _eval(self):
"Evaluates a individual using recursion and self._pos as pointer"
pos = self._pos
self._pos += 1
node = self._ind[pos]
if isinstance(node, Function):
args = [self._eval() for x in range(node.nargs)]
node.eval(args)
for x in arg... | [
"def",
"_eval",
"(",
"self",
")",
":",
"pos",
"=",
"self",
".",
"_pos",
"self",
".",
"_pos",
"+=",
"1",
"node",
"=",
"self",
".",
"_ind",
"[",
"pos",
"]",
"if",
"isinstance",
"(",
"node",
",",
"Function",
")",
":",
"args",
"=",
"[",
"self",
"."... | Evaluates a individual using recursion and self._pos as pointer | [
"Evaluates",
"a",
"individual",
"using",
"recursion",
"and",
"self",
".",
"_pos",
"as",
"pointer"
] | python | train |
djordon/queueing-tool | queueing_tool/network/queue_network.py | https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L667-L741 | def draw(self, update_colors=True, line_kwargs=None,
scatter_kwargs=None, **kwargs):
"""Draws the network. The coloring of the network corresponds
to the number of agents at each queue.
Parameters
----------
update_colors : ``bool`` (optional, default: ``True``).
... | [
"def",
"draw",
"(",
"self",
",",
"update_colors",
"=",
"True",
",",
"line_kwargs",
"=",
"None",
",",
"scatter_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"HAS_MATPLOTLIB",
":",
"raise",
"ImportError",
"(",
"\"matplotlib is necessary... | Draws the network. The coloring of the network corresponds
to the number of agents at each queue.
Parameters
----------
update_colors : ``bool`` (optional, default: ``True``).
Specifies whether all the colors are updated.
line_kwargs : dict (optional, default: None)
... | [
"Draws",
"the",
"network",
".",
"The",
"coloring",
"of",
"the",
"network",
"corresponds",
"to",
"the",
"number",
"of",
"agents",
"at",
"each",
"queue",
"."
] | python | valid |
Qiskit/qiskit-terra | qiskit/extensions/standard/cswap.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/cswap.py#L53-L55 | def cswap(self, ctl, tgt1, tgt2):
"""Apply Fredkin to circuit."""
return self.append(FredkinGate(), [ctl, tgt1, tgt2], []) | [
"def",
"cswap",
"(",
"self",
",",
"ctl",
",",
"tgt1",
",",
"tgt2",
")",
":",
"return",
"self",
".",
"append",
"(",
"FredkinGate",
"(",
")",
",",
"[",
"ctl",
",",
"tgt1",
",",
"tgt2",
"]",
",",
"[",
"]",
")"
] | Apply Fredkin to circuit. | [
"Apply",
"Fredkin",
"to",
"circuit",
"."
] | python | test |
knipknap/exscript | Exscript/protocols/protocol.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L954-L974 | def execute(self, command, consume=True):
"""
Sends the given data to the remote host (with a newline appended)
and waits for a prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that f... | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"consume",
"=",
"True",
")",
":",
"self",
".",
"send",
"(",
"command",
"+",
"'\\r'",
")",
"return",
"self",
".",
"expect_prompt",
"(",
"consume",
")"
] | Sends the given data to the remote host (with a newline appended)
and waits for a prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that fails, a custom prompt may
also be defined using the se... | [
"Sends",
"the",
"given",
"data",
"to",
"the",
"remote",
"host",
"(",
"with",
"a",
"newline",
"appended",
")",
"and",
"waits",
"for",
"a",
"prompt",
"in",
"the",
"response",
".",
"The",
"prompt",
"attempts",
"to",
"use",
"a",
"sane",
"default",
"that",
... | python | train |
ngmarchant/oasis | oasis/experiments.py | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L216-L239 | def calc_confusion_matrix(self, printout = False):
"""
Calculates number of TP, FP, TN, FN
"""
if self.labels is None:
raise DataError("Cannot calculate confusion matrix before data "
"has been read.")
if self.preds is None:
ra... | [
"def",
"calc_confusion_matrix",
"(",
"self",
",",
"printout",
"=",
"False",
")",
":",
"if",
"self",
".",
"labels",
"is",
"None",
":",
"raise",
"DataError",
"(",
"\"Cannot calculate confusion matrix before data \"",
"\"has been read.\"",
")",
"if",
"self",
".",
"pr... | Calculates number of TP, FP, TN, FN | [
"Calculates",
"number",
"of",
"TP",
"FP",
"TN",
"FN"
] | python | train |
trec-kba/streamcorpus-pipeline | streamcorpus_pipeline/_hyperlink_labels.py | https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_hyperlink_labels.py#L254-L295 | def byte_href_anchors(self, chars=False):
'''
simple, regex-based extractor of anchor tags, so we can
compute BYTE offsets for anchor texts and associate them with
their href.
Generates tuple(href_string, first_byte, byte_length, anchor_text)
'''
input_bu... | [
"def",
"byte_href_anchors",
"(",
"self",
",",
"chars",
"=",
"False",
")",
":",
"input_buffer",
"=",
"self",
".",
"clean_html",
"if",
"chars",
":",
"input_buffer",
"=",
"input_buffer",
".",
"decode",
"(",
"'utf8'",
")",
"idx",
"=",
"0",
"## split doc up into ... | simple, regex-based extractor of anchor tags, so we can
compute BYTE offsets for anchor texts and associate them with
their href.
Generates tuple(href_string, first_byte, byte_length, anchor_text) | [
"simple",
"regex",
"-",
"based",
"extractor",
"of",
"anchor",
"tags",
"so",
"we",
"can",
"compute",
"BYTE",
"offsets",
"for",
"anchor",
"texts",
"and",
"associate",
"them",
"with",
"their",
"href",
".",
"Generates",
"tuple",
"(",
"href_string",
"first_byte",
... | python | test |
marrow/cinje | cinje/util.py | https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L475-L511 | def stream(self):
"""The workhorse of cinje: transform input lines and emit output lines.
After constructing an instance with a set of input lines iterate this property to generate the template.
"""
if 'init' not in self.flag:
root = True
self.prepare()
else:
root = False
# Track which lin... | [
"def",
"stream",
"(",
"self",
")",
":",
"if",
"'init'",
"not",
"in",
"self",
".",
"flag",
":",
"root",
"=",
"True",
"self",
".",
"prepare",
"(",
")",
"else",
":",
"root",
"=",
"False",
"# Track which lines were generated in response to which lines of source code... | The workhorse of cinje: transform input lines and emit output lines.
After constructing an instance with a set of input lines iterate this property to generate the template. | [
"The",
"workhorse",
"of",
"cinje",
":",
"transform",
"input",
"lines",
"and",
"emit",
"output",
"lines",
".",
"After",
"constructing",
"an",
"instance",
"with",
"a",
"set",
"of",
"input",
"lines",
"iterate",
"this",
"property",
"to",
"generate",
"the",
"temp... | python | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/crypto/encryption.py | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/encryption.py#L52-L67 | def decrypt_attribute(attribute_name, attribute, decryption_key, algorithm):
# type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.RAW_ATTRIBUTE
"""Decrypt a single DynamoDB attribute.
:param str attribute_name: DynamoDB attribute name
:param dict attribute: Encrypted Dynam... | [
"def",
"decrypt_attribute",
"(",
"attribute_name",
",",
"attribute",
",",
"decryption_key",
",",
"algorithm",
")",
":",
"# type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.RAW_ATTRIBUTE",
"encrypted_attribute",
"=",
"attribute",
"[",
"Tag",
".",
... | Decrypt a single DynamoDB attribute.
:param str attribute_name: DynamoDB attribute name
:param dict attribute: Encrypted DynamoDB attribute
:param DelegatedKey encryption_key: DelegatedKey to use to encrypt the attribute
:param str algorithm: Decryption algorithm descriptor (passed to encryption_key as... | [
"Decrypt",
"a",
"single",
"DynamoDB",
"attribute",
"."
] | python | train |
ltalirz/aiida-gudhi | aiida_gudhi/calculations/rips.py | https://github.com/ltalirz/aiida-gudhi/blob/81ebec782ddff3ab97a3e3242b809fec989fa4b9/aiida_gudhi/calculations/rips.py#L118-L155 | def _prepare_for_submission(self, tempfolder, inputdict):
"""
Create input files.
:param tempfolder: aiida.common.folders.Folder subclass where
the plugin should put all its files.
:param inputdict: dictionary of the input nodes as they would
be r... | [
"def",
"_prepare_for_submission",
"(",
"self",
",",
"tempfolder",
",",
"inputdict",
")",
":",
"parameters",
",",
"code",
",",
"distance_matrix",
",",
"symlink",
"=",
"self",
".",
"_validate_inputs",
"(",
"inputdict",
")",
"# Prepare CalcInfo to be returned to aiida",
... | Create input files.
:param tempfolder: aiida.common.folders.Folder subclass where
the plugin should put all its files.
:param inputdict: dictionary of the input nodes as they would
be returned by get_inputs_dict | [
"Create",
"input",
"files",
"."
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/fileutil.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L154-L159 | def getLTime():
"""Returns a formatted string with the current local time."""
_ltime = _time.localtime(_time.time())
tlm_str = _time.strftime('%H:%M:%S (%d/%m/%Y)', _ltime)
return tlm_str | [
"def",
"getLTime",
"(",
")",
":",
"_ltime",
"=",
"_time",
".",
"localtime",
"(",
"_time",
".",
"time",
"(",
")",
")",
"tlm_str",
"=",
"_time",
".",
"strftime",
"(",
"'%H:%M:%S (%d/%m/%Y)'",
",",
"_ltime",
")",
"return",
"tlm_str"
] | Returns a formatted string with the current local time. | [
"Returns",
"a",
"formatted",
"string",
"with",
"the",
"current",
"local",
"time",
"."
] | python | train |
ladybug-tools/ladybug | ladybug/datacollection.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L129-L139 | def filter_by_hoys(self, hoys):
"""Filter the Data Collection based on an analysis period.
Args:
hoys: A List of hours of the year 0..8759
Return:
A new Data Collection with filtered data
"""
_moys = tuple(int(hour * 60) for hour in hoys)
return s... | [
"def",
"filter_by_hoys",
"(",
"self",
",",
"hoys",
")",
":",
"_moys",
"=",
"tuple",
"(",
"int",
"(",
"hour",
"*",
"60",
")",
"for",
"hour",
"in",
"hoys",
")",
"return",
"self",
".",
"filter_by_moys",
"(",
"_moys",
")"
] | Filter the Data Collection based on an analysis period.
Args:
hoys: A List of hours of the year 0..8759
Return:
A new Data Collection with filtered data | [
"Filter",
"the",
"Data",
"Collection",
"based",
"on",
"an",
"analysis",
"period",
"."
] | python | train |
walkr/nanoservice | benchmarks/bench_pub_sub_auth.py | https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/benchmarks/bench_pub_sub_auth.py#L13-L31 | def start_service(addr, n, authenticator):
""" Start a service """
s = Subscriber(addr, authenticator=authenticator)
def do_something(line):
pass
s.subscribe('test', do_something)
started = time.time()
for _ in range(n):
s.process()
s.socket.close()
duration = time.ti... | [
"def",
"start_service",
"(",
"addr",
",",
"n",
",",
"authenticator",
")",
":",
"s",
"=",
"Subscriber",
"(",
"addr",
",",
"authenticator",
"=",
"authenticator",
")",
"def",
"do_something",
"(",
"line",
")",
":",
"pass",
"s",
".",
"subscribe",
"(",
"'test'... | Start a service | [
"Start",
"a",
"service"
] | python | train |
splunk/splunk-sdk-python | examples/analytics/bottle.py | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1576-L1604 | def path_shift(script_name, path_info, shift=1):
''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:return: The modified paths.
:param script_name: The SCRIPT_NAME path.
:param script_name: The PATH_INFO path.
:param shift: The number of path fragments to shift.... | [
"def",
"path_shift",
"(",
"script_name",
",",
"path_info",
",",
"shift",
"=",
"1",
")",
":",
"if",
"shift",
"==",
"0",
":",
"return",
"script_name",
",",
"path_info",
"pathlist",
"=",
"path_info",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'"... | Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:return: The modified paths.
:param script_name: The SCRIPT_NAME path.
:param script_name: The PATH_INFO path.
:param shift: The number of path fragments to shift. May be negative to
change the shift direction.... | [
"Shift",
"path",
"fragments",
"from",
"PATH_INFO",
"to",
"SCRIPT_NAME",
"and",
"vice",
"versa",
"."
] | python | train |
perrygeo/simanneal | examples/watershed/shapefile.py | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L347-L353 | def __recordFmt(self):
"""Calculates the size of a .shp geometry record."""
if not self.numRecords:
self.__dbfHeader()
fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields])
fmtSize = calcsize(fmt)
return (fmt, fmtSize) | [
"def",
"__recordFmt",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"numRecords",
":",
"self",
".",
"__dbfHeader",
"(",
")",
"fmt",
"=",
"''",
".",
"join",
"(",
"[",
"'%ds'",
"%",
"fieldinfo",
"[",
"2",
"]",
"for",
"fieldinfo",
"in",
"self",
"."... | Calculates the size of a .shp geometry record. | [
"Calculates",
"the",
"size",
"of",
"a",
".",
"shp",
"geometry",
"record",
"."
] | python | train |
reorx/torext | torext/app.py | https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L223-L240 | def route_many(self, *args, **kwargs):
"""
>>> from torext.route import include
>>> app = TorextApp()
>>> app.route_many([
... ('/account', include('account.views')),
... ('/account', include('account.views')),
... ], '^account.example.com$')
"""
... | [
"def",
"route_many",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"2",
":",
"prefix",
",",
"rules",
"=",
"args",
"elif",
"len",
"(",
"args",
")",
"==",
"1",
":",
"prefix",
"=",
"None",
... | >>> from torext.route import include
>>> app = TorextApp()
>>> app.route_many([
... ('/account', include('account.views')),
... ('/account', include('account.views')),
... ], '^account.example.com$') | [
">>>",
"from",
"torext",
".",
"route",
"import",
"include",
">>>",
"app",
"=",
"TorextApp",
"()",
">>>",
"app",
".",
"route_many",
"(",
"[",
"...",
"(",
"/",
"account",
"include",
"(",
"account",
".",
"views",
"))",
"...",
"(",
"/",
"account",
"include... | python | train |
google/flatbuffers | python/flatbuffers/builder.py | https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L735-L753 | def vtableEqual(a, objectStart, b):
"""vtableEqual compares an unwritten vtable to a written vtable."""
N.enforce_number(objectStart, N.UOffsetTFlags)
if len(a) * N.VOffsetTFlags.bytewidth != len(b):
return False
for i, elem in enumerate(a):
x = encode.Get(packer.voffset, b, i * N.VOf... | [
"def",
"vtableEqual",
"(",
"a",
",",
"objectStart",
",",
"b",
")",
":",
"N",
".",
"enforce_number",
"(",
"objectStart",
",",
"N",
".",
"UOffsetTFlags",
")",
"if",
"len",
"(",
"a",
")",
"*",
"N",
".",
"VOffsetTFlags",
".",
"bytewidth",
"!=",
"len",
"(... | vtableEqual compares an unwritten vtable to a written vtable. | [
"vtableEqual",
"compares",
"an",
"unwritten",
"vtable",
"to",
"a",
"written",
"vtable",
"."
] | python | train |
niklasf/python-chess | chess/engine.py | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2314-L2325 | def close(self) -> None:
"""
Closes the transport and the background event loop as soon as possible.
"""
def _shutdown() -> None:
self.transport.close()
self.shutdown_event.set()
with self._shutdown_lock:
if not self._shutdown:
... | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"def",
"_shutdown",
"(",
")",
"->",
"None",
":",
"self",
".",
"transport",
".",
"close",
"(",
")",
"self",
".",
"shutdown_event",
".",
"set",
"(",
")",
"with",
"self",
".",
"_shutdown_lock",
":",
... | Closes the transport and the background event loop as soon as possible. | [
"Closes",
"the",
"transport",
"and",
"the",
"background",
"event",
"loop",
"as",
"soon",
"as",
"possible",
"."
] | python | train |
glitchassassin/lackey | lackey/InputEmulation.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L59-L73 | def moveSpeed(self, location, seconds=0.3):
""" Moves cursor to specified ``Location`` over ``seconds``.
If ``seconds`` is 0, moves the cursor immediately. Used for smooth
somewhat-human-like motion.
"""
self._lock.acquire()
original_location = mouse.get_position()
... | [
"def",
"moveSpeed",
"(",
"self",
",",
"location",
",",
"seconds",
"=",
"0.3",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"original_location",
"=",
"mouse",
".",
"get_position",
"(",
")",
"mouse",
".",
"move",
"(",
"location",
".",
"x",
... | Moves cursor to specified ``Location`` over ``seconds``.
If ``seconds`` is 0, moves the cursor immediately. Used for smooth
somewhat-human-like motion. | [
"Moves",
"cursor",
"to",
"specified",
"Location",
"over",
"seconds",
"."
] | python | train |
juju/theblues | theblues/identity_manager.py | https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L33-L42 | def get_user(self, username, macaroons):
"""Fetch user data.
Raise a ServerError if an error occurs in the request process.
@param username the user's name.
@param macaroons the encoded macaroons string.
"""
url = '{}u/{}'.format(self.url, username)
return make_... | [
"def",
"get_user",
"(",
"self",
",",
"username",
",",
"macaroons",
")",
":",
"url",
"=",
"'{}u/{}'",
".",
"format",
"(",
"self",
".",
"url",
",",
"username",
")",
"return",
"make_request",
"(",
"url",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
... | Fetch user data.
Raise a ServerError if an error occurs in the request process.
@param username the user's name.
@param macaroons the encoded macaroons string. | [
"Fetch",
"user",
"data",
"."
] | python | train |
langloisjp/tstore | tstore/pgtablestorage.py | https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L398-L409 | def sqldelete(table, where):
"""Generates SQL delete from ... where ...
>>> sqldelete('t', {'id': 5})
('delete from t where id=%s', [5])
"""
validate_name(table)
(whereclause, wherevalues) = sqlwhere(where)
sql = "delete from {}".format(table)
if whereclause:
sql += " where " + ... | [
"def",
"sqldelete",
"(",
"table",
",",
"where",
")",
":",
"validate_name",
"(",
"table",
")",
"(",
"whereclause",
",",
"wherevalues",
")",
"=",
"sqlwhere",
"(",
"where",
")",
"sql",
"=",
"\"delete from {}\"",
".",
"format",
"(",
"table",
")",
"if",
"wher... | Generates SQL delete from ... where ...
>>> sqldelete('t', {'id': 5})
('delete from t where id=%s', [5]) | [
"Generates",
"SQL",
"delete",
"from",
"...",
"where",
"..."
] | python | train |
chaimleib/intervaltree | intervaltree/node.py | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L205-L214 | def remove(self, interval):
"""
Returns self after removing the interval and balancing.
If interval is not present, raise ValueError.
"""
# since this is a list, called methods can set this to [1],
# making it true
done = []
return self.remove_interval_he... | [
"def",
"remove",
"(",
"self",
",",
"interval",
")",
":",
"# since this is a list, called methods can set this to [1],",
"# making it true",
"done",
"=",
"[",
"]",
"return",
"self",
".",
"remove_interval_helper",
"(",
"interval",
",",
"done",
",",
"should_raise_error",
... | Returns self after removing the interval and balancing.
If interval is not present, raise ValueError. | [
"Returns",
"self",
"after",
"removing",
"the",
"interval",
"and",
"balancing",
"."
] | python | train |
sosy-lab/benchexec | benchexec/tablegenerator/__init__.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/tablegenerator/__init__.py#L214-L228 | def _get_columns_relevant_for_diff(columns_to_show):
"""
Extract columns that are relevant for the diff table.
@param columns_to_show: (list) A list of columns that should be shown
@return: (set) Set of columns that are relevant for the diff table. If
none is marked relevant, the column na... | [
"def",
"_get_columns_relevant_for_diff",
"(",
"columns_to_show",
")",
":",
"cols",
"=",
"set",
"(",
"[",
"col",
".",
"title",
"for",
"col",
"in",
"columns_to_show",
"if",
"col",
".",
"relevant_for_diff",
"]",
")",
"if",
"len",
"(",
"cols",
")",
"==",
"0",
... | Extract columns that are relevant for the diff table.
@param columns_to_show: (list) A list of columns that should be shown
@return: (set) Set of columns that are relevant for the diff table. If
none is marked relevant, the column named "status" will be
returned in the set. | [
"Extract",
"columns",
"that",
"are",
"relevant",
"for",
"the",
"diff",
"table",
"."
] | python | train |
fedora-infra/fedora-messaging | fedora_messaging/_session.py | https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/_session.py#L324-L358 | def _on_connection_close(self, connection, reply_code_or_reason, reply_text=None):
"""
Callback invoked when a previously-opened connection is closed.
Args:
connection (pika.connection.SelectConnection): The connection that
was just closed.
reply_code_or_... | [
"def",
"_on_connection_close",
"(",
"self",
",",
"connection",
",",
"reply_code_or_reason",
",",
"reply_text",
"=",
"None",
")",
":",
"self",
".",
"_channel",
"=",
"None",
"if",
"isinstance",
"(",
"reply_code_or_reason",
",",
"pika_errs",
".",
"ConnectionClosed",
... | Callback invoked when a previously-opened connection is closed.
Args:
connection (pika.connection.SelectConnection): The connection that
was just closed.
reply_code_or_reason (int|Exception): The reason why the channel
was closed. In older versions of pik... | [
"Callback",
"invoked",
"when",
"a",
"previously",
"-",
"opened",
"connection",
"is",
"closed",
"."
] | python | train |
dunovank/jupyter-themes | jupyterthemes/stylefx.py | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L400-L420 | def set_mathjax_style(style_css, mathfontsize):
"""Write mathjax settings, set math fontsize
"""
jax_style = """<script>
MathJax.Hub.Config({
"HTML-CSS": {
/*preferredFont: "TeX",*/
/*availableFonts: ["TeX", "STIX"],*/
styles: {
scale: %d,
... | [
"def",
"set_mathjax_style",
"(",
"style_css",
",",
"mathfontsize",
")",
":",
"jax_style",
"=",
"\"\"\"<script>\n MathJax.Hub.Config({\n \"HTML-CSS\": {\n /*preferredFont: \"TeX\",*/\n /*availableFonts: [\"TeX\", \"STIX\"],*/\n styles: {\n ... | Write mathjax settings, set math fontsize | [
"Write",
"mathjax",
"settings",
"set",
"math",
"fontsize"
] | python | train |
wilzbach/smarkov | smarkov/hmm.py | https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/hmm.py#L93-L96 | def _emitHMM(self, token_type, past_states, past_emissions):
""" emits a word based on previous tokens """
assert token_type in self.emissions
return utils.weighted_choice(self.emissions[token_type].items()) | [
"def",
"_emitHMM",
"(",
"self",
",",
"token_type",
",",
"past_states",
",",
"past_emissions",
")",
":",
"assert",
"token_type",
"in",
"self",
".",
"emissions",
"return",
"utils",
".",
"weighted_choice",
"(",
"self",
".",
"emissions",
"[",
"token_type",
"]",
... | emits a word based on previous tokens | [
"emits",
"a",
"word",
"based",
"on",
"previous",
"tokens"
] | python | train |
xtrementl/focus | focus/plugin/modules/timer.py | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/timer.py#L55-L69 | def parse_option(self, option, block_name, *values):
""" Parse duration option for timer.
"""
try:
if len(values) != 1:
raise TypeError
self.total_duration = int(values[0])
if self.total_duration <= 0:
raise ValueError
... | [
"def",
"parse_option",
"(",
"self",
",",
"option",
",",
"block_name",
",",
"*",
"values",
")",
":",
"try",
":",
"if",
"len",
"(",
"values",
")",
"!=",
"1",
":",
"raise",
"TypeError",
"self",
".",
"total_duration",
"=",
"int",
"(",
"values",
"[",
"0",... | Parse duration option for timer. | [
"Parse",
"duration",
"option",
"for",
"timer",
"."
] | python | train |
proversity-org/bibblio-api-python | bibbliothon/enrichment.py | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L15-L33 | def create_content_item(access_token, payload):
'''
Name: create_content_item
Parameters: access_token, payload (dict)
Return: dictionary
'''
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + str(access_token)
}
request = requests.post(enrichment_url, json=payload, headers=heade... | [
"def",
"create_content_item",
"(",
"access_token",
",",
"payload",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"request",
"=",
"requests",
".",
... | Name: create_content_item
Parameters: access_token, payload (dict)
Return: dictionary | [
"Name",
":",
"create_content_item",
"Parameters",
":",
"access_token",
"payload",
"(",
"dict",
")",
"Return",
":",
"dictionary"
] | python | train |
chaoss/grimoirelab-perceval | perceval/backends/core/phabricator.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/phabricator.py#L196-L210 | def parse_users(raw_json):
"""Parse a Phabricator users JSON stream.
The method parses a JSON stream and returns a list iterator.
Each item is a dictionary that contais the user parsed data.
:param raw_json: JSON string to parse
:returns: a generator of parsed users
""... | [
"def",
"parse_users",
"(",
"raw_json",
")",
":",
"results",
"=",
"json",
".",
"loads",
"(",
"raw_json",
")",
"users",
"=",
"results",
"[",
"'result'",
"]",
"for",
"u",
"in",
"users",
":",
"yield",
"u"
] | Parse a Phabricator users JSON stream.
The method parses a JSON stream and returns a list iterator.
Each item is a dictionary that contais the user parsed data.
:param raw_json: JSON string to parse
:returns: a generator of parsed users | [
"Parse",
"a",
"Phabricator",
"users",
"JSON",
"stream",
"."
] | python | test |
sony/nnabla | python/src/nnabla/experimental/mixed_precision_training.py | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/experimental/mixed_precision_training.py#L86-L143 | def update(self):
"""Monolithic update method.
This method calls the following methods with the dynamic loss scaling.
1. solver.zerograd
2. feed data
3. loss.forward
4. loss.backward
5. comm.all_reduce (if it is specified)
6. solver.update
"""
... | [
"def",
"update",
"(",
"self",
")",
":",
"# Initialize gradients.",
"self",
".",
"solver",
".",
"zero_grad",
"(",
")",
"# Forward and backward",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"accum_grad",
")",
":",
"# feed data",
"self",
".",
"data_feeder",
"(... | Monolithic update method.
This method calls the following methods with the dynamic loss scaling.
1. solver.zerograd
2. feed data
3. loss.forward
4. loss.backward
5. comm.all_reduce (if it is specified)
6. solver.update | [
"Monolithic",
"update",
"method",
"."
] | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/brocade_ras_ext_rpc/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/brocade_ras_ext_rpc/__init__.py#L176-L199 | def _set_show_system_info(self, v, load=False):
"""
Setter method for show_system_info, mapped from YANG variable /brocade_ras_ext_rpc/show_system_info (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_system_info is considered as a private
method. Backends ... | [
"def",
"_set_show_system_info",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for show_system_info, mapped from YANG variable /brocade_ras_ext_rpc/show_system_info (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_system_info is considered as a private
method. Backends looking to populate this variable should
do so via calli... | [
"Setter",
"method",
"for",
"show_system_info",
"mapped",
"from",
"YANG",
"variable",
"/",
"brocade_ras_ext_rpc",
"/",
"show_system_info",
"(",
"rpc",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"so... | python | train |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/entitlements.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L316-L360 | def update(ctx, opts, owner_repo_identifier, show_tokens, name, token):
"""
Update (set) a entitlement in a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
... | [
"def",
"update",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_identifier",
",",
"show_tokens",
",",
"name",
",",
"token",
")",
":",
"owner",
",",
"repo",
",",
"identifier",
"=",
"owner_repo_identifier",
"# Use stderr for messages if the output is something else (e.g. # JS... | Update (set) a entitlement in a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your-repo/abcdef123456'
Full CLI example:
$ cloudsmi... | [
"Update",
"(",
"set",
")",
"a",
"entitlement",
"in",
"a",
"repository",
"."
] | python | train |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winresource.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winresource.py#L93-L104 | def update_resources_from_dict(self, res, types=None, names=None,
languages=None):
"""
Update or add resources from resource dict.
types = a list of resource types to update (None = all)
names = a list of resource names to update (None = all)
... | [
"def",
"update_resources_from_dict",
"(",
"self",
",",
"res",
",",
"types",
"=",
"None",
",",
"names",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",
"UpdateResourcesFromDict",
"(",
"self",
".",
"filename",
",",
"res",
",",
"types",
",",
"names",
... | Update or add resources from resource dict.
types = a list of resource types to update (None = all)
names = a list of resource names to update (None = all)
languages = a list of resource languages to update (None = all) | [
"Update",
"or",
"add",
"resources",
"from",
"resource",
"dict",
".",
"types",
"=",
"a",
"list",
"of",
"resource",
"types",
"to",
"update",
"(",
"None",
"=",
"all",
")",
"names",
"=",
"a",
"list",
"of",
"resource",
"names",
"to",
"update",
"(",
"None",
... | python | train |
dgomes/pyipma | pyipma/api.py | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L76-L97 | async def forecast(self, globalIdLocal):
"""Retrieve next 5 days forecast."""
data = await self.retrieve(API_FORECAST + "{globalIdLocal}.json".
format(globalIdLocal=globalIdLocal))
if not self.weather_type:
await self.weather_type_classe()
... | [
"async",
"def",
"forecast",
"(",
"self",
",",
"globalIdLocal",
")",
":",
"data",
"=",
"await",
"self",
".",
"retrieve",
"(",
"API_FORECAST",
"+",
"\"{globalIdLocal}.json\"",
".",
"format",
"(",
"globalIdLocal",
"=",
"globalIdLocal",
")",
")",
"if",
"not",
"s... | Retrieve next 5 days forecast. | [
"Retrieve",
"next",
"5",
"days",
"forecast",
"."
] | python | train |
fedora-infra/fmn.rules | fmn/rules/generic.py | https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/generic.py#L26-L44 | def not_user_filter(config, message, fasnick=None, *args, **kw):
""" Everything except a particular user
Use this rule to exclude messages that are associated with one or more
users. Specify several users by separating them with a comma ','.
"""
fasnick = kw.get('fasnick', fasnick)
if not fasn... | [
"def",
"not_user_filter",
"(",
"config",
",",
"message",
",",
"fasnick",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"fasnick",
"=",
"kw",
".",
"get",
"(",
"'fasnick'",
",",
"fasnick",
")",
"if",
"not",
"fasnick",
":",
"return",
"... | Everything except a particular user
Use this rule to exclude messages that are associated with one or more
users. Specify several users by separating them with a comma ','. | [
"Everything",
"except",
"a",
"particular",
"user"
] | python | train |
ralphje/imagemounter | imagemounter/volume.py | https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/volume.py#L374-L409 | def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True):
"""Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mou... | [
"def",
"init",
"(",
"self",
",",
"only_mount",
"=",
"None",
",",
"skip_mount",
"=",
"None",
",",
"swallow_exceptions",
"=",
"True",
")",
":",
"if",
"swallow_exceptions",
":",
"self",
".",
"exception",
"=",
"None",
"try",
":",
"if",
"not",
"self",
".",
... | Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by
:func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded,... | [
"Generator",
"that",
"mounts",
"this",
"volume",
"and",
"either",
"yields",
"itself",
"or",
"recursively",
"generates",
"its",
"subvolumes",
"."
] | python | train |
ConsenSys/mythril-classic | mythril/laser/ethereum/state/machine_state.py | https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/laser/ethereum/state/machine_state.py#L174-L185 | def pop(self, amount=1) -> Union[BitVec, List[BitVec]]:
"""Pops amount elements from the stack.
:param amount:
:return:
"""
if amount > len(self.stack):
raise StackUnderflowException
values = self.stack[-amount:][::-1]
del self.stack[-amount:]
... | [
"def",
"pop",
"(",
"self",
",",
"amount",
"=",
"1",
")",
"->",
"Union",
"[",
"BitVec",
",",
"List",
"[",
"BitVec",
"]",
"]",
":",
"if",
"amount",
">",
"len",
"(",
"self",
".",
"stack",
")",
":",
"raise",
"StackUnderflowException",
"values",
"=",
"s... | Pops amount elements from the stack.
:param amount:
:return: | [
"Pops",
"amount",
"elements",
"from",
"the",
"stack",
"."
] | python | train |
riga/tfdeploy | tfdeploy.py | https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L705-L719 | def func(self, values):
"""
The actual ensembling logic that combines multiple *values*. The method call is forwareded
tothe ensemble method-specific variant which is determined using *method*.
"""
if self.method == METHOD_MEAN:
return self.func_mean(values)
e... | [
"def",
"func",
"(",
"self",
",",
"values",
")",
":",
"if",
"self",
".",
"method",
"==",
"METHOD_MEAN",
":",
"return",
"self",
".",
"func_mean",
"(",
"values",
")",
"elif",
"self",
".",
"method",
"==",
"METHOD_MAX",
":",
"return",
"self",
".",
"func_max... | The actual ensembling logic that combines multiple *values*. The method call is forwareded
tothe ensemble method-specific variant which is determined using *method*. | [
"The",
"actual",
"ensembling",
"logic",
"that",
"combines",
"multiple",
"*",
"values",
"*",
".",
"The",
"method",
"call",
"is",
"forwareded",
"tothe",
"ensemble",
"method",
"-",
"specific",
"variant",
"which",
"is",
"determined",
"using",
"*",
"method",
"*",
... | python | train |
olucurious/PyFCM | pyfcm/baseapi.py | https://github.com/olucurious/PyFCM/blob/28096cd5f6ef515bb6034e63327723d12304249a/pyfcm/baseapi.py#L363-L390 | def subscribe_registration_ids_to_topic(self, registration_ids, topic_name):
"""
Subscribes a list of registration ids to a topic
Args:
registration_ids (list): ids to be subscribed
topic_name (str): name of topic
Returns:
True: if operation succeede... | [
"def",
"subscribe_registration_ids_to_topic",
"(",
"self",
",",
"registration_ids",
",",
"topic_name",
")",
":",
"url",
"=",
"'https://iid.googleapis.com/iid/v1:batchAdd'",
"payload",
"=",
"{",
"'to'",
":",
"'/topics/'",
"+",
"topic_name",
",",
"'registration_tokens'",
... | Subscribes a list of registration ids to a topic
Args:
registration_ids (list): ids to be subscribed
topic_name (str): name of topic
Returns:
True: if operation succeeded
Raises:
InvalidDataError: data sent to server was incorrectly formatted
... | [
"Subscribes",
"a",
"list",
"of",
"registration",
"ids",
"to",
"a",
"topic"
] | python | train |
dgketchum/satellite_image | sat_image/mtl.py | https://github.com/dgketchum/satellite_image/blob/0207fbb7b2bbf14f4307db65489bb4d4c5b92f52/sat_image/mtl.py#L148-L194 | def _checkstatus(status, line):
"""Returns state/status after reading the next line.
The status codes are::
LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF - BEGIN parsing; 1 - ENTER METADATA GROUP, 2 - READ METADATA LINE,
3 - END METDADATA GROUP, 4 - END PARSING
Permitted Transitions::... | [
"def",
"_checkstatus",
"(",
"status",
",",
"line",
")",
":",
"newstatus",
"=",
"0",
"if",
"status",
"==",
"0",
":",
"# begin --> enter metadata group OR end",
"if",
"_islinetype",
"(",
"line",
",",
"GRPSTART",
")",
":",
"newstatus",
"=",
"1",
"elif",
"_isfin... | Returns state/status after reading the next line.
The status codes are::
LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF - BEGIN parsing; 1 - ENTER METADATA GROUP, 2 - READ METADATA LINE,
3 - END METDADATA GROUP, 4 - END PARSING
Permitted Transitions::
LE07_clip_L1TP_039027_20150529... | [
"Returns",
"state",
"/",
"status",
"after",
"reading",
"the",
"next",
"line",
".",
"The",
"status",
"codes",
"are",
"::",
"LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1",
".",
"TIF",
"-",
"BEGIN",
"parsing",
";",
"1",
"-",
"ENTER",
"METADATA",
"GROUP",
"2",
... | python | train |
saltstack/salt | salt/states/boto_apigateway.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1280-L1285 | def _aws_model_ref_from_swagger_ref(self, r):
'''
Helper function to reference models created on aws apigw
'''
model_name = r.split('/')[-1]
return 'https://apigateway.amazonaws.com/restapis/{0}/models/{1}'.format(self.restApiId, model_name) | [
"def",
"_aws_model_ref_from_swagger_ref",
"(",
"self",
",",
"r",
")",
":",
"model_name",
"=",
"r",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"return",
"'https://apigateway.amazonaws.com/restapis/{0}/models/{1}'",
".",
"format",
"(",
"self",
".",
"restAp... | Helper function to reference models created on aws apigw | [
"Helper",
"function",
"to",
"reference",
"models",
"created",
"on",
"aws",
"apigw"
] | python | train |
spyder-ide/spyder | spyder/plugins/console/utils/interpreter.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/utils/interpreter.py#L298-L308 | def eval(self, text):
"""
Evaluate text and return (obj, valid)
where *obj* is the object represented by *text*
and *valid* is True if object evaluation did not raise any exception
"""
assert is_text_string(text)
try:
return eval(text, self.loc... | [
"def",
"eval",
"(",
"self",
",",
"text",
")",
":",
"assert",
"is_text_string",
"(",
"text",
")",
"try",
":",
"return",
"eval",
"(",
"text",
",",
"self",
".",
"locals",
")",
",",
"True",
"except",
":",
"return",
"None",
",",
"False"
] | Evaluate text and return (obj, valid)
where *obj* is the object represented by *text*
and *valid* is True if object evaluation did not raise any exception | [
"Evaluate",
"text",
"and",
"return",
"(",
"obj",
"valid",
")",
"where",
"*",
"obj",
"*",
"is",
"the",
"object",
"represented",
"by",
"*",
"text",
"*",
"and",
"*",
"valid",
"*",
"is",
"True",
"if",
"object",
"evaluation",
"did",
"not",
"raise",
"any",
... | python | train |
FactoryBoy/factory_boy | factory/builder.py | https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/builder.py#L251-L306 | def build(self, parent_step=None, force_sequence=None):
"""Build a factory instance."""
# TODO: Handle "batch build" natively
pre, post = parse_declarations(
self.extras,
base_pre=self.factory_meta.pre_declarations,
base_post=self.factory_meta.post_declaration... | [
"def",
"build",
"(",
"self",
",",
"parent_step",
"=",
"None",
",",
"force_sequence",
"=",
"None",
")",
":",
"# TODO: Handle \"batch build\" natively",
"pre",
",",
"post",
"=",
"parse_declarations",
"(",
"self",
".",
"extras",
",",
"base_pre",
"=",
"self",
".",... | Build a factory instance. | [
"Build",
"a",
"factory",
"instance",
"."
] | python | train |
seb-m/pyinotify | python2/pyinotify.py | https://github.com/seb-m/pyinotify/blob/0f3f8950d12e4a6534320153eed1a90a778da4ae/python2/pyinotify.py#L1838-L1849 | def __format_path(self, path):
"""
Format path to its internal (stored in watch manager) representation.
"""
# Unicode strings are converted back to strings, because it seems
# that inotify_add_watch from ctypes does not work well when
# it receives an ctypes.create_unico... | [
"def",
"__format_path",
"(",
"self",
",",
"path",
")",
":",
"# Unicode strings are converted back to strings, because it seems",
"# that inotify_add_watch from ctypes does not work well when",
"# it receives an ctypes.create_unicode_buffer instance as argument.",
"# Therefore even wd are index... | Format path to its internal (stored in watch manager) representation. | [
"Format",
"path",
"to",
"its",
"internal",
"(",
"stored",
"in",
"watch",
"manager",
")",
"representation",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/help/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/plugin.py#L247-L267 | def apply_plugin_settings(self, options):
"""Apply configuration file's plugin settings"""
color_scheme_n = 'color_scheme_name'
color_scheme_o = self.get_color_scheme()
connect_n = 'connect_to_oi'
wrap_n = 'wrap'
wrap_o = self.get_option(wrap_n)
self.wrap_a... | [
"def",
"apply_plugin_settings",
"(",
"self",
",",
"options",
")",
":",
"color_scheme_n",
"=",
"'color_scheme_name'",
"color_scheme_o",
"=",
"self",
".",
"get_color_scheme",
"(",
")",
"connect_n",
"=",
"'connect_to_oi'",
"wrap_n",
"=",
"'wrap'",
"wrap_o",
"=",
"sel... | Apply configuration file's plugin settings | [
"Apply",
"configuration",
"file",
"s",
"plugin",
"settings"
] | python | train |
honeynet/beeswarm | beeswarm/drones/honeypot/helpers/common.py | https://github.com/honeynet/beeswarm/blob/db51ea0bc29f631c3e3b5312b479ac9d5e31079a/beeswarm/drones/honeypot/helpers/common.py#L10-L15 | def list2dict(list_of_options):
"""Transforms a list of 2 element tuples to a dictionary"""
d = {}
for key, value in list_of_options:
d[key] = value
return d | [
"def",
"list2dict",
"(",
"list_of_options",
")",
":",
"d",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"list_of_options",
":",
"d",
"[",
"key",
"]",
"=",
"value",
"return",
"d"
] | Transforms a list of 2 element tuples to a dictionary | [
"Transforms",
"a",
"list",
"of",
"2",
"element",
"tuples",
"to",
"a",
"dictionary"
] | python | train |
apache/spark | python/pyspark/sql/functions.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L1856-L1867 | def translate(srcCol, matching, replace):
"""A function translate any character in the `srcCol` by a character in `matching`.
The characters in `replace` is corresponding to the characters in `matching`.
The translate will happen when any character in the string matching with the character
in the `match... | [
"def",
"translate",
"(",
"srcCol",
",",
"matching",
",",
"replace",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"translate",
"(",
"_to_java_column",
"(",
"srcCol",
")",... | A function translate any character in the `srcCol` by a character in `matching`.
The characters in `replace` is corresponding to the characters in `matching`.
The translate will happen when any character in the string matching with the character
in the `matching`.
>>> spark.createDataFrame([('translate... | [
"A",
"function",
"translate",
"any",
"character",
"in",
"the",
"srcCol",
"by",
"a",
"character",
"in",
"matching",
".",
"The",
"characters",
"in",
"replace",
"is",
"corresponding",
"to",
"the",
"characters",
"in",
"matching",
".",
"The",
"translate",
"will",
... | python | train |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L568-L581 | def get_wellseries(self, matrix):
"""
Returns the grid as a WellSeries of WellSeries
"""
res = OrderedDict()
for col, cells in matrix.items():
if col not in res:
res[col] = OrderedDict()
for row, cell in cells.items():
res[c... | [
"def",
"get_wellseries",
"(",
"self",
",",
"matrix",
")",
":",
"res",
"=",
"OrderedDict",
"(",
")",
"for",
"col",
",",
"cells",
"in",
"matrix",
".",
"items",
"(",
")",
":",
"if",
"col",
"not",
"in",
"res",
":",
"res",
"[",
"col",
"]",
"=",
"Order... | Returns the grid as a WellSeries of WellSeries | [
"Returns",
"the",
"grid",
"as",
"a",
"WellSeries",
"of",
"WellSeries"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.