repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L63-L69 | def getWriteSession(self):
''' return unscope session, TODO, make it clear '''
if self.WriteSession is None:
self.WriteSession=sessionmaker(bind=self.engine)
self.writeSession=self.WriteSession()
return self.writeSession | [
"def",
"getWriteSession",
"(",
"self",
")",
":",
"if",
"self",
".",
"WriteSession",
"is",
"None",
":",
"self",
".",
"WriteSession",
"=",
"sessionmaker",
"(",
"bind",
"=",
"self",
".",
"engine",
")",
"self",
".",
"writeSession",
"=",
"self",
".",
"WriteSe... | return unscope session, TODO, make it clear | [
"return",
"unscope",
"session",
"TODO",
"make",
"it",
"clear"
] | python | train | 38.428571 |
yougov/mongo-connector | mongo_connector/doc_managers/doc_manager_simulator.py | https://github.com/yougov/mongo-connector/blob/557cafd4b54c848cd54ef28a258391a154650cb4/mongo_connector/doc_managers/doc_manager_simulator.py#L156-L171 | def search(self, start_ts, end_ts):
"""Searches through all documents and finds all documents that were
modified or deleted within the range.
Since we have very few documents in the doc dict when this is called,
linear search is fine. This method is only used by rollbacks to query
... | [
"def",
"search",
"(",
"self",
",",
"start_ts",
",",
"end_ts",
")",
":",
"for",
"_id",
"in",
"self",
".",
"doc_dict",
":",
"entry",
"=",
"self",
".",
"doc_dict",
"[",
"_id",
"]",
"if",
"entry",
".",
"ts",
"<=",
"end_ts",
"or",
"entry",
".",
"ts",
... | Searches through all documents and finds all documents that were
modified or deleted within the range.
Since we have very few documents in the doc dict when this is called,
linear search is fine. This method is only used by rollbacks to query
all the documents in the target engine withi... | [
"Searches",
"through",
"all",
"documents",
"and",
"finds",
"all",
"documents",
"that",
"were",
"modified",
"or",
"deleted",
"within",
"the",
"range",
"."
] | python | train | 52.4375 |
facetoe/zenpy | zenpy/lib/api_objects/__init__.py | https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api_objects/__init__.py#L4242-L4247 | def submitter(self):
"""
| Comment: The user who submitted the ticket. The submitter always becomes the author of the first comment on the ticket
"""
if self.api and self.submitter_id:
return self.api._get_user(self.submitter_id) | [
"def",
"submitter",
"(",
"self",
")",
":",
"if",
"self",
".",
"api",
"and",
"self",
".",
"submitter_id",
":",
"return",
"self",
".",
"api",
".",
"_get_user",
"(",
"self",
".",
"submitter_id",
")"
] | | Comment: The user who submitted the ticket. The submitter always becomes the author of the first comment on the ticket | [
"|",
"Comment",
":",
"The",
"user",
"who",
"submitted",
"the",
"ticket",
".",
"The",
"submitter",
"always",
"becomes",
"the",
"author",
"of",
"the",
"first",
"comment",
"on",
"the",
"ticket"
] | python | train | 44.833333 |
bwohlberg/sporco | sporco/common.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/common.py#L147-L167 | def set_dtype(self, opt, dtype):
"""Set the `dtype` attribute. If opt['DataType'] has a value
other than None, it overrides the `dtype` parameter of this
method. No changes are made if the `dtype` attribute already
exists and has a value other than 'None'.
Parameters
---... | [
"def",
"set_dtype",
"(",
"self",
",",
"opt",
",",
"dtype",
")",
":",
"# Take no action of self.dtype exists and is not None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'dtype'",
")",
"or",
"self",
".",
"dtype",
"is",
"None",
":",
"# DataType option overrides expl... | Set the `dtype` attribute. If opt['DataType'] has a value
other than None, it overrides the `dtype` parameter of this
method. No changes are made if the `dtype` attribute already
exists and has a value other than 'None'.
Parameters
----------
opt : :class:`cdict.Constrai... | [
"Set",
"the",
"dtype",
"attribute",
".",
"If",
"opt",
"[",
"DataType",
"]",
"has",
"a",
"value",
"other",
"than",
"None",
"it",
"overrides",
"the",
"dtype",
"parameter",
"of",
"this",
"method",
".",
"No",
"changes",
"are",
"made",
"if",
"the",
"dtype",
... | python | train | 40.190476 |
Shapeways/coyote_framework | coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py | https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebDriverWrapper.py#L258-L277 | def is_alert_present(self):
"""Tests if an alert is present
@return: True if alert is present, False otherwise
"""
current_frame = None
try:
current_frame = self.driver.current_window_handle
a = self.driver.switch_to_alert()
a.text
exc... | [
"def",
"is_alert_present",
"(",
"self",
")",
":",
"current_frame",
"=",
"None",
"try",
":",
"current_frame",
"=",
"self",
".",
"driver",
".",
"current_window_handle",
"a",
"=",
"self",
".",
"driver",
".",
"switch_to_alert",
"(",
")",
"a",
".",
"text",
"exc... | Tests if an alert is present
@return: True if alert is present, False otherwise | [
"Tests",
"if",
"an",
"alert",
"is",
"present"
] | python | train | 30.15 |
asaskevich/binario | binario/writer.py | https://github.com/asaskevich/binario/blob/8d40337952ab77f02da0edeae7fa761eadf6ab45/binario/writer.py#L92-L95 | def write_long(self, number):
""" Writes a long integer to the underlying output file as a 8-byte value. """
buf = pack(self.byte_order + "q", number)
self.write(buf) | [
"def",
"write_long",
"(",
"self",
",",
"number",
")",
":",
"buf",
"=",
"pack",
"(",
"self",
".",
"byte_order",
"+",
"\"q\"",
",",
"number",
")",
"self",
".",
"write",
"(",
"buf",
")"
] | Writes a long integer to the underlying output file as a 8-byte value. | [
"Writes",
"a",
"long",
"integer",
"to",
"the",
"underlying",
"output",
"file",
"as",
"a",
"8",
"-",
"byte",
"value",
"."
] | python | train | 46.75 |
WoLpH/python-progressbar | progressbar/bar.py | https://github.com/WoLpH/python-progressbar/blob/963617a1bb9d81624ecf31f3457185992cd97bfa/progressbar/bar.py#L552-L597 | def update(self, value=None, force=False, **kwargs):
'Updates the ProgressBar to a new value.'
if self.start_time is None:
self.start()
return self.update(value, force=force, **kwargs)
if value is not None and value is not base.UnknownLength:
if self.max_valu... | [
"def",
"update",
"(",
"self",
",",
"value",
"=",
"None",
",",
"force",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"start_time",
"is",
"None",
":",
"self",
".",
"start",
"(",
")",
"return",
"self",
".",
"update",
"(",
"val... | Updates the ProgressBar to a new value. | [
"Updates",
"the",
"ProgressBar",
"to",
"a",
"new",
"value",
"."
] | python | train | 39.021739 |
welbornprod/colr | colr/progress_frames.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L73-L101 | def cls_register(cls, frameset, new_class, init_args, name=None):
""" Register a new FrameSet or FrameSet subclass as a member/attribute
of a class.
Returns the new FrameSet or FrameSet subclass.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
... | [
"def",
"cls_register",
"(",
"cls",
",",
"frameset",
",",
"new_class",
",",
"init_args",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"getattr",
"(",
"frameset",
",",
"'name'",
",",
"None",
")",
"if",
"name",
"is",
"None",
":",
"rais... | Register a new FrameSet or FrameSet subclass as a member/attribute
of a class.
Returns the new FrameSet or FrameSet subclass.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
init_args : A list of properties from the `frameset` to try to use
... | [
"Register",
"a",
"new",
"FrameSet",
"or",
"FrameSet",
"subclass",
"as",
"a",
"member",
"/",
"attribute",
"of",
"a",
"class",
".",
"Returns",
"the",
"new",
"FrameSet",
"or",
"FrameSet",
"subclass",
".",
"Arguments",
":",
"frameset",
":",
"An",
"existing",
"... | python | train | 44.655172 |
rigetti/pyquil | pyquil/unitary_tools.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/unitary_tools.py#L359-L377 | def lifted_state_operator(state: TensorProductState, qubits: List[int]):
"""Take a TensorProductState along with a list of qubits and return a matrix
corresponding to the tensored-up representation of the states' density operator form.
Developer note: Quil and the QVM like qubits to be ordered such that qu... | [
"def",
"lifted_state_operator",
"(",
"state",
":",
"TensorProductState",
",",
"qubits",
":",
"List",
"[",
"int",
"]",
")",
":",
"mat",
"=",
"1.0",
"for",
"qubit",
"in",
"qubits",
":",
"oneq_state",
"=",
"state",
"[",
"qubit",
"]",
"assert",
"oneq_state",
... | Take a TensorProductState along with a list of qubits and return a matrix
corresponding to the tensored-up representation of the states' density operator form.
Developer note: Quil and the QVM like qubits to be ordered such that qubit 0 is on the right.
Therefore, in ``qubit_adjacent_lifted_gate``, ``lifte... | [
"Take",
"a",
"TensorProductState",
"along",
"with",
"a",
"list",
"of",
"qubits",
"and",
"return",
"a",
"matrix",
"corresponding",
"to",
"the",
"tensored",
"-",
"up",
"representation",
"of",
"the",
"states",
"density",
"operator",
"form",
"."
] | python | train | 49.526316 |
ralphbean/taskw | taskw/warrior.py | https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L816-L825 | def task_delete(self, **kw):
""" Marks a task as deleted. """
id, task = self.get_task(**kw)
if task['status'] == Status.DELETED:
raise ValueError("Task is already deleted.")
self._execute(id, 'delete')
return self.get_task(uuid=task['uuid'])[1] | [
"def",
"task_delete",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"id",
",",
"task",
"=",
"self",
".",
"get_task",
"(",
"*",
"*",
"kw",
")",
"if",
"task",
"[",
"'status'",
"]",
"==",
"Status",
".",
"DELETED",
":",
"raise",
"ValueError",
"(",
"\"T... | Marks a task as deleted. | [
"Marks",
"a",
"task",
"as",
"deleted",
"."
] | python | train | 29.2 |
numenta/htmresearch | projects/sequence_prediction/continuous_sequence/run_tm_model.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sequence_prediction/continuous_sequence/run_tm_model.py#L172-L187 | def runMultiplePassSPonly(df, model, nMultiplePass, nTrain):
"""
run CLA model SP through data record 0:nTrain nMultiplePass passes
"""
predictedField = model.getInferenceArgs()['predictedField']
print "run TM through the train data multiple times"
for nPass in xrange(nMultiplePass):
for j in xrange(nT... | [
"def",
"runMultiplePassSPonly",
"(",
"df",
",",
"model",
",",
"nMultiplePass",
",",
"nTrain",
")",
":",
"predictedField",
"=",
"model",
".",
"getInferenceArgs",
"(",
")",
"[",
"'predictedField'",
"]",
"print",
"\"run TM through the train data multiple times\"",
"for",... | run CLA model SP through data record 0:nTrain nMultiplePass passes | [
"run",
"CLA",
"model",
"SP",
"through",
"data",
"record",
"0",
":",
"nTrain",
"nMultiplePass",
"passes"
] | python | train | 32.625 |
chrisrink10/basilisp | src/basilisp/lang/compiler/generator.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/generator.py#L400-L407 | def _is_dynamic(v: Var) -> bool:
"""Return True if the Var holds a value which should be compiled to a dynamic
Var access."""
return (
Maybe(v.meta)
.map(lambda m: m.get(SYM_DYNAMIC_META_KEY, None)) # type: ignore
.or_else_get(False)
) | [
"def",
"_is_dynamic",
"(",
"v",
":",
"Var",
")",
"->",
"bool",
":",
"return",
"(",
"Maybe",
"(",
"v",
".",
"meta",
")",
".",
"map",
"(",
"lambda",
"m",
":",
"m",
".",
"get",
"(",
"SYM_DYNAMIC_META_KEY",
",",
"None",
")",
")",
"# type: ignore",
".",... | Return True if the Var holds a value which should be compiled to a dynamic
Var access. | [
"Return",
"True",
"if",
"the",
"Var",
"holds",
"a",
"value",
"which",
"should",
"be",
"compiled",
"to",
"a",
"dynamic",
"Var",
"access",
"."
] | python | test | 33.625 |
funilrys/PyFunceble | PyFunceble/__init__.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/__init__.py#L556-L1339 | def _command_line(): # pragma: no cover pylint: disable=too-many-branches,too-many-statements
"""
Provide the command line interface.
"""
if __name__ == "PyFunceble":
# We initiate the end of the coloration at the end of each line.
initiate(autoreset=True)
# We load the config... | [
"def",
"_command_line",
"(",
")",
":",
"# pragma: no cover pylint: disable=too-many-branches,too-many-statements",
"if",
"__name__",
"==",
"\"PyFunceble\"",
":",
"# We initiate the end of the coloration at the end of each line.",
"initiate",
"(",
"autoreset",
"=",
"True",
")",
"#... | Provide the command line interface. | [
"Provide",
"the",
"command",
"line",
"interface",
"."
] | python | test | 35.705357 |
mitsei/dlkit | dlkit/json_/learning/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/objects.py#L1290-L1302 | def clear_completion(self):
"""Clears the completion.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.grading.GradeSystemFo... | [
"def",
"clear_completion",
"(",
"self",
")",
":",
"# Implemented from template for osid.grading.GradeSystemForm.clear_lowest_numeric_score",
"if",
"(",
"self",
".",
"get_completion_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
"or",
"self",
".",
"get_completion_metada... | Clears the completion.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | [
"Clears",
"the",
"completion",
"."
] | python | train | 43 |
numenta/htmresearch | projects/combined_sequences/generate_plots.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/generate_plots.py#L42-L74 | def plotOneInferenceRun(stats,
fields,
basename,
itemType="",
plotDir="plots",
ymax=100,
trialNumber=0):
"""
Plots individual inference runs.
"""
if not os.path.exists(... | [
"def",
"plotOneInferenceRun",
"(",
"stats",
",",
"fields",
",",
"basename",
",",
"itemType",
"=",
"\"\"",
",",
"plotDir",
"=",
"\"plots\"",
",",
"ymax",
"=",
"100",
",",
"trialNumber",
"=",
"0",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
... | Plots individual inference runs. | [
"Plots",
"individual",
"inference",
"runs",
"."
] | python | train | 25.515152 |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L1100-L1106 | def record_close(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /record-xxxx/close API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Data-Object-Lifecycle#API-method%3A-%2Fclass-xxxx%2Fclose
"""
return DXHTTPRequest('/%s/close' % object_id... | [
"def",
"record_close",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/close'",
"%",
"object_id",
",",
"input_params",
",",
"always_retry",
"=",
... | Invokes the /record-xxxx/close API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Data-Object-Lifecycle#API-method%3A-%2Fclass-xxxx%2Fclose | [
"Invokes",
"the",
"/",
"record",
"-",
"xxxx",
"/",
"close",
"API",
"method",
"."
] | python | train | 52.285714 |
erdewit/ib_insync | ib_insync/ib.py | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/ib.py#L456-L465 | def ticker(self, contract: Contract) -> Ticker:
"""
Get ticker of the given contract. It must have been requested before
with reqMktData with the same contract object. The ticker may not be
ready yet if called directly after :meth:`.reqMktData`.
Args:
contract: Contr... | [
"def",
"ticker",
"(",
"self",
",",
"contract",
":",
"Contract",
")",
"->",
"Ticker",
":",
"return",
"self",
".",
"wrapper",
".",
"tickers",
".",
"get",
"(",
"id",
"(",
"contract",
")",
")"
] | Get ticker of the given contract. It must have been requested before
with reqMktData with the same contract object. The ticker may not be
ready yet if called directly after :meth:`.reqMktData`.
Args:
contract: Contract to get ticker for. | [
"Get",
"ticker",
"of",
"the",
"given",
"contract",
".",
"It",
"must",
"have",
"been",
"requested",
"before",
"with",
"reqMktData",
"with",
"the",
"same",
"contract",
"object",
".",
"The",
"ticker",
"may",
"not",
"be",
"ready",
"yet",
"if",
"called",
"direc... | python | train | 39.9 |
bhmm/bhmm | bhmm/_external/sklearn/utils.py | https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/utils.py#L229-L329 | def check_array(array, accept_sparse=None, dtype="numeric", order=None,
copy=False, force_all_finite=True, ensure_2d=True,
allow_nd=False, ensure_min_samples=1, ensure_min_features=1):
"""Input validation on an array, list, sparse matrix or similar.
By default, the input is conv... | [
"def",
"check_array",
"(",
"array",
",",
"accept_sparse",
"=",
"None",
",",
"dtype",
"=",
"\"numeric\"",
",",
"order",
"=",
"None",
",",
"copy",
"=",
"False",
",",
"force_all_finite",
"=",
"True",
",",
"ensure_2d",
"=",
"True",
",",
"allow_nd",
"=",
"Fal... | Input validation on an array, list, sparse matrix or similar.
By default, the input is converted to an at least 2nd numpy array.
If the dtype of the array is object, attempt converting to float,
raising on failure.
Parameters
----------
array : object
Input object to check / convert.
... | [
"Input",
"validation",
"on",
"an",
"array",
"list",
"sparse",
"matrix",
"or",
"similar",
"."
] | python | train | 40.188119 |
ronhanson/python-tbx | tbx/network.py | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/network.py#L111-L121 | def send_by_packet(self, data):
"""
Send data by packet on socket
"""
total_sent = 0
while total_sent < PACKET_SIZE:
sent = self.sock.send(data[total_sent:])
if sent == 0:
raise RuntimeError("socket connection broken")
total_sen... | [
"def",
"send_by_packet",
"(",
"self",
",",
"data",
")",
":",
"total_sent",
"=",
"0",
"while",
"total_sent",
"<",
"PACKET_SIZE",
":",
"sent",
"=",
"self",
".",
"sock",
".",
"send",
"(",
"data",
"[",
"total_sent",
":",
"]",
")",
"if",
"sent",
"==",
"0"... | Send data by packet on socket | [
"Send",
"data",
"by",
"packet",
"on",
"socket"
] | python | train | 31.363636 |
ramrod-project/database-brain | schema/brain/checks.py | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L55-L64 | def special_target_typecheck(value):
"""
Special type checking for the target object
:param value: <dict>
:return: <bool>
"""
result = True
# if key:Optional exists, it must be a dict object
result &= isinstance(value.get(TARGET_OPTIONAL_FIELD, dict()), dict)
return result | [
"def",
"special_target_typecheck",
"(",
"value",
")",
":",
"result",
"=",
"True",
"# if key:Optional exists, it must be a dict object",
"result",
"&=",
"isinstance",
"(",
"value",
".",
"get",
"(",
"TARGET_OPTIONAL_FIELD",
",",
"dict",
"(",
")",
")",
",",
"dict",
"... | Special type checking for the target object
:param value: <dict>
:return: <bool> | [
"Special",
"type",
"checking",
"for",
"the",
"target",
"object",
":",
"param",
"value",
":",
"<dict",
">",
":",
"return",
":",
"<bool",
">"
] | python | train | 30 |
useblocks/groundwork | groundwork/patterns/gw_shared_objects_pattern.py | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_shared_objects_pattern.py#L172-L191 | def register(self, name, description, obj, plugin):
"""
Registers a new shared object.
:param name: Unique name for shared object
:type name: str
:param description: Description of shared object
:type description: str
:param obj: The object, which shall be shared... | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"description",
",",
"obj",
",",
"plugin",
")",
":",
"if",
"name",
"in",
"self",
".",
"_shared_objects",
".",
"keys",
"(",
")",
":",
"raise",
"SharedObjectExistException",
"(",
"\"Shared Object %s already regist... | Registers a new shared object.
:param name: Unique name for shared object
:type name: str
:param description: Description of shared object
:type description: str
:param obj: The object, which shall be shared
:type obj: any type
:param plugin: Plugin, which regist... | [
"Registers",
"a",
"new",
"shared",
"object",
"."
] | python | train | 43.3 |
pymc-devs/pymc | pymc/database/txt.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/txt.py#L198-L209 | def funname(file):
"""Return variable names from file names."""
if isinstance(file, str):
files = [file]
else:
files = file
bases = [os.path.basename(f) for f in files]
names = [os.path.splitext(b)[0] for b in bases]
if isinstance(file, str):
return names[0]
else:
... | [
"def",
"funname",
"(",
"file",
")",
":",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"files",
"=",
"[",
"file",
"]",
"else",
":",
"files",
"=",
"file",
"bases",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
"for",
"f",... | Return variable names from file names. | [
"Return",
"variable",
"names",
"from",
"file",
"names",
"."
] | python | train | 27.166667 |
saltstack/salt | salt/utils/locales.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/locales.py#L86-L99 | def join_locale(comps):
'''
Join a locale specifier split in the format returned by split_locale.
'''
loc = comps['language']
if comps.get('territory'):
loc += '_' + comps['territory']
if comps.get('codeset'):
loc += '.' + comps['codeset']
if comps.get('modifier'):
lo... | [
"def",
"join_locale",
"(",
"comps",
")",
":",
"loc",
"=",
"comps",
"[",
"'language'",
"]",
"if",
"comps",
".",
"get",
"(",
"'territory'",
")",
":",
"loc",
"+=",
"'_'",
"+",
"comps",
"[",
"'territory'",
"]",
"if",
"comps",
".",
"get",
"(",
"'codeset'"... | Join a locale specifier split in the format returned by split_locale. | [
"Join",
"a",
"locale",
"specifier",
"split",
"in",
"the",
"format",
"returned",
"by",
"split_locale",
"."
] | python | train | 29.785714 |
Accelize/pycosio | pycosio/_core/io_file_system.py | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_file_system.py#L13-L82 | def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only fi... | [
"def",
"list_objects",
"(",
"self",
",",
"path",
"=",
"''",
",",
"relative",
"=",
"False",
",",
"first_level",
"=",
"False",
",",
"max_request_entries",
"=",
"None",
")",
":",
"entries",
"=",
"0",
"next_values",
"=",
"[",
"]",
"max_request_entries_arg",
"=... | List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries return... | [
"List",
"objects",
"."
] | python | train | 32.328571 |
wright-group/WrightTools | WrightTools/_dataset.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L190-L208 | def argmax(self):
"""Index of the maximum, ignorning nans."""
if "argmax" not in self.attrs.keys():
def f(dataset, s):
arr = dataset[s]
try:
amin = np.nanargmax(arr)
except ValueError:
amin = 0
... | [
"def",
"argmax",
"(",
"self",
")",
":",
"if",
"\"argmax\"",
"not",
"in",
"self",
".",
"attrs",
".",
"keys",
"(",
")",
":",
"def",
"f",
"(",
"dataset",
",",
"s",
")",
":",
"arr",
"=",
"dataset",
"[",
"s",
"]",
"try",
":",
"amin",
"=",
"np",
".... | Index of the maximum, ignorning nans. | [
"Index",
"of",
"the",
"maximum",
"ignorning",
"nans",
"."
] | python | train | 38.368421 |
rkcosmos/deepcut | deepcut/train.py | https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L204-L217 | def evaluate(best_processed_path, model):
"""
Evaluate model on splitted 10 percent testing set
"""
x_test_char, x_test_type, y_test = prepare_feature(best_processed_path, option='test')
y_predict = model.predict([x_test_char, x_test_type])
y_predict = (y_predict.ravel() > 0.5).astype(int)
... | [
"def",
"evaluate",
"(",
"best_processed_path",
",",
"model",
")",
":",
"x_test_char",
",",
"x_test_type",
",",
"y_test",
"=",
"prepare_feature",
"(",
"best_processed_path",
",",
"option",
"=",
"'test'",
")",
"y_predict",
"=",
"model",
".",
"predict",
"(",
"[",... | Evaluate model on splitted 10 percent testing set | [
"Evaluate",
"model",
"on",
"splitted",
"10",
"percent",
"testing",
"set"
] | python | valid | 34.285714 |
hvac/hvac | hvac/api/system_backend/key.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/system_backend/key.py#L100-L113 | def get_encryption_key_status(self):
"""Read information about the current encryption key used by Vault.
Supported methods:
GET: /sys/key-status. Produces: 200 application/json
:return: JSON response with information regarding the current encryption key used by Vault.
:rtyp... | [
"def",
"get_encryption_key_status",
"(",
"self",
")",
":",
"api_path",
"=",
"'/v1/sys/key-status'",
"response",
"=",
"self",
".",
"_adapter",
".",
"get",
"(",
"url",
"=",
"api_path",
",",
")",
"return",
"response",
".",
"json",
"(",
")"
] | Read information about the current encryption key used by Vault.
Supported methods:
GET: /sys/key-status. Produces: 200 application/json
:return: JSON response with information regarding the current encryption key used by Vault.
:rtype: dict | [
"Read",
"information",
"about",
"the",
"current",
"encryption",
"key",
"used",
"by",
"Vault",
"."
] | python | train | 33.642857 |
saghul/evergreen | evergreen/core/loop.py | https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/core/loop.py#L109-L119 | def current(cls):
"""Get the current event loop singleton object.
"""
try:
return _tls.loop
except AttributeError:
# create loop only for main thread
if threading.current_thread().name == 'MainThread':
_tls.loop = cls()
... | [
"def",
"current",
"(",
"cls",
")",
":",
"try",
":",
"return",
"_tls",
".",
"loop",
"except",
"AttributeError",
":",
"# create loop only for main thread",
"if",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
"==",
"'MainThread'",
":",
"_tls",
".",
... | Get the current event loop singleton object. | [
"Get",
"the",
"current",
"event",
"loop",
"singleton",
"object",
"."
] | python | train | 37.545455 |
datastore/datastore | datastore/core/query.py | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L69-L83 | def offset_gen(offset, iterable, skip_signal=None):
'''A generator that applies an `offset`, skipping `offset` elements from
`iterable`. If skip_signal is a callable, it will be called with every
skipped element.
'''
offset = int(offset)
assert offset >= 0, 'negative offset'
for item in iterable:
if ... | [
"def",
"offset_gen",
"(",
"offset",
",",
"iterable",
",",
"skip_signal",
"=",
"None",
")",
":",
"offset",
"=",
"int",
"(",
"offset",
")",
"assert",
"offset",
">=",
"0",
",",
"'negative offset'",
"for",
"item",
"in",
"iterable",
":",
"if",
"offset",
">",
... | A generator that applies an `offset`, skipping `offset` elements from
`iterable`. If skip_signal is a callable, it will be called with every
skipped element. | [
"A",
"generator",
"that",
"applies",
"an",
"offset",
"skipping",
"offset",
"elements",
"from",
"iterable",
".",
"If",
"skip_signal",
"is",
"a",
"callable",
"it",
"will",
"be",
"called",
"with",
"every",
"skipped",
"element",
"."
] | python | train | 28 |
Contraz/demosys-py | demosys/project/base.py | https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/project/base.py#L163-L172 | def _add_resource_descriptions_to_pools(self, meta_list):
"""
Takes a list of resource descriptions adding them
to the resource pool they belong to scheduling them for loading.
"""
if not meta_list:
return
for meta in meta_list:
getattr(r... | [
"def",
"_add_resource_descriptions_to_pools",
"(",
"self",
",",
"meta_list",
")",
":",
"if",
"not",
"meta_list",
":",
"return",
"for",
"meta",
"in",
"meta_list",
":",
"getattr",
"(",
"resources",
",",
"meta",
".",
"resource_type",
")",
".",
"add",
"(",
"meta... | Takes a list of resource descriptions adding them
to the resource pool they belong to scheduling them for loading. | [
"Takes",
"a",
"list",
"of",
"resource",
"descriptions",
"adding",
"them",
"to",
"the",
"resource",
"pool",
"they",
"belong",
"to",
"scheduling",
"them",
"for",
"loading",
"."
] | python | valid | 35 |
google/grr | grr/server/grr_response_server/client_report_utils.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/client_report_utils.py#L168-L193 | def FetchMostRecentGraphSeries(label,
report_type,
token = None
):
"""Fetches the latest graph series for a client label from the DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSe... | [
"def",
"FetchMostRecentGraphSeries",
"(",
"label",
",",
"report_type",
",",
"token",
"=",
"None",
")",
":",
"if",
"_ShouldUseLegacyDatastore",
"(",
")",
":",
"return",
"_FetchMostRecentGraphSeriesFromTheLegacyDB",
"(",
"label",
",",
"report_type",
",",
"token",
"=",... | Fetches the latest graph series for a client label from the DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for.
token: ACL token to use for reading from the legacy (non-relational)
datastore.
Raises:
AFF4AttributeTypeError: ... | [
"Fetches",
"the",
"latest",
"graph",
"series",
"for",
"a",
"client",
"label",
"from",
"the",
"DB",
"."
] | python | train | 35.730769 |
python-odin/odinweb | odinweb/data_structures.py | https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/data_structures.py#L404-L417 | def format(self, node_formatter=None, separator='/'):
# type: (Optional[Callable[[PathParam], str]]) -> str
"""
Format a URL path.
An optional `node_parser(PathNode)` can be supplied for converting a
`PathNode` into a string to support the current web framework.
... | [
"def",
"format",
"(",
"self",
",",
"node_formatter",
"=",
"None",
",",
"separator",
"=",
"'/'",
")",
":",
"# type: (Optional[Callable[[PathParam], str]]) -> str",
"if",
"self",
".",
"_nodes",
"==",
"(",
"''",
",",
")",
":",
"return",
"separator",
"else",
":",
... | Format a URL path.
An optional `node_parser(PathNode)` can be supplied for converting a
`PathNode` into a string to support the current web framework. | [
"Format",
"a",
"URL",
"path",
".",
"An",
"optional",
"node_parser",
"(",
"PathNode",
")",
"can",
"be",
"supplied",
"for",
"converting",
"a",
"PathNode",
"into",
"a",
"string",
"to",
"support",
"the",
"current",
"web",
"framework",
"."
] | python | train | 41.571429 |
codeinn/vcs | vcs/utils/helpers.py | https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/utils/helpers.py#L112-L119 | def run_command(cmd, *args):
"""
Runs command on the system with given ``args``.
"""
command = ' '.join((cmd, args))
p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
return p.retcode, stdout, stderr | [
"def",
"run_command",
"(",
"cmd",
",",
"*",
"args",
")",
":",
"command",
"=",
"' '",
".",
"join",
"(",
"(",
"cmd",
",",
"args",
")",
")",
"p",
"=",
"Popen",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"... | Runs command on the system with given ``args``. | [
"Runs",
"command",
"on",
"the",
"system",
"with",
"given",
"args",
"."
] | python | train | 32.5 |
singularitti/scientific-string | scientific_string/strings.py | https://github.com/singularitti/scientific-string/blob/615dca747e8fb1e89ed1d9f18aef4066295a17a9/scientific_string/strings.py#L93-L120 | def string_to_general_float(s: str) -> float:
"""
Convert a string to corresponding single or double precision scientific number.
:param s: a string could be '0.1', '1e-5', '1.0D-5', or any other validated number
:return: a float or raise an error
.. doctest::
>>> string_to_general_float(... | [
"def",
"string_to_general_float",
"(",
"s",
":",
"str",
")",
"->",
"float",
":",
"if",
"'D'",
"in",
"s",
".",
"upper",
"(",
")",
":",
"# Possible double precision number",
"try",
":",
"return",
"string_to_double_precision_float",
"(",
"s",
")",
"except",
"Valu... | Convert a string to corresponding single or double precision scientific number.
:param s: a string could be '0.1', '1e-5', '1.0D-5', or any other validated number
:return: a float or raise an error
.. doctest::
>>> string_to_general_float('1.0D-5')
1e-05
>>> string_to_general_floa... | [
"Convert",
"a",
"string",
"to",
"corresponding",
"single",
"or",
"double",
"precision",
"scientific",
"number",
"."
] | python | train | 33.821429 |
gboeing/osmnx | osmnx/plot.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/plot.py#L100-L115 | def rgb_color_list_to_hex(color_list):
"""
Convert a list of RGBa colors to a list of hexadecimal color codes.
Parameters
----------
color_list : list
the list of RGBa colors
Returns
-------
color_list_hex : list
"""
color_list_rgb = [[int(x*255) for x in c[0:3]] for c ... | [
"def",
"rgb_color_list_to_hex",
"(",
"color_list",
")",
":",
"color_list_rgb",
"=",
"[",
"[",
"int",
"(",
"x",
"*",
"255",
")",
"for",
"x",
"in",
"c",
"[",
"0",
":",
"3",
"]",
"]",
"for",
"c",
"in",
"color_list",
"]",
"color_list_hex",
"=",
"[",
"'... | Convert a list of RGBa colors to a list of hexadecimal color codes.
Parameters
----------
color_list : list
the list of RGBa colors
Returns
-------
color_list_hex : list | [
"Convert",
"a",
"list",
"of",
"RGBa",
"colors",
"to",
"a",
"list",
"of",
"hexadecimal",
"color",
"codes",
"."
] | python | train | 27.9375 |
KelSolaar/Umbra | umbra/components/addons/projects_explorer/projects_explorer.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/addons/projects_explorer/projects_explorer.py#L563-L572 | def __remove_actions(self):
"""
Removes actions.
"""
LOGGER.debug("> Removing '{0}' Component actions.".format(self.__class__.__name__))
remove_project_action = "Actions|Umbra|Components|factory.script_editor|&File|Remove Project"
self.__script_editor.command_menu.remov... | [
"def",
"__remove_actions",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Removing '{0}' Component actions.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"remove_project_action",
"=",
"\"Actions|Umbra|Components|factory.script_ed... | Removes actions. | [
"Removes",
"actions",
"."
] | python | train | 46.2 |
haikuginger/beekeeper | beekeeper/hive.py | https://github.com/haikuginger/beekeeper/blob/b647d3add0b407ec5dc3a2a39c4f6dac31243b18/beekeeper/hive.py#L32-L40 | def from_file(cls, fname, version=None, require_https=True):
"""
Create a Hive object based on JSON located in a local file.
"""
if os.path.exists(fname):
with open(fname) as hive_file:
return cls(**json.load(hive_file)).from_version(version, require_https=req... | [
"def",
"from_file",
"(",
"cls",
",",
"fname",
",",
"version",
"=",
"None",
",",
"require_https",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"hive_file",
":",
"retu... | Create a Hive object based on JSON located in a local file. | [
"Create",
"a",
"Hive",
"object",
"based",
"on",
"JSON",
"located",
"in",
"a",
"local",
"file",
"."
] | python | train | 41.555556 |
google/grr | grr/client/grr_response_client/client_actions/artifact_collector.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/artifact_collector.py#L227-L252 | def _ProcessArtifactFilesSource(self, source):
"""Get artifact responses, extract paths and send corresponding files."""
if source.path_type != rdf_paths.PathSpec.PathType.OS:
raise ValueError("Only supported path type is OS.")
# TODO(user): Check paths for GlobExpressions.
# If it contains a * ... | [
"def",
"_ProcessArtifactFilesSource",
"(",
"self",
",",
"source",
")",
":",
"if",
"source",
".",
"path_type",
"!=",
"rdf_paths",
".",
"PathSpec",
".",
"PathType",
".",
"OS",
":",
"raise",
"ValueError",
"(",
"\"Only supported path type is OS.\"",
")",
"# TODO(user)... | Get artifact responses, extract paths and send corresponding files. | [
"Get",
"artifact",
"responses",
"extract",
"paths",
"and",
"send",
"corresponding",
"files",
"."
] | python | train | 40.5 |
tk0miya/tk.phpautodoc | src/phply/phpparse.py | https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L1277-L1283 | def p_static_non_empty_array_pair_list_pair(p):
'''static_non_empty_array_pair_list : static_non_empty_array_pair_list COMMA static_scalar DOUBLE_ARROW static_scalar
| static_scalar DOUBLE_ARROW static_scalar'''
if len(p) == 6:
p[0] = p[1] + [ast.ArrayElement(p[3]... | [
"def",
"p_static_non_empty_array_pair_list_pair",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"6",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"ast",
".",
"ArrayElement",
"(",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
... | static_non_empty_array_pair_list : static_non_empty_array_pair_list COMMA static_scalar DOUBLE_ARROW static_scalar
| static_scalar DOUBLE_ARROW static_scalar | [
"static_non_empty_array_pair_list",
":",
"static_non_empty_array_pair_list",
"COMMA",
"static_scalar",
"DOUBLE_ARROW",
"static_scalar",
"|",
"static_scalar",
"DOUBLE_ARROW",
"static_scalar"
] | python | train | 61.714286 |
python-diamond/Diamond | src/collectors/redisstat/redisstat.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L209-L227 | def _client(self, host, port, unix_socket, auth):
"""Return a redis client for the configuration.
:param str host: redis host
:param int port: redis port
:rtype: redis.Redis
"""
db = int(self.config['db'])
timeout = int(self.config['timeout'])
try:
cli = redis.Redis... | [
"def",
"_client",
"(",
"self",
",",
"host",
",",
"port",
",",
"unix_socket",
",",
"auth",
")",
":",
"db",
"=",
"int",
"(",
"self",
".",
"config",
"[",
"'db'",
"]",
")",
"timeout",
"=",
"int",
"(",
"self",
".",
"config",
"[",
"'timeout'",
"]",
")"... | Return a redis client for the configuration.
:param str host: redis host
:param int port: redis port
:rtype: redis.Redis | [
"Return",
"a",
"redis",
"client",
"for",
"the",
"configuration",
"."
] | python | train | 35.473684 |
threeML/astromodels | astromodels/functions/function.py | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/functions/function.py#L1648-L1825 | def _parse_function_expression(function_specification):
"""
Parse a complex function expression like:
((((powerlaw{1} + (sin{2} * 3)) + (sin{2} * 25)) - (powerlaw{1} * 16)) + (sin{2} ** 3.0))
and return a composite function instance
:param function_specification:
:return: a composite function... | [
"def",
"_parse_function_expression",
"(",
"function_specification",
")",
":",
"# NOTE FOR SECURITY",
"# This function has some security concerns. Security issues could arise if the user tries to read a model",
"# file which has been maliciously formatted to contain harmful code. In this function we ... | Parse a complex function expression like:
((((powerlaw{1} + (sin{2} * 3)) + (sin{2} * 25)) - (powerlaw{1} * 16)) + (sin{2} ** 3.0))
and return a composite function instance
:param function_specification:
:return: a composite function instance | [
"Parse",
"a",
"complex",
"function",
"expression",
"like",
":"
] | python | train | 42.320225 |
guaix-ucm/numina | numina/frame/combine.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/frame/combine.py#L185-L208 | def manage_fits(list_of_frame):
"""Manage a list of FITS resources"""
import astropy.io.fits as fits
import numina.types.dataframe as df
refs = []
for frame in list_of_frame:
if isinstance(frame, str):
ref = fits.open(frame)
refs.append(ref)
elif isinstance(... | [
"def",
"manage_fits",
"(",
"list_of_frame",
")",
":",
"import",
"astropy",
".",
"io",
".",
"fits",
"as",
"fits",
"import",
"numina",
".",
"types",
".",
"dataframe",
"as",
"df",
"refs",
"=",
"[",
"]",
"for",
"frame",
"in",
"list_of_frame",
":",
"if",
"i... | Manage a list of FITS resources | [
"Manage",
"a",
"list",
"of",
"FITS",
"resources"
] | python | train | 25.333333 |
welbornprod/colr | colr/controls.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/controls.py#L311-L317 | def scroll_down(lines=1, file=sys.stdout):
""" Scroll the whole page down a number of lines, new lines are added to
the top.
Esc[<lines>T
"""
scroll.down(lines).write(file=file) | [
"def",
"scroll_down",
"(",
"lines",
"=",
"1",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"scroll",
".",
"down",
"(",
"lines",
")",
".",
"write",
"(",
"file",
"=",
"file",
")"
] | Scroll the whole page down a number of lines, new lines are added to
the top.
Esc[<lines>T | [
"Scroll",
"the",
"whole",
"page",
"down",
"a",
"number",
"of",
"lines",
"new",
"lines",
"are",
"added",
"to",
"the",
"top",
"."
] | python | train | 28.571429 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/aws/sns.py | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L43-L68 | def publish_table_notification(table_key, message, message_types, subject=None):
""" Publish a notification for a specific table
:type table_key: str
:param table_key: Table configuration option key name
:type message: str
:param message: Message to send via SNS
:type message_types: list
:p... | [
"def",
"publish_table_notification",
"(",
"table_key",
",",
"message",
",",
"message_types",
",",
"subject",
"=",
"None",
")",
":",
"topic",
"=",
"get_table_option",
"(",
"table_key",
",",
"'sns_topic_arn'",
")",
"if",
"not",
"topic",
":",
"return",
"for",
"me... | Publish a notification for a specific table
:type table_key: str
:param table_key: Table configuration option key name
:type message: str
:param message: Message to send via SNS
:type message_types: list
:param message_types:
List with types:
- scale-up
- scale-down
... | [
"Publish",
"a",
"notification",
"for",
"a",
"specific",
"table"
] | python | train | 31.730769 |
coursera-dl/coursera-dl | coursera/cookies.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L350-L372 | def get_cookies_for_class(session, class_name,
cookies_file=None,
username=None,
password=None):
"""
Get the cookies for the given class.
We do not validate the cookies if they are loaded from a cookies file
because this is i... | [
"def",
"get_cookies_for_class",
"(",
"session",
",",
"class_name",
",",
"cookies_file",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"cookies_file",
":",
"cookies",
"=",
"find_cookies_for_class",
"(",
"cookies_file",
... | Get the cookies for the given class.
We do not validate the cookies if they are loaded from a cookies file
because this is intended for debugging purposes or if the coursera
authentication process has changed. | [
"Get",
"the",
"cookies",
"for",
"the",
"given",
"class",
"."
] | python | train | 40.956522 |
sigsep/sigsep-mus-eval | museval/metrics.py | https://github.com/sigsep/sigsep-mus-eval/blob/a7c9af3647f0c0bb9bbaeccec0b1a6a9e09d1e2d/museval/metrics.py#L410-L426 | def bss_eval_images_framewise(reference_sources, estimated_sources,
window=30 * 44100, hop=15 * 44100,
compute_permutation=False):
"""
BSS Eval v3 bss_eval_images_framewise
Framewise computation of bss_eval_images.
Wrapper to ``bss_eval`` with... | [
"def",
"bss_eval_images_framewise",
"(",
"reference_sources",
",",
"estimated_sources",
",",
"window",
"=",
"30",
"*",
"44100",
",",
"hop",
"=",
"15",
"*",
"44100",
",",
"compute_permutation",
"=",
"False",
")",
":",
"return",
"bss_eval",
"(",
"reference_sources... | BSS Eval v3 bss_eval_images_framewise
Framewise computation of bss_eval_images.
Wrapper to ``bss_eval`` with the right parameters. | [
"BSS",
"Eval",
"v3",
"bss_eval_images_framewise"
] | python | train | 33.882353 |
spacetelescope/stsci.tools | lib/stsci/tools/basicpar.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/basicpar.py#L930-L960 | def get(self, field=None, index=None, lpar=0, prompt=1, native=0, mode="h"):
"""Return value of this parameter as a string (or in native format
if native is non-zero.)"""
if field: return self._getField(field,native=native,prompt=prompt)
# may prompt for value if prompt flag is set
... | [
"def",
"get",
"(",
"self",
",",
"field",
"=",
"None",
",",
"index",
"=",
"None",
",",
"lpar",
"=",
"0",
",",
"prompt",
"=",
"1",
",",
"native",
"=",
"0",
",",
"mode",
"=",
"\"h\"",
")",
":",
"if",
"field",
":",
"return",
"self",
".",
"_getField... | Return value of this parameter as a string (or in native format
if native is non-zero.) | [
"Return",
"value",
"of",
"this",
"parameter",
"as",
"a",
"string",
"(",
"or",
"in",
"native",
"format",
"if",
"native",
"is",
"non",
"-",
"zero",
".",
")"
] | python | train | 40.16129 |
python-odin/odinweb | odinweb/cors.py | https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/cors.py#L166-L173 | def post_request(self, request, response):
# type: (BaseHttpRequest, HttpResponse) -> HttpResponse
"""
Post-request hook to allow CORS headers to responses.
"""
if request.method != api.Method.OPTIONS:
response.headers.update(self.request_headers(request))
ret... | [
"def",
"post_request",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"# type: (BaseHttpRequest, HttpResponse) -> HttpResponse",
"if",
"request",
".",
"method",
"!=",
"api",
".",
"Method",
".",
"OPTIONS",
":",
"response",
".",
"headers",
".",
"update",
... | Post-request hook to allow CORS headers to responses. | [
"Post",
"-",
"request",
"hook",
"to",
"allow",
"CORS",
"headers",
"to",
"responses",
"."
] | python | train | 40.625 |
census-instrumentation/opencensus-python | contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/__init__.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-ocagent/opencensus/ext/ocagent/trace_exporter/__init__.py#L113-L134 | def generate_span_requests(self, span_datas):
"""Span request generator.
:type span_datas: list of
:class:`~opencensus.trace.span_data.SpanData`
:param span_datas: SpanData tuples to convert to protobuf spans
and send to opensensusd agent
... | [
"def",
"generate_span_requests",
"(",
"self",
",",
"span_datas",
")",
":",
"pb_spans",
"=",
"[",
"utils",
".",
"translate_to_trace_proto",
"(",
"span_data",
")",
"for",
"span_data",
"in",
"span_datas",
"]",
"# TODO: send node once per channel",
"yield",
"trace_service... | Span request generator.
:type span_datas: list of
:class:`~opencensus.trace.span_data.SpanData`
:param span_datas: SpanData tuples to convert to protobuf spans
and send to opensensusd agent
:rtype: list of
`~gen.opencensus.age... | [
"Span",
"request",
"generator",
"."
] | python | train | 34.409091 |
glomex/gcdt | gcdt/ramuda_core.py | https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/ramuda_core.py#L419-L450 | def get_metrics(awsclient, name):
"""Print out cloudformation metrics for a lambda function.
:param awsclient
:param name: name of the lambda function
:return: exit_code
"""
metrics = ['Duration', 'Errors', 'Invocations', 'Throttles']
client_cw = awsclient.get_client('cloudwatch')
for m... | [
"def",
"get_metrics",
"(",
"awsclient",
",",
"name",
")",
":",
"metrics",
"=",
"[",
"'Duration'",
",",
"'Errors'",
",",
"'Invocations'",
",",
"'Throttles'",
"]",
"client_cw",
"=",
"awsclient",
".",
"get_client",
"(",
"'cloudwatch'",
")",
"for",
"metric",
"in... | Print out cloudformation metrics for a lambda function.
:param awsclient
:param name: name of the lambda function
:return: exit_code | [
"Print",
"out",
"cloudformation",
"metrics",
"for",
"a",
"lambda",
"function",
"."
] | python | train | 32.59375 |
pgmpy/pgmpy | pgmpy/sampling/HMC.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/HMC.py#L152-L183 | def _sample(self, position, trajectory_length, stepsize, lsteps=None):
"""
Runs a single sampling iteration to return a sample
"""
# Resampling momentum
momentum = np.reshape(np.random.normal(0, 1, len(position)), position.shape)
# position_m here will be the previous sa... | [
"def",
"_sample",
"(",
"self",
",",
"position",
",",
"trajectory_length",
",",
"stepsize",
",",
"lsteps",
"=",
"None",
")",
":",
"# Resampling momentum",
"momentum",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
... | Runs a single sampling iteration to return a sample | [
"Runs",
"a",
"single",
"sampling",
"iteration",
"to",
"return",
"a",
"sample"
] | python | train | 40.53125 |
gebn/nibble | nibble/decorators.py | https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/decorators.py#L65-L79 | def python_2_nonzero_compatible(klass):
"""
Adds a `__nonzero__()` method to classes that define a `__bool__()` method,
so boolean conversion works in Python 2. Has no effect in Python 3.
:param klass: The class to modify. Must define `__bool__()`.
:return: The possibly patched class.
"""
i... | [
"def",
"python_2_nonzero_compatible",
"(",
"klass",
")",
":",
"if",
"six",
".",
"PY2",
":",
"if",
"'__bool__'",
"not",
"in",
"klass",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"'@python_2_nonzero_compatible cannot be applied to {0} because '",
"'it doesn\\'t def... | Adds a `__nonzero__()` method to classes that define a `__bool__()` method,
so boolean conversion works in Python 2. Has no effect in Python 3.
:param klass: The class to modify. Must define `__bool__()`.
:return: The possibly patched class. | [
"Adds",
"a",
"__nonzero__",
"()",
"method",
"to",
"classes",
"that",
"define",
"a",
"__bool__",
"()",
"method",
"so",
"boolean",
"conversion",
"works",
"in",
"Python",
"2",
".",
"Has",
"no",
"effect",
"in",
"Python",
"3",
"."
] | python | train | 40.333333 |
coin-or/GiMPy | src/gimpy/graph.py | https://github.com/coin-or/GiMPy/blob/51853122a50eb6019d06bbdedbfc396a833b5a22/src/gimpy/graph.py#L2349-L2403 | def simplex_determine_leaving_arc(self, t, k, l):
'''
API:
simplex_determine_leaving_arc(self, t, k, l)
Description:
Determines and returns the leaving arc.
Input:
t: current spanning tree solution.
k: tail of the entering arc.
... | [
"def",
"simplex_determine_leaving_arc",
"(",
"self",
",",
"t",
",",
"k",
",",
"l",
")",
":",
"# k,l are the first two elements of the cycle",
"cycle",
"=",
"self",
".",
"simplex_identify_cycle",
"(",
"t",
",",
"k",
",",
"l",
")",
"flow_kl",
"=",
"self",
".",
... | API:
simplex_determine_leaving_arc(self, t, k, l)
Description:
Determines and returns the leaving arc.
Input:
t: current spanning tree solution.
k: tail of the entering arc.
l: head of the entering arc.
Return:
Returns the t... | [
"API",
":",
"simplex_determine_leaving_arc",
"(",
"self",
"t",
"k",
"l",
")",
"Description",
":",
"Determines",
"and",
"returns",
"the",
"leaving",
"arc",
".",
"Input",
":",
"t",
":",
"current",
"spanning",
"tree",
"solution",
".",
"k",
":",
"tail",
"of",
... | python | train | 41.363636 |
lsst-sqre/lsst-projectmeta-kit | lsstprojectmeta/tex/lsstdoc.py | https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/tex/lsstdoc.py#L48-L73 | def read(cls, root_tex_path):
"""Construct an `LsstLatexDoc` instance by reading and parsing the
LaTeX source.
Parameters
----------
root_tex_path : `str`
Path to the LaTeX source on the filesystem. For multi-file LaTeX
projects this should be the path to... | [
"def",
"read",
"(",
"cls",
",",
"root_tex_path",
")",
":",
"# Read and normalize the TeX source, replacing macros with content",
"root_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"root_tex_path",
")",
"tex_source",
"=",
"read_tex_file",
"(",
"root_tex_path",
")... | Construct an `LsstLatexDoc` instance by reading and parsing the
LaTeX source.
Parameters
----------
root_tex_path : `str`
Path to the LaTeX source on the filesystem. For multi-file LaTeX
projects this should be the path to the root document.
Notes
... | [
"Construct",
"an",
"LsstLatexDoc",
"instance",
"by",
"reading",
"and",
"parsing",
"the",
"LaTeX",
"source",
"."
] | python | valid | 38.038462 |
angr/angr | angr/analyses/cfg/cfg_fast.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_fast.py#L2750-L2765 | def _graph_add_edge(self, cfg_node, src_node, src_jumpkind, src_ins_addr, src_stmt_idx):
"""
Add edge between nodes, or add node if entry point
:param CFGNode cfg_node: node which is jumped to
:param CFGNode src_node: node which is jumped from none if entry point
:param str src_... | [
"def",
"_graph_add_edge",
"(",
"self",
",",
"cfg_node",
",",
"src_node",
",",
"src_jumpkind",
",",
"src_ins_addr",
",",
"src_stmt_idx",
")",
":",
"if",
"src_node",
"is",
"None",
":",
"self",
".",
"graph",
".",
"add_node",
"(",
"cfg_node",
")",
"else",
":",... | Add edge between nodes, or add node if entry point
:param CFGNode cfg_node: node which is jumped to
:param CFGNode src_node: node which is jumped from none if entry point
:param str src_jumpkind: what type of jump the edge takes
:param int or str src_stmt_idx: source statements ID
... | [
"Add",
"edge",
"between",
"nodes",
"or",
"add",
"node",
"if",
"entry",
"point"
] | python | train | 42.5625 |
djgagne/hagelslag | hagelslag/evaluation/ProbabilityMetrics.py | https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/evaluation/ProbabilityMetrics.py#L455-L473 | def update(self, forecasts, observations):
"""
Update the statistics with forecasts and observations.
Args:
forecasts: The discrete Cumulative Distribution Functions of
observations:
"""
if len(observations.shape) == 1:
obs_cdfs = np.zeros((ob... | [
"def",
"update",
"(",
"self",
",",
"forecasts",
",",
"observations",
")",
":",
"if",
"len",
"(",
"observations",
".",
"shape",
")",
"==",
"1",
":",
"obs_cdfs",
"=",
"np",
".",
"zeros",
"(",
"(",
"observations",
".",
"size",
",",
"self",
".",
"thresho... | Update the statistics with forecasts and observations.
Args:
forecasts: The discrete Cumulative Distribution Functions of
observations: | [
"Update",
"the",
"statistics",
"with",
"forecasts",
"and",
"observations",
"."
] | python | train | 42.315789 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/flask/app.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/app.py#L847-L871 | def register_module(self, module, **options):
"""Registers a module with this application. The keyword argument
of this function are the same as the ones for the constructor of the
:class:`Module` class and will override the values of the module if
provided.
.. versionchanged::... | [
"def",
"register_module",
"(",
"self",
",",
"module",
",",
"*",
"*",
"options",
")",
":",
"assert",
"blueprint_is_module",
"(",
"module",
")",
",",
"'register_module requires '",
"'actual module objects. Please upgrade to blueprints though.'",
"if",
"not",
"self",
".",... | Registers a module with this application. The keyword argument
of this function are the same as the ones for the constructor of the
:class:`Module` class and will override the values of the module if
provided.
.. versionchanged:: 0.7
The module system was deprecated in favor... | [
"Registers",
"a",
"module",
"with",
"this",
"application",
".",
"The",
"keyword",
"argument",
"of",
"this",
"function",
"are",
"the",
"same",
"as",
"the",
"ones",
"for",
"the",
"constructor",
"of",
"the",
":",
"class",
":",
"Module",
"class",
"and",
"will"... | python | test | 49.48 |
PaulHancock/Aegean | AegeanTools/catalogs.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/catalogs.py#L121-L142 | def update_meta_data(meta=None):
"""
Modify the metadata dictionary.
DATE, PROGRAM, and PROGVER are added/modified.
Parameters
----------
meta : dict
The dictionary to be modified, default = None (empty)
Returns
-------
An updated dictionary.
"""
if meta is None... | [
"def",
"update_meta_data",
"(",
"meta",
"=",
"None",
")",
":",
"if",
"meta",
"is",
"None",
":",
"meta",
"=",
"{",
"}",
"if",
"'DATE'",
"not",
"in",
"meta",
":",
"meta",
"[",
"'DATE'",
"]",
"=",
"strftime",
"(",
"\"%Y-%m-%d %H:%M:%S\"",
",",
"gmtime",
... | Modify the metadata dictionary.
DATE, PROGRAM, and PROGVER are added/modified.
Parameters
----------
meta : dict
The dictionary to be modified, default = None (empty)
Returns
-------
An updated dictionary. | [
"Modify",
"the",
"metadata",
"dictionary",
".",
"DATE",
"PROGRAM",
"and",
"PROGVER",
"are",
"added",
"/",
"modified",
"."
] | python | train | 25.954545 |
apache/incubator-mxnet | python/mxnet/rnn/rnn.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rnn/rnn.py#L62-L95 | def load_rnn_checkpoint(cells, prefix, epoch):
"""Load model checkpoint from file.
Pack weights after loading.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
Prefix of model name.
epoch : int
Epoch ... | [
"def",
"load_rnn_checkpoint",
"(",
"cells",
",",
"prefix",
",",
"epoch",
")",
":",
"sym",
",",
"arg",
",",
"aux",
"=",
"load_checkpoint",
"(",
"prefix",
",",
"epoch",
")",
"if",
"isinstance",
"(",
"cells",
",",
"BaseRNNCell",
")",
":",
"cells",
"=",
"[... | Load model checkpoint from file.
Pack weights after loading.
Parameters
----------
cells : mxnet.rnn.RNNCell or list of RNNCells
The RNN cells used by this symbol.
prefix : str
Prefix of model name.
epoch : int
Epoch number of model we would like to load.
Returns
... | [
"Load",
"model",
"checkpoint",
"from",
"file",
".",
"Pack",
"weights",
"after",
"loading",
"."
] | python | train | 29.352941 |
genicam/harvesters | src/harvesters/core.py | https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L2564-L2609 | def update_device_info_list(self):
"""
Updates the device information list. You'll have to call this method
every time you added CTI files or plugged/unplugged devices.
:return: None.
"""
#
self._release_gentl_producers()
try:
self._open_gent... | [
"def",
"update_device_info_list",
"(",
"self",
")",
":",
"#",
"self",
".",
"_release_gentl_producers",
"(",
")",
"try",
":",
"self",
".",
"_open_gentl_producers",
"(",
")",
"self",
".",
"_open_systems",
"(",
")",
"#",
"for",
"system",
"in",
"self",
".",
"_... | Updates the device information list. You'll have to call this method
every time you added CTI files or plugged/unplugged devices.
:return: None. | [
"Updates",
"the",
"device",
"information",
"list",
".",
"You",
"ll",
"have",
"to",
"call",
"this",
"method",
"every",
"time",
"you",
"added",
"CTI",
"files",
"or",
"plugged",
"/",
"unplugged",
"devices",
"."
] | python | valid | 37.282609 |
ThreatConnect-Inc/tcex | app_init/playbook_utility/app.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/app_init/playbook_utility/app.py#L25-L48 | def run(self):
"""Run the App main logic.
This method should contain the core logic of the App.
"""
# read inputs
indent = int(self.tcex.playbook.read(self.args.indent))
json_data = self.tcex.playbook.read(self.args.json_data)
# get the playbook variable type
... | [
"def",
"run",
"(",
"self",
")",
":",
"# read inputs",
"indent",
"=",
"int",
"(",
"self",
".",
"tcex",
".",
"playbook",
".",
"read",
"(",
"self",
".",
"args",
".",
"indent",
")",
")",
"json_data",
"=",
"self",
".",
"tcex",
".",
"playbook",
".",
"rea... | Run the App main logic.
This method should contain the core logic of the App. | [
"Run",
"the",
"App",
"main",
"logic",
"."
] | python | train | 36 |
sci-bots/pygtkhelpers | pygtkhelpers/ui/objectlist/column.py | https://github.com/sci-bots/pygtkhelpers/blob/3a6e6d6340221c686229cd1c951d7537dae81b07/pygtkhelpers/ui/objectlist/column.py#L203-L234 | def create_treecolumn(self, objectlist):
"""Create a gtk.TreeViewColumn for the configuration.
"""
col = gtk.TreeViewColumn(self.title)
col.set_data('pygtkhelpers::objectlist', objectlist)
col.set_data('pygtkhelpers::column', self)
col.props.visible = self.visible
... | [
"def",
"create_treecolumn",
"(",
"self",
",",
"objectlist",
")",
":",
"col",
"=",
"gtk",
".",
"TreeViewColumn",
"(",
"self",
".",
"title",
")",
"col",
".",
"set_data",
"(",
"'pygtkhelpers::objectlist'",
",",
"objectlist",
")",
"col",
".",
"set_data",
"(",
... | Create a gtk.TreeViewColumn for the configuration. | [
"Create",
"a",
"gtk",
".",
"TreeViewColumn",
"for",
"the",
"configuration",
"."
] | python | train | 45.9375 |
JoelBender/bacpypes | py25/bacpypes/debugging.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/debugging.py#L43-L75 | def ModuleLogger(globs):
"""Create a module level logger.
To debug a module, create a _debug variable in the module, then use the
ModuleLogger function to create a "module level" logger. When a handler
is added to this logger or a child of this logger, the _debug variable will
be incremented.
... | [
"def",
"ModuleLogger",
"(",
"globs",
")",
":",
"# make sure that _debug is defined",
"if",
"not",
"globs",
".",
"has_key",
"(",
"'_debug'",
")",
":",
"raise",
"RuntimeError",
"(",
"\"define _debug before creating a module logger\"",
")",
"# logger name is the module name",
... | Create a module level logger.
To debug a module, create a _debug variable in the module, then use the
ModuleLogger function to create a "module level" logger. When a handler
is added to this logger or a child of this logger, the _debug variable will
be incremented.
All of the calls within functio... | [
"Create",
"a",
"module",
"level",
"logger",
"."
] | python | train | 35.575758 |
alfredodeza/notario | notario/store.py | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/store.py#L25-L35 | def create_store():
"""
A helper for setting the _proxy and slapping the store
object for us.
:return: A thread-local storage as a dictionary
"""
new_storage = _proxy('store')
_state.store = type('store', (object,), {})
new_storage.store = dict()
return new_storage.store | [
"def",
"create_store",
"(",
")",
":",
"new_storage",
"=",
"_proxy",
"(",
"'store'",
")",
"_state",
".",
"store",
"=",
"type",
"(",
"'store'",
",",
"(",
"object",
",",
")",
",",
"{",
"}",
")",
"new_storage",
".",
"store",
"=",
"dict",
"(",
")",
"ret... | A helper for setting the _proxy and slapping the store
object for us.
:return: A thread-local storage as a dictionary | [
"A",
"helper",
"for",
"setting",
"the",
"_proxy",
"and",
"slapping",
"the",
"store",
"object",
"for",
"us",
"."
] | python | train | 27.090909 |
numenta/htmresearch | projects/energy_based_pooling/energy_based_models/energy_based_pooler.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/energy_based_pooling/energy_based_models/energy_based_pooler.py#L195-L205 | def encode(self, x):
"""
Given an input array `x` it returns its associated encoding `y(x)`, that is,
a stable configuration (local energy minimum) of the hidden units
while the visible units are clampled to `x`.
Note that NO learning takes place.
"""
E... | [
"def",
"encode",
"(",
"self",
",",
"x",
")",
":",
"E",
"=",
"self",
".",
"energy",
"y_min",
"=",
"self",
".",
"find_energy_minimum",
"(",
"E",
",",
"x",
")",
"return",
"y_min"
] | Given an input array `x` it returns its associated encoding `y(x)`, that is,
a stable configuration (local energy minimum) of the hidden units
while the visible units are clampled to `x`.
Note that NO learning takes place. | [
"Given",
"an",
"input",
"array",
"x",
"it",
"returns",
"its",
"associated",
"encoding",
"y",
"(",
"x",
")",
"that",
"is",
"a",
"stable",
"configuration",
"(",
"local",
"energy",
"minimum",
")",
"of",
"the",
"hidden",
"units",
"while",
"the",
"visible",
"... | python | train | 36.181818 |
diffeo/rejester | rejester/workers.py | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L433-L460 | def as_child(cls, global_config, parent=None):
'''Run a single job in a child process.
This method never returns; it always calls :func:`sys.exit`
with an error code that says what it did.
'''
try:
setproctitle('rejester worker')
random.seed() # otherwi... | [
"def",
"as_child",
"(",
"cls",
",",
"global_config",
",",
"parent",
"=",
"None",
")",
":",
"try",
":",
"setproctitle",
"(",
"'rejester worker'",
")",
"random",
".",
"seed",
"(",
")",
"# otherwise everyone inherits the same seed",
"yakonfig",
".",
"set_default_conf... | Run a single job in a child process.
This method never returns; it always calls :func:`sys.exit`
with an error code that says what it did. | [
"Run",
"a",
"single",
"job",
"in",
"a",
"child",
"process",
"."
] | python | train | 43.178571 |
OpenKMIP/PyKMIP | kmip/core/enums.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/enums.py#L1851-L1888 | def is_bit_mask(enumeration, potential_mask):
"""
A utility function that checks if the provided value is a composite bit
mask of enumeration values in the specified enumeration class.
Args:
enumeration (class): One of the mask enumeration classes found in this
file. These include:
... | [
"def",
"is_bit_mask",
"(",
"enumeration",
",",
"potential_mask",
")",
":",
"if",
"not",
"isinstance",
"(",
"potential_mask",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"False",
"mask_enumerations",
"=",
"(",
"CryptographicUsageMask",
",",
"ProtectionSto... | A utility function that checks if the provided value is a composite bit
mask of enumeration values in the specified enumeration class.
Args:
enumeration (class): One of the mask enumeration classes found in this
file. These include:
* Cryptographic Usage Mask
... | [
"A",
"utility",
"function",
"that",
"checks",
"if",
"the",
"provided",
"value",
"is",
"a",
"composite",
"bit",
"mask",
"of",
"enumeration",
"values",
"in",
"the",
"specified",
"enumeration",
"class",
"."
] | python | test | 29.842105 |
a1ezzz/wasp-general | wasp_general/network/web/headers.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L209-L219 | def content_type(self, value=None):
""" Set (replace) and or get "Content-Type" header value
:param value: value to set (if specified)
:return: None if header doesn't exist, otherwise - str
"""
content_type = self.normalize_name('Content-Type')
if value is not None:
self.replace_headers(content_type, va... | [
"def",
"content_type",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"content_type",
"=",
"self",
".",
"normalize_name",
"(",
"'Content-Type'",
")",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"replace_headers",
"(",
"content_type",
",",
"val... | Set (replace) and or get "Content-Type" header value
:param value: value to set (if specified)
:return: None if header doesn't exist, otherwise - str | [
"Set",
"(",
"replace",
")",
"and",
"or",
"get",
"Content",
"-",
"Type",
"header",
"value"
] | python | train | 36.363636 |
fastai/fastai | docs_src/nbval/kernel.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/kernel.py#L35-L45 | def get_kernel_spec(self, kernel_name):
"""Returns a :class:`KernelSpec` instance for the given kernel_name.
Raises :exc:`NoSuchKernel` if the given kernel name is not found.
"""
if kernel_name == CURRENT_ENV_KERNEL_NAME:
return self.kernel_spec_class(
resour... | [
"def",
"get_kernel_spec",
"(",
"self",
",",
"kernel_name",
")",
":",
"if",
"kernel_name",
"==",
"CURRENT_ENV_KERNEL_NAME",
":",
"return",
"self",
".",
"kernel_spec_class",
"(",
"resource_dir",
"=",
"ipykernel",
".",
"kernelspec",
".",
"RESOURCES",
",",
"*",
"*",... | Returns a :class:`KernelSpec` instance for the given kernel_name.
Raises :exc:`NoSuchKernel` if the given kernel name is not found. | [
"Returns",
"a",
":",
"class",
":",
"KernelSpec",
"instance",
"for",
"the",
"given",
"kernel_name",
"."
] | python | train | 45.818182 |
konstantinstadler/pymrio | pymrio/core/mriosystem.py | https://github.com/konstantinstadler/pymrio/blob/d764aa0dd2150200e867a9713a98ddae203e12d4/pymrio/core/mriosystem.py#L1631-L1645 | def reset_to_flows(self, force=False):
""" Keeps only the absolute values.
This removes all attributes which can not be aggregated and must be
recalculated after the aggregation.
Parameters
----------
force: boolean, optional
If True, reset to flows althoug... | [
"def",
"reset_to_flows",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"super",
"(",
")",
".",
"reset_to_flows",
"(",
"force",
"=",
"force",
",",
"_meta",
"=",
"self",
".",
"meta",
")",
"return",
"self"
] | Keeps only the absolute values.
This removes all attributes which can not be aggregated and must be
recalculated after the aggregation.
Parameters
----------
force: boolean, optional
If True, reset to flows although the system can not be
recalculated. D... | [
"Keeps",
"only",
"the",
"absolute",
"values",
"."
] | python | train | 30.866667 |
opennode/waldur-core | waldur_core/cost_tracking/views.py | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/views.py#L139-L150 | def list(self, request, *args, **kwargs):
"""
To get a list of default price list items, run **GET** against */api/default-price-list-items/*
as authenticated user.
Price lists can be filtered by:
- ?key=<string>
- ?item_type=<string> has to be from list of available i... | [
"def",
"list",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"DefaultPriceListItemViewSet",
",",
"self",
")",
".",
"list",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | To get a list of default price list items, run **GET** against */api/default-price-list-items/*
as authenticated user.
Price lists can be filtered by:
- ?key=<string>
- ?item_type=<string> has to be from list of available item_types
(available options: 'flavor', 'storage', ... | [
"To",
"get",
"a",
"list",
"of",
"default",
"price",
"list",
"items",
"run",
"**",
"GET",
"**",
"against",
"*",
"/",
"api",
"/",
"default",
"-",
"price",
"-",
"list",
"-",
"items",
"/",
"*",
"as",
"authenticated",
"user",
"."
] | python | train | 52.583333 |
NoviceLive/intellicoder | intellicoder/transformers.py | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/transformers.py#L272-L288 | def update_func_body(original, updater=None):
"""Update all function body using the updating function."""
updated = ''
regex = r'([_\w][_\w\d]*)\s*\(.*\)\s*\{'
match = re.search(regex, original)
while match:
name = match.group(1)
logging.debug(_('Found candidate: %s'), name)
... | [
"def",
"update_func_body",
"(",
"original",
",",
"updater",
"=",
"None",
")",
":",
"updated",
"=",
"''",
"regex",
"=",
"r'([_\\w][_\\w\\d]*)\\s*\\(.*\\)\\s*\\{'",
"match",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"original",
")",
"while",
"match",
":",
"... | Update all function body using the updating function. | [
"Update",
"all",
"function",
"body",
"using",
"the",
"updating",
"function",
"."
] | python | train | 37.764706 |
PyCQA/astroid | astroid/node_classes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L4183-L4201 | def block_range(self, lineno):
"""Get a range from the given line number to where this node ends.
:param lineno: The line number to start the range at.
:type lineno: int
:returns: The range of line numbers that this node belongs to,
starting at the given line number.
... | [
"def",
"block_range",
"(",
"self",
",",
"lineno",
")",
":",
"child",
"=",
"self",
".",
"body",
"[",
"0",
"]",
"# py2.5 try: except: finally:",
"if",
"(",
"isinstance",
"(",
"child",
",",
"TryExcept",
")",
"and",
"child",
".",
"fromlineno",
"==",
"self",
... | Get a range from the given line number to where this node ends.
:param lineno: The line number to start the range at.
:type lineno: int
:returns: The range of line numbers that this node belongs to,
starting at the given line number.
:rtype: tuple(int, int) | [
"Get",
"a",
"range",
"from",
"the",
"given",
"line",
"number",
"to",
"where",
"this",
"node",
"ends",
"."
] | python | train | 36.315789 |
hsolbrig/PyShEx | pyshex/evaluate.py | https://github.com/hsolbrig/PyShEx/blob/9d659cc36e808afd66d4a6d60e8ea21cb12eb744/pyshex/evaluate.py#L14-L45 | def evaluate(g: Graph,
schema: Union[str, ShExJ.Schema],
focus: Optional[Union[str, URIRef, IRIREF]],
start: Optional[Union[str, URIRef, IRIREF, START, START_TYPE]]=None,
debug_trace: bool = False) -> Tuple[bool, Optional[str]]:
""" Evaluate focus node `focus` in ... | [
"def",
"evaluate",
"(",
"g",
":",
"Graph",
",",
"schema",
":",
"Union",
"[",
"str",
",",
"ShExJ",
".",
"Schema",
"]",
",",
"focus",
":",
"Optional",
"[",
"Union",
"[",
"str",
",",
"URIRef",
",",
"IRIREF",
"]",
"]",
",",
"start",
":",
"Optional",
... | Evaluate focus node `focus` in graph `g` against shape `shape` in ShEx schema `schema`
:param g: Graph containing RDF
:param schema: ShEx Schema -- if str, it will be parsed
:param focus: focus node in g. If not specified, all URI subjects in G will be evaluated.
:param start: Starting shape. If omitt... | [
"Evaluate",
"focus",
"node",
"focus",
"in",
"graph",
"g",
"against",
"shape",
"shape",
"in",
"ShEx",
"schema",
"schema"
] | python | train | 45.34375 |
bcbio/bcbio-nextgen | bcbio/pipeline/merge.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/merge.py#L93-L101 | def _merge_outfile_fname(out_file, bam_files, work_dir, batch):
"""Derive correct name of BAM file based on batching.
"""
if out_file is None:
out_file = os.path.join(work_dir, os.path.basename(sorted(bam_files)[0]))
if batch is not None:
base, ext = os.path.splitext(out_file)
ou... | [
"def",
"_merge_outfile_fname",
"(",
"out_file",
",",
"bam_files",
",",
"work_dir",
",",
"batch",
")",
":",
"if",
"out_file",
"is",
"None",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"os",
".",
"path",
".",
"basename",
"... | Derive correct name of BAM file based on batching. | [
"Derive",
"correct",
"name",
"of",
"BAM",
"file",
"based",
"on",
"batching",
"."
] | python | train | 41.333333 |
silver-castle/mach9 | mach9/http.py | https://github.com/silver-castle/mach9/blob/7a623aab3c70d89d36ade6901b6307e115400c5e/mach9/http.py#L191-L200 | def get_request_body_chunk(self, content: bytes, closed: bool,
more_content: bool) -> Dict[str, Any]:
'''
http://channels.readthedocs.io/en/stable/asgi/www.html#request-body-chunk
'''
return {
'content': content,
'closed': closed,
... | [
"def",
"get_request_body_chunk",
"(",
"self",
",",
"content",
":",
"bytes",
",",
"closed",
":",
"bool",
",",
"more_content",
":",
"bool",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"'content'",
":",
"content",
",",
"'closed'",
... | http://channels.readthedocs.io/en/stable/asgi/www.html#request-body-chunk | [
"http",
":",
"//",
"channels",
".",
"readthedocs",
".",
"io",
"/",
"en",
"/",
"stable",
"/",
"asgi",
"/",
"www",
".",
"html#request",
"-",
"body",
"-",
"chunk"
] | python | train | 35.9 |
gvanderheide/discreteMarkovChain | discreteMarkovChain/markovChain.py | https://github.com/gvanderheide/discreteMarkovChain/blob/8325ffdb791c109eee600684ee0dc9126ce80700/discreteMarkovChain/markovChain.py#L565-L594 | def computePi(self,method='power'):
"""
Calculate the steady state distribution using your preferred method and store it in the attribute `pi`.
By default uses the most robust method, 'power'. Other methods are 'eigen','linear', and 'krylov'
Parameters
----------
... | [
"def",
"computePi",
"(",
"self",
",",
"method",
"=",
"'power'",
")",
":",
"methodSet",
"=",
"[",
"'power'",
",",
"'eigen'",
",",
"'linear'",
",",
"'krylov'",
"]",
"assert",
"method",
"in",
"methodSet",
",",
"\"Incorrect method specified. Choose from %r\"",
"%",
... | Calculate the steady state distribution using your preferred method and store it in the attribute `pi`.
By default uses the most robust method, 'power'. Other methods are 'eigen','linear', and 'krylov'
Parameters
----------
method : string, optional(default='power')
... | [
"Calculate",
"the",
"steady",
"state",
"distribution",
"using",
"your",
"preferred",
"method",
"and",
"store",
"it",
"in",
"the",
"attribute",
"pi",
".",
"By",
"default",
"uses",
"the",
"most",
"robust",
"method",
"power",
".",
"Other",
"methods",
"are",
"ei... | python | train | 37.7 |
OnroerendErfgoed/crabpy | crabpy/gateway/crab.py | https://github.com/OnroerendErfgoed/crabpy/blob/3a6fd8bc5aca37c2a173e3ea94e4e468b8aa79c1/crabpy/gateway/crab.py#L1291-L1323 | def get_subadres_by_id(self, id):
'''
Retrieve a `Subadres` by the Id.
:param integer id: the Id of the `Subadres`
:rtype: :class:`Subadres`
'''
def creator():
res = crab_gateway_request(
self.client, 'GetSubadresWithStatusBySubadresId', id
... | [
"def",
"get_subadres_by_id",
"(",
"self",
",",
"id",
")",
":",
"def",
"creator",
"(",
")",
":",
"res",
"=",
"crab_gateway_request",
"(",
"self",
".",
"client",
",",
"'GetSubadresWithStatusBySubadresId'",
",",
"id",
")",
"if",
"res",
"==",
"None",
":",
"rai... | Retrieve a `Subadres` by the Id.
:param integer id: the Id of the `Subadres`
:rtype: :class:`Subadres` | [
"Retrieve",
"a",
"Subadres",
"by",
"the",
"Id",
"."
] | python | train | 33.939394 |
Asana/python-asana | asana/resources/gen/webhooks.py | https://github.com/Asana/python-asana/blob/6deb7a34495db23f44858e53b6bb2c9eccff7872/asana/resources/gen/webhooks.py#L100-L110 | def delete_by_id(self, webhook, params={}, **options):
"""This method permanently removes a webhook. Note that it may be possible
to receive a request that was already in flight after deleting the
webhook, but no further requests will be issued.
Parameters
----------
we... | [
"def",
"delete_by_id",
"(",
"self",
",",
"webhook",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/webhooks/%s\"",
"%",
"(",
"webhook",
")",
"return",
"self",
".",
"client",
".",
"delete",
"(",
"path",
",",
"params... | This method permanently removes a webhook. Note that it may be possible
to receive a request that was already in flight after deleting the
webhook, but no further requests will be issued.
Parameters
----------
webhook : {Id} The webhook to delete. | [
"This",
"method",
"permanently",
"removes",
"a",
"webhook",
".",
"Note",
"that",
"it",
"may",
"be",
"possible",
"to",
"receive",
"a",
"request",
"that",
"was",
"already",
"in",
"flight",
"after",
"deleting",
"the",
"webhook",
"but",
"no",
"further",
"request... | python | train | 41.636364 |
dnanexus/dx-toolkit | src/python/dxpy/scripts/dx_build_report_html.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/scripts/dx_build_report_html.py#L178-L187 | def upload_html(destination, html, name=None):
"""
Uploads the HTML to a file on the server
"""
[project, path, n] = parse_destination(destination)
try:
dxfile = dxpy.upload_string(html, media_type="text/html", project=project, folder=path, hidden=True, name=name or None)
return dxfi... | [
"def",
"upload_html",
"(",
"destination",
",",
"html",
",",
"name",
"=",
"None",
")",
":",
"[",
"project",
",",
"path",
",",
"n",
"]",
"=",
"parse_destination",
"(",
"destination",
")",
"try",
":",
"dxfile",
"=",
"dxpy",
".",
"upload_string",
"(",
"htm... | Uploads the HTML to a file on the server | [
"Uploads",
"the",
"HTML",
"to",
"a",
"file",
"on",
"the",
"server"
] | python | train | 45 |
pgjones/quart | quart/logging.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/logging.py#L15-L27 | def create_logger(app: 'Quart') -> Logger:
"""Create a logger for the app based on the app settings.
This creates a logger named quart.app that has a log level based
on the app configuration.
"""
logger = getLogger('quart.app')
if app.debug and logger.level == NOTSET:
logger.setLevel(D... | [
"def",
"create_logger",
"(",
"app",
":",
"'Quart'",
")",
"->",
"Logger",
":",
"logger",
"=",
"getLogger",
"(",
"'quart.app'",
")",
"if",
"app",
".",
"debug",
"and",
"logger",
".",
"level",
"==",
"NOTSET",
":",
"logger",
".",
"setLevel",
"(",
"DEBUG",
"... | Create a logger for the app based on the app settings.
This creates a logger named quart.app that has a log level based
on the app configuration. | [
"Create",
"a",
"logger",
"for",
"the",
"app",
"based",
"on",
"the",
"app",
"settings",
"."
] | python | train | 28.538462 |
OCA/openupgradelib | openupgradelib/openupgrade_merge_records.py | https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade_merge_records.py#L396-L437 | def _change_generic(env, model_name, record_ids, target_record_id,
exclude_columns, method='orm'):
""" Update known generic style res_id/res_model references """
for model_to_replace, res_id_column, model_column in [
('calendar.event', 'res_id', 'res_model'),
('ir.att... | [
"def",
"_change_generic",
"(",
"env",
",",
"model_name",
",",
"record_ids",
",",
"target_record_id",
",",
"exclude_columns",
",",
"method",
"=",
"'orm'",
")",
":",
"for",
"model_to_replace",
",",
"res_id_column",
",",
"model_column",
"in",
"[",
"(",
"'calendar.e... | Update known generic style res_id/res_model references | [
"Update",
"known",
"generic",
"style",
"res_id",
"/",
"res_model",
"references"
] | python | train | 43.5 |
Terrance/SkPy | skpy/conn.py | https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L887-L899 | def subscribe(self):
"""
Subscribe to contact and conversation events. These are accessible through :meth:`getEvents`.
"""
self.conn("POST", "{0}/users/ME/endpoints/{1}/subscriptions".format(self.conn.msgsHost, self.id),
auth=SkypeConnection.Auth.RegToken,
... | [
"def",
"subscribe",
"(",
"self",
")",
":",
"self",
".",
"conn",
"(",
"\"POST\"",
",",
"\"{0}/users/ME/endpoints/{1}/subscriptions\"",
".",
"format",
"(",
"self",
".",
"conn",
".",
"msgsHost",
",",
"self",
".",
"id",
")",
",",
"auth",
"=",
"SkypeConnection",
... | Subscribe to contact and conversation events. These are accessible through :meth:`getEvents`. | [
"Subscribe",
"to",
"contact",
"and",
"conversation",
"events",
".",
"These",
"are",
"accessible",
"through",
":",
"meth",
":",
"getEvents",
"."
] | python | test | 58 |
greenbone/ospd | ospd/ospd.py | https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L169-L180 | def close_client_stream(client_stream, unix_path):
""" Closes provided client stream """
try:
client_stream.shutdown(socket.SHUT_RDWR)
if unix_path:
logger.debug('%s: Connection closed', unix_path)
else:
peer = client_stream.getpeername()
logger.debug(... | [
"def",
"close_client_stream",
"(",
"client_stream",
",",
"unix_path",
")",
":",
"try",
":",
"client_stream",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"if",
"unix_path",
":",
"logger",
".",
"debug",
"(",
"'%s: Connection closed'",
",",
"unix_path",
... | Closes provided client stream | [
"Closes",
"provided",
"client",
"stream"
] | python | train | 41.083333 |
sqlboy/fileseq | src/fileseq/filesequence.py | https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L789-L814 | def conformPadding(cls, chars):
"""
Ensure alternate input padding formats are conformed
to formats defined in PAD_MAP
If chars is already a format defined in PAD_MAP, then
it is returned unmodified.
Example::
'#' -> '#'
'@@@@' -> '@@@@'
... | [
"def",
"conformPadding",
"(",
"cls",
",",
"chars",
")",
":",
"pad",
"=",
"chars",
"if",
"pad",
"and",
"pad",
"[",
"0",
"]",
"not",
"in",
"PAD_MAP",
":",
"pad",
"=",
"cls",
".",
"getPaddingChars",
"(",
"cls",
".",
"getPaddingNum",
"(",
"pad",
")",
"... | Ensure alternate input padding formats are conformed
to formats defined in PAD_MAP
If chars is already a format defined in PAD_MAP, then
it is returned unmodified.
Example::
'#' -> '#'
'@@@@' -> '@@@@'
'%04d' -> '#'
Args:
char... | [
"Ensure",
"alternate",
"input",
"padding",
"formats",
"are",
"conformed",
"to",
"formats",
"defined",
"in",
"PAD_MAP"
] | python | train | 25.961538 |
mixmastamyk/env | env.py | https://github.com/mixmastamyk/env/blob/63ed6b914bd5189986972b338b86453e42890fa0/env.py#L183-L208 | def prefix(self, prefix, lowercase=True):
''' Returns a dictionary of keys with the same prefix.
Compat with kr/env, lowercased.
> xdg = env.prefix('XDG_')
> for key, value in xdg.items():
print('%-20s' % key, value[:6], '…')
config_dirs /e... | [
"def",
"prefix",
"(",
"self",
",",
"prefix",
",",
"lowercase",
"=",
"True",
")",
":",
"env_subset",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_envars",
".",
"keys",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"prefix",
")",
":",
"n... | Returns a dictionary of keys with the same prefix.
Compat with kr/env, lowercased.
> xdg = env.prefix('XDG_')
> for key, value in xdg.items():
print('%-20s' % key, value[:6], '…')
config_dirs /etc/x…
current_desktop MATE
da... | [
"Returns",
"a",
"dictionary",
"of",
"keys",
"with",
"the",
"same",
"prefix",
".",
"Compat",
"with",
"kr",
"/",
"env",
"lowercased",
"."
] | python | train | 38.038462 |
paulgb/runipy | runipy/notebook_runner.py | https://github.com/paulgb/runipy/blob/d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe/runipy/notebook_runner.py#L235-L249 | def run_notebook(self, skip_exceptions=False, progress_callback=None):
"""
Run all the notebook cells in order and update the outputs in-place.
If ``skip_exceptions`` is set, then if exceptions occur in a cell, the
subsequent cells are run (by default, the notebook execution stops).
... | [
"def",
"run_notebook",
"(",
"self",
",",
"skip_exceptions",
"=",
"False",
",",
"progress_callback",
"=",
"None",
")",
":",
"for",
"i",
",",
"cell",
"in",
"enumerate",
"(",
"self",
".",
"iter_code_cells",
"(",
")",
")",
":",
"try",
":",
"self",
".",
"ru... | Run all the notebook cells in order and update the outputs in-place.
If ``skip_exceptions`` is set, then if exceptions occur in a cell, the
subsequent cells are run (by default, the notebook execution stops). | [
"Run",
"all",
"the",
"notebook",
"cells",
"in",
"order",
"and",
"update",
"the",
"outputs",
"in",
"-",
"place",
"."
] | python | train | 39.733333 |
MAVENSDC/cdflib | cdflib/cdfread.py | https://github.com/MAVENSDC/cdflib/blob/d237c60e5db67db0f92d96054209c25c4042465c/cdflib/cdfread.py#L1726-L1741 | def _convert_option(self):
'''
Determines how to convert CDF byte ordering to the system
byte ordering.
'''
if sys.byteorder == 'little' and self._endian() == 'big-endian':
# big->little
order = '>'
elif sys.byteorder == 'big' and self._endian() =... | [
"def",
"_convert_option",
"(",
"self",
")",
":",
"if",
"sys",
".",
"byteorder",
"==",
"'little'",
"and",
"self",
".",
"_endian",
"(",
")",
"==",
"'big-endian'",
":",
"# big->little",
"order",
"=",
"'>'",
"elif",
"sys",
".",
"byteorder",
"==",
"'big'",
"a... | Determines how to convert CDF byte ordering to the system
byte ordering. | [
"Determines",
"how",
"to",
"convert",
"CDF",
"byte",
"ordering",
"to",
"the",
"system",
"byte",
"ordering",
"."
] | python | train | 28.75 |
anchore/anchore | anchore/cli/system.py | https://github.com/anchore/anchore/blob/8a4d5b9708e27856312d303aae3f04f3c72039d6/anchore/cli/system.py#L116-L130 | def backup(outputdir):
"""
Backup an anchore installation to a tarfile.
"""
ecode = 0
try:
anchore_print('Backing up anchore system to directory '+str(outputdir)+' ...')
backupfile = config.backup(outputdir)
anchore_print({"anchore_backup_tarball":str(backupfile)}, do_format... | [
"def",
"backup",
"(",
"outputdir",
")",
":",
"ecode",
"=",
"0",
"try",
":",
"anchore_print",
"(",
"'Backing up anchore system to directory '",
"+",
"str",
"(",
"outputdir",
")",
"+",
"' ...'",
")",
"backupfile",
"=",
"config",
".",
"backup",
"(",
"outputdir",
... | Backup an anchore installation to a tarfile. | [
"Backup",
"an",
"anchore",
"installation",
"to",
"a",
"tarfile",
"."
] | python | train | 28.666667 |
Netflix-Skunkworks/policyuniverse | policyuniverse/statement.py | https://github.com/Netflix-Skunkworks/policyuniverse/blob/f31453219b348549c3d71659660b868dfb9030a3/policyuniverse/statement.py#L140-L203 | def _condition_entries(self):
"""Extracts any ARNs, Account Numbers, UserIDs, Usernames, CIDRs, VPCs, and VPC Endpoints from a condition block.
Ignores any negated condition operators like StringNotLike.
Ignores weak condition keys like referer, date, etc.
Reason: A con... | [
"def",
"_condition_entries",
"(",
"self",
")",
":",
"conditions",
"=",
"list",
"(",
")",
"condition",
"=",
"self",
".",
"statement",
".",
"get",
"(",
"'Condition'",
")",
"if",
"not",
"condition",
":",
"return",
"conditions",
"key_mapping",
"=",
"{",
"'aws:... | Extracts any ARNs, Account Numbers, UserIDs, Usernames, CIDRs, VPCs, and VPC Endpoints from a condition block.
Ignores any negated condition operators like StringNotLike.
Ignores weak condition keys like referer, date, etc.
Reason: A condition is meant to limit the principal in... | [
"Extracts",
"any",
"ARNs",
"Account",
"Numbers",
"UserIDs",
"Usernames",
"CIDRs",
"VPCs",
"and",
"VPC",
"Endpoints",
"from",
"a",
"condition",
"block",
".",
"Ignores",
"any",
"negated",
"condition",
"operators",
"like",
"StringNotLike",
".",
"Ignores",
"weak",
"... | python | train | 45.96875 |
Cologler/fsoopify-python | fsoopify/nodes.py | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L228-L238 | def load(self, format=None, *, kwargs={}):
'''
deserialize object from the file.
auto detect format by file extension name if `format` is None.
for example, `.json` will detect as `json`.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any s... | [
"def",
"load",
"(",
"self",
",",
"format",
"=",
"None",
",",
"*",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"return",
"load",
"(",
"self",
",",
"format",
"=",
"format",
",",
"kwargs",
"=",
"kwargs",
")"
] | deserialize object from the file.
auto detect format by file extension name if `format` is None.
for example, `.json` will detect as `json`.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any serialize exceptions. | [
"deserialize",
"object",
"from",
"the",
"file",
"."
] | python | train | 36.181818 |
bcbio/bcbio-nextgen | bcbio/variation/population.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L143-L183 | def create_gemini_db_orig(gemini_vcf, data, gemini_db=None, ped_file=None):
"""Original GEMINI specific data loader, only works with hg19/GRCh37.
"""
if not gemini_db:
gemini_db = "%s.db" % utils.splitext_plus(gemini_vcf)[0]
if not utils.file_exists(gemini_db):
if not vcfutils.vcf_has_va... | [
"def",
"create_gemini_db_orig",
"(",
"gemini_vcf",
",",
"data",
",",
"gemini_db",
"=",
"None",
",",
"ped_file",
"=",
"None",
")",
":",
"if",
"not",
"gemini_db",
":",
"gemini_db",
"=",
"\"%s.db\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"gemini_vcf",
")",
... | Original GEMINI specific data loader, only works with hg19/GRCh37. | [
"Original",
"GEMINI",
"specific",
"data",
"loader",
"only",
"works",
"with",
"hg19",
"/",
"GRCh37",
"."
] | python | train | 56.195122 |
bolt-project/bolt | bolt/spark/array.py | https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/array.py#L85-L115 | def _align(self, axis):
"""
Align spark bolt array so that axes for iteration are in the keys.
This operation is applied before most functional operators.
It ensures that the specified axes are valid, and swaps
key/value axes so that functional operators can be applied
o... | [
"def",
"_align",
"(",
"self",
",",
"axis",
")",
":",
"# ensure that the specified axes are valid",
"inshape",
"(",
"self",
".",
"shape",
",",
"axis",
")",
"# find the value axes that should be moved into the keys (axis >= split)",
"tokeys",
"=",
"[",
"(",
"a",
"-",
"s... | Align spark bolt array so that axes for iteration are in the keys.
This operation is applied before most functional operators.
It ensures that the specified axes are valid, and swaps
key/value axes so that functional operators can be applied
over the correct records.
Parameters... | [
"Align",
"spark",
"bolt",
"array",
"so",
"that",
"axes",
"for",
"iteration",
"are",
"in",
"the",
"keys",
"."
] | python | test | 33.129032 |
user-cont/colin | colin/core/target.py | https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/target.py#L193-L205 | def file_is_present(self, file_path):
"""
check if file 'file_path' is present, raises IOError if file_path
is not a file
:param file_path: str, path to the file
:return: True if file exists, False if file does not exist
"""
real_path = self.cont_path(file_path)
... | [
"def",
"file_is_present",
"(",
"self",
",",
"file_path",
")",
":",
"real_path",
"=",
"self",
".",
"cont_path",
"(",
"file_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"real_path",
")",
":",
"return",
"False",
"if",
"not",
"os",
".",
... | check if file 'file_path' is present, raises IOError if file_path
is not a file
:param file_path: str, path to the file
:return: True if file exists, False if file does not exist | [
"check",
"if",
"file",
"file_path",
"is",
"present",
"raises",
"IOError",
"if",
"file_path",
"is",
"not",
"a",
"file",
":",
"param",
"file_path",
":",
"str",
"path",
"to",
"the",
"file",
":",
"return",
":",
"True",
"if",
"file",
"exists",
"False",
"if",
... | python | train | 37.923077 |
singularityhub/singularity-python | singularity/analysis/compare.py | https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/analysis/compare.py#L41-L75 | def container_similarity_vector(container1=None,packages_set=None,by=None):
'''container similarity_vector is similar to compare_packages, but intended
to compare a container object (singularity image or singularity hub container)
to a list of packages. If packages_set is not provided, the default used is
... | [
"def",
"container_similarity_vector",
"(",
"container1",
"=",
"None",
",",
"packages_set",
"=",
"None",
",",
"by",
"=",
"None",
")",
":",
"if",
"by",
"==",
"None",
":",
"by",
"=",
"[",
"'files.txt'",
"]",
"if",
"not",
"isinstance",
"(",
"by",
",",
"lis... | container similarity_vector is similar to compare_packages, but intended
to compare a container object (singularity image or singularity hub container)
to a list of packages. If packages_set is not provided, the default used is
'docker-os'. This can be changed to 'docker-library', or if the user wants a cu... | [
"container",
"similarity_vector",
"is",
"similar",
"to",
"compare_packages",
"but",
"intended",
"to",
"compare",
"a",
"container",
"object",
"(",
"singularity",
"image",
"or",
"singularity",
"hub",
"container",
")",
"to",
"a",
"list",
"of",
"packages",
".",
"If"... | python | train | 43.257143 |
CalebBell/thermo | thermo/thermal_conductivity.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L1671-L1730 | def Gharagheizi_gas(T, MW, Tb, Pc, omega):
r'''Estimates the thermal conductivity of a gas as a function of
temperature using the CSP method of Gharagheizi [1]_. A convoluted
method claiming high-accuracy and using only statistically significant
variable following analalysis.
Requires temperature,... | [
"def",
"Gharagheizi_gas",
"(",
"T",
",",
"MW",
",",
"Tb",
",",
"Pc",
",",
"omega",
")",
":",
"Pc",
"=",
"Pc",
"/",
"1E4",
"B",
"=",
"T",
"+",
"(",
"2.",
"*",
"omega",
"+",
"2.",
"*",
"T",
"-",
"2.",
"*",
"T",
"*",
"(",
"2.",
"*",
"omega",... | r'''Estimates the thermal conductivity of a gas as a function of
temperature using the CSP method of Gharagheizi [1]_. A convoluted
method claiming high-accuracy and using only statistically significant
variable following analalysis.
Requires temperature, molecular weight, boiling temperature and crit... | [
"r",
"Estimates",
"the",
"thermal",
"conductivity",
"of",
"a",
"gas",
"as",
"a",
"function",
"of",
"temperature",
"using",
"the",
"CSP",
"method",
"of",
"Gharagheizi",
"[",
"1",
"]",
"_",
".",
"A",
"convoluted",
"method",
"claiming",
"high",
"-",
"accuracy... | python | valid | 37.3 |
timkpaine/pyEX | pyEX/marketdata/sse.py | https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/marketdata/sse.py#L185-L197 | def securityEventSSE(symbols=None, on_data=None, token='', version=''):
'''The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs
https://iexcloud.io/docs/api/#deep-security-event
Args:
symbols (string); Tick... | [
"def",
"securityEventSSE",
"(",
"symbols",
"=",
"None",
",",
"on_data",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"return",
"_runSSE",
"(",
"'security-event'",
",",
"symbols",
",",
"on_data",
",",
"token",
",",
"version",... | The Security event message is used to indicate events that apply to a security. A Security event message will be sent whenever such event occurs
https://iexcloud.io/docs/api/#deep-security-event
Args:
symbols (string); Tickers to request
on_data (function): Callback on data
token (stri... | [
"The",
"Security",
"event",
"message",
"is",
"used",
"to",
"indicate",
"events",
"that",
"apply",
"to",
"a",
"security",
".",
"A",
"Security",
"event",
"message",
"will",
"be",
"sent",
"whenever",
"such",
"event",
"occurs"
] | python | valid | 40.153846 |
DataKitchen/DKCloudCommand | DKCloudCommand/cli/__main__.py | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L313-L318 | def kitchen_list(backend):
"""
List all Kitchens
"""
click.echo(click.style('%s - Getting the list of kitchens' % get_datetime(), fg='green'))
check_and_print(DKCloudCommandRunner.list_kitchen(backend.dki)) | [
"def",
"kitchen_list",
"(",
"backend",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'%s - Getting the list of kitchens'",
"%",
"get_datetime",
"(",
")",
",",
"fg",
"=",
"'green'",
")",
")",
"check_and_print",
"(",
"DKCloudCommandRunner",
"... | List all Kitchens | [
"List",
"all",
"Kitchens"
] | python | train | 36.833333 |
open-mmlab/mmcv | mmcv/utils/timer.py | https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/utils/timer.py#L56-L61 | def start(self):
"""Start the timer."""
if not self._is_running:
self._t_start = time()
self._is_running = True
self._t_last = time() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_running",
":",
"self",
".",
"_t_start",
"=",
"time",
"(",
")",
"self",
".",
"_is_running",
"=",
"True",
"self",
".",
"_t_last",
"=",
"time",
"(",
")"
] | Start the timer. | [
"Start",
"the",
"timer",
"."
] | python | test | 29.333333 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1376-L1394 | def read_stack_dwords(self, count, offset = 0):
"""
Reads DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
... | [
"def",
"read_stack_dwords",
"(",
"self",
",",
"count",
",",
"offset",
"=",
"0",
")",
":",
"if",
"count",
">",
"0",
":",
"stackData",
"=",
"self",
".",
"read_stack_data",
"(",
"count",
"*",
"4",
",",
"offset",
")",
"return",
"struct",
".",
"unpack",
"... | Reads DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise ... | [
"Reads",
"DWORDs",
"from",
"the",
"top",
"of",
"the",
"stack",
"."
] | python | train | 31.315789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.