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 |
|---|---|---|---|---|---|---|---|---|---|
manns/pyspread | pyspread/src/gui/_main_window.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_main_window.py#L832-L905 | def OnOpen(self, event):
"""File open event handler"""
# If changes have taken place save of old grid
if undo.stack().haschanged():
save_choice = self.interfaces.get_save_request_from_user()
if save_choice is None:
# Cancelled close operation
... | [
"def",
"OnOpen",
"(",
"self",
",",
"event",
")",
":",
"# If changes have taken place save of old grid",
"if",
"undo",
".",
"stack",
"(",
")",
".",
"haschanged",
"(",
")",
":",
"save_choice",
"=",
"self",
".",
"interfaces",
".",
"get_save_request_from_user",
"(",... | File open event handler | [
"File",
"open",
"event",
"handler"
] | python | train | 31.378378 |
openfisca/openfisca-france-indirect-taxation | openfisca_france_indirect_taxation/param/preprocessing.py | https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/param/preprocessing.py#L29-L475 | def preprocess_legislation(legislation_json):
'''
Preprocess the legislation parameters to add prices and amounts from national accounts
'''
import os
import pkg_resources
import pandas as pd
# Add fuel prices to the tree
default_config_files_directory = os.path.join(
pkg_resou... | [
"def",
"preprocess_legislation",
"(",
"legislation_json",
")",
":",
"import",
"os",
"import",
"pkg_resources",
"import",
"pandas",
"as",
"pd",
"# Add fuel prices to the tree",
"default_config_files_directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pkg_resources",
... | Preprocess the legislation parameters to add prices and amounts from national accounts | [
"Preprocess",
"the",
"legislation",
"parameters",
"to",
"add",
"prices",
"and",
"amounts",
"from",
"national",
"accounts"
] | python | train | 53.340045 |
angr/angr | angr/storage/paged_memory.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/storage/paged_memory.py#L601-L613 | def contains_no_backer(self, addr):
"""
Tests if the address is contained in any page of paged memory, without considering memory backers.
:param int addr: The address to test.
:return: True if the address is included in one of the pages, False otherwise.
:rtype: bool
""... | [
"def",
"contains_no_backer",
"(",
"self",
",",
"addr",
")",
":",
"for",
"i",
",",
"p",
"in",
"self",
".",
"_pages",
".",
"items",
"(",
")",
":",
"if",
"i",
"*",
"self",
".",
"_page_size",
"<=",
"addr",
"<",
"(",
"i",
"+",
"1",
")",
"*",
"self",... | Tests if the address is contained in any page of paged memory, without considering memory backers.
:param int addr: The address to test.
:return: True if the address is included in one of the pages, False otherwise.
:rtype: bool | [
"Tests",
"if",
"the",
"address",
"is",
"contained",
"in",
"any",
"page",
"of",
"paged",
"memory",
"without",
"considering",
"memory",
"backers",
"."
] | python | train | 39.076923 |
google-research/batch-ppo | agents/algorithms/ppo/utility.py | https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L94-L105 | def lambda_return(reward, value, length, discount, lambda_):
"""TD-lambda returns."""
timestep = tf.range(reward.shape[1].value)
mask = tf.cast(timestep[None, :] < length[:, None], tf.float32)
sequence = mask * reward + discount * value * (1 - lambda_)
discount = mask * discount * lambda_
sequence = tf.stac... | [
"def",
"lambda_return",
"(",
"reward",
",",
"value",
",",
"length",
",",
"discount",
",",
"lambda_",
")",
":",
"timestep",
"=",
"tf",
".",
"range",
"(",
"reward",
".",
"shape",
"[",
"1",
"]",
".",
"value",
")",
"mask",
"=",
"tf",
".",
"cast",
"(",
... | TD-lambda returns. | [
"TD",
"-",
"lambda",
"returns",
"."
] | python | train | 50.666667 |
saltstack/salt | salt/modules/azurearm_compute.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L512-L537 | def virtual_machines_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual machines within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_all
'''
result = {}
compconn = __utils__['azurearm.get_client']('comput... | [
"def",
"virtual_machines_list_all",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"vms",
"=",
"__utils__",
"[",
"'a... | .. versionadded:: 2019.2.0
List all virtual machines within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_all | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train | 26.461538 |
facebook/watchman | python/pywatchman/capabilities.py | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/capabilities.py#L59-L77 | def synthesize(vers, opts):
""" Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets
"""
parsed_version = parse_version(vers["version"])
vers["capabilities"] = {}
for name in opts["optional"]:
vers["capabilities"][name] ... | [
"def",
"synthesize",
"(",
"vers",
",",
"opts",
")",
":",
"parsed_version",
"=",
"parse_version",
"(",
"vers",
"[",
"\"version\"",
"]",
")",
"vers",
"[",
"\"capabilities\"",
"]",
"=",
"{",
"}",
"for",
"name",
"in",
"opts",
"[",
"\"optional\"",
"]",
":",
... | Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets | [
"Synthesize",
"a",
"capability",
"enabled",
"version",
"response",
"This",
"is",
"a",
"very",
"limited",
"emulation",
"for",
"relatively",
"recent",
"feature",
"sets"
] | python | train | 37.631579 |
mjirik/imtools | imtools/datasets.py | https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/datasets.py#L14-L47 | def sliver_reader(filename_end_mask="*[0-9].mhd", sliver_reference_dir="~/data/medical/orig/sliver07/training/", read_orig=True, read_seg=False):
"""
Generator for reading sliver data from directory structure.
:param filename_end_mask: file selection can be controlled with this parameter
:param sliver_... | [
"def",
"sliver_reader",
"(",
"filename_end_mask",
"=",
"\"*[0-9].mhd\"",
",",
"sliver_reference_dir",
"=",
"\"~/data/medical/orig/sliver07/training/\"",
",",
"read_orig",
"=",
"True",
",",
"read_seg",
"=",
"False",
")",
":",
"sliver_reference_dir",
"=",
"op",
".",
"ex... | Generator for reading sliver data from directory structure.
:param filename_end_mask: file selection can be controlled with this parameter
:param sliver_reference_dir: directory with sliver .mhd and .raw files
:param read_orig: read image data if is set True
:param read_seg: read segmentation data if i... | [
"Generator",
"for",
"reading",
"sliver",
"data",
"from",
"directory",
"structure",
"."
] | python | train | 41.558824 |
blockstack/blockstack-core | api/search/substring_search.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/search/substring_search.py#L41-L50 | def anyword_substring_search_inner(query_word, target_words):
""" return True if ANY target_word matches a query_word
"""
for target_word in target_words:
if(target_word.startswith(query_word)):
return query_word
return False | [
"def",
"anyword_substring_search_inner",
"(",
"query_word",
",",
"target_words",
")",
":",
"for",
"target_word",
"in",
"target_words",
":",
"if",
"(",
"target_word",
".",
"startswith",
"(",
"query_word",
")",
")",
":",
"return",
"query_word",
"return",
"False"
] | return True if ANY target_word matches a query_word | [
"return",
"True",
"if",
"ANY",
"target_word",
"matches",
"a",
"query_word"
] | python | train | 25.5 |
anuragkumarak95/wordnet | wordnet/tf_idf_generator.py | https://github.com/anuragkumarak95/wordnet/blob/7aba239ddebb0971e9e76124890373b60a2573c8/wordnet/tf_idf_generator.py#L35-L89 | def find_tf_idf(file_names=['./../test/testdata'],prev_file_path=None, dump_path=None):
'''Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate... | [
"def",
"find_tf_idf",
"(",
"file_names",
"=",
"[",
"'./../test/testdata'",
"]",
",",
"prev_file_path",
"=",
"None",
",",
"dump_path",
"=",
"None",
")",
":",
"tf_idf",
"=",
"[",
"]",
"# will hold a dict of word_count for every doc(line in a doc in this case)",
"df",
"=... | Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate a new tfidf list which overrides over an old one by mentioning its path.
@Args:
--
... | [
"Function",
"to",
"create",
"a",
"TF",
"-",
"IDF",
"list",
"of",
"dictionaries",
"for",
"a",
"corpus",
"of",
"docs",
".",
"If",
"you",
"opt",
"for",
"dumping",
"the",
"data",
"you",
"can",
"provide",
"a",
"file_path",
"with",
".",
"tfidfpkl",
"extension"... | python | train | 49.563636 |
bwohlberg/sporco | sporco/dictlrn/prlcnscdl.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/dictlrn/prlcnscdl.py#L687-L700 | def cbpdnmd_ystep(k):
"""Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
if mp_W.shape[0] > 1:
W = mp_W[k]
else:
W = mp_W
AXU0 = mp_DX[k] - mp_S[k] + mp_Z... | [
"def",
"cbpdnmd_ystep",
"(",
"k",
")",
":",
"if",
"mp_W",
".",
"shape",
"[",
"0",
"]",
">",
"1",
":",
"W",
"=",
"mp_W",
"[",
"k",
"]",
"else",
":",
"W",
"=",
"mp_W",
"AXU0",
"=",
"mp_DX",
"[",
"k",
"]",
"-",
"mp_S",
"[",
"k",
"]",
"+",
"m... | Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables. | [
"Do",
"the",
"Y",
"step",
"of",
"the",
"cbpdn",
"stage",
".",
"The",
"only",
"parameter",
"is",
"the",
"slice",
"index",
"k",
"and",
"there",
"are",
"no",
"return",
"values",
";",
"all",
"inputs",
"and",
"outputs",
"are",
"from",
"and",
"to",
"global",... | python | train | 32.142857 |
twilio/twilio-python | twilio/rest/proxy/v1/service/session/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/proxy/v1/service/session/__init__.py#L154-L163 | def get(self, sid):
"""
Constructs a SessionContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.session.SessionContext
:rtype: twilio.rest.proxy.v1.service.session.SessionContext
"""
return SessionContext(sel... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"SessionContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | Constructs a SessionContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.proxy.v1.service.session.SessionContext
:rtype: twilio.rest.proxy.v1.service.session.SessionContext | [
"Constructs",
"a",
"SessionContext"
] | python | train | 37.6 |
autokey/autokey | lib/autokey/scripting.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L700-L715 | def choose_colour(self, title="Select Colour", **kwargs):
"""
Show a Colour Chooser dialog
Usage: C{dialog.choose_colour(title="Select Colour")}
@param title: window title for the dialog
@return:
@rtype: C{DialogData(int, Optional[ColourData])}
"... | [
"def",
"choose_colour",
"(",
"self",
",",
"title",
"=",
"\"Select Colour\"",
",",
"*",
"*",
"kwargs",
")",
":",
"return_data",
"=",
"self",
".",
"_run_zenity",
"(",
"title",
",",
"[",
"\"--color-selection\"",
"]",
",",
"kwargs",
")",
"if",
"return_data",
"... | Show a Colour Chooser dialog
Usage: C{dialog.choose_colour(title="Select Colour")}
@param title: window title for the dialog
@return:
@rtype: C{DialogData(int, Optional[ColourData])} | [
"Show",
"a",
"Colour",
"Chooser",
"dialog",
"Usage",
":",
"C",
"{",
"dialog",
".",
"choose_colour",
"(",
"title",
"=",
"Select",
"Colour",
")",
"}"
] | python | train | 40.5625 |
textbook/aslack | aslack/slack_bot/bot.py | https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L267-L285 | def _validate_first_message(cls, msg):
"""Check the first message matches the expected handshake.
Note:
The handshake is provided as :py:attr:`RTM_HANDSHAKE`.
Arguments:
msg (:py:class:`aiohttp.Message`): The message to validate.
Raises:
:py:class:`SlackA... | [
"def",
"_validate_first_message",
"(",
"cls",
",",
"msg",
")",
":",
"data",
"=",
"cls",
".",
"_unpack_message",
"(",
"msg",
")",
"logger",
".",
"debug",
"(",
"data",
")",
"if",
"data",
"!=",
"cls",
".",
"RTM_HANDSHAKE",
":",
"raise",
"SlackApiError",
"("... | Check the first message matches the expected handshake.
Note:
The handshake is provided as :py:attr:`RTM_HANDSHAKE`.
Arguments:
msg (:py:class:`aiohttp.Message`): The message to validate.
Raises:
:py:class:`SlackApiError`: If the data doesn't match the
... | [
"Check",
"the",
"first",
"message",
"matches",
"the",
"expected",
"handshake",
"."
] | python | valid | 32.421053 |
ARMmbed/yotta | yotta/lib/cmakegen.py | https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/cmakegen.py#L175-L200 | def _validateListedSubdirsExist(self, component):
''' Return true if all the subdirectories which this component lists in
its module.json file exist (although their validity is otherwise
not checked).
If they don't, warning messages are printed.
'''
lib_subdi... | [
"def",
"_validateListedSubdirsExist",
"(",
"self",
",",
"component",
")",
":",
"lib_subdirs",
"=",
"component",
".",
"getLibs",
"(",
"explicit_only",
"=",
"True",
")",
"bin_subdirs",
"=",
"component",
".",
"getBinaries",
"(",
")",
"ok",
"=",
"True",
"for",
"... | Return true if all the subdirectories which this component lists in
its module.json file exist (although their validity is otherwise
not checked).
If they don't, warning messages are printed. | [
"Return",
"true",
"if",
"all",
"the",
"subdirectories",
"which",
"this",
"component",
"lists",
"in",
"its",
"module",
".",
"json",
"file",
"exist",
"(",
"although",
"their",
"validity",
"is",
"otherwise",
"not",
"checked",
")",
"."
] | python | valid | 38.538462 |
istresearch/scrapy-cluster | crawler/crawling/log_retry_middleware.py | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/log_retry_middleware.py#L149-L161 | def _increment_504_stat(self, request):
'''
Increments the 504 stat counters
@param request: The scrapy request in the spider
'''
for key in self.stats_dict:
if key == 'lifetime':
unique = request.url + str(time.time())
self.stats_dict... | [
"def",
"_increment_504_stat",
"(",
"self",
",",
"request",
")",
":",
"for",
"key",
"in",
"self",
".",
"stats_dict",
":",
"if",
"key",
"==",
"'lifetime'",
":",
"unique",
"=",
"request",
".",
"url",
"+",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
... | Increments the 504 stat counters
@param request: The scrapy request in the spider | [
"Increments",
"the",
"504",
"stat",
"counters"
] | python | train | 35.615385 |
inasafe/inasafe | safe/datastore/folder.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/folder.py#L125-L144 | def layer_uri(self, layer_name):
"""Get layer URI.
:param layer_name: The name of the layer to fetch.
:type layer_name: str
:return: The URI to the layer.
:rtype: str
.. versionadded:: 4.0
"""
layers = self.layers()
for layer, extension in produ... | [
"def",
"layer_uri",
"(",
"self",
",",
"layer_name",
")",
":",
"layers",
"=",
"self",
".",
"layers",
"(",
")",
"for",
"layer",
",",
"extension",
"in",
"product",
"(",
"layers",
",",
"EXTENSIONS",
")",
":",
"one_file",
"=",
"QFileInfo",
"(",
"self",
".",... | Get layer URI.
:param layer_name: The name of the layer to fetch.
:type layer_name: str
:return: The URI to the layer.
:rtype: str
.. versionadded:: 4.0 | [
"Get",
"layer",
"URI",
"."
] | python | train | 29.95 |
waqasbhatti/astrobase | astrobase/lcproc/varthreshold.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/varthreshold.py#L96-L699 | def variability_threshold(featuresdir,
outfile,
magbins=DEFAULT_MAGBINS,
maxobjects=None,
timecols=None,
magcols=None,
errcols=None,
lcfor... | [
"def",
"variability_threshold",
"(",
"featuresdir",
",",
"outfile",
",",
"magbins",
"=",
"DEFAULT_MAGBINS",
",",
"maxobjects",
"=",
"None",
",",
"timecols",
"=",
"None",
",",
"magcols",
"=",
"None",
",",
"errcols",
"=",
"None",
",",
"lcformat",
"=",
"'hat-sq... | This generates a list of objects with stetson J, IQR, and 1.0/eta
above some threshold value to select them as potential variable stars.
Use this to pare down the objects to review and put through
period-finding. This does the thresholding per magnitude bin; this should be
better than one single cut th... | [
"This",
"generates",
"a",
"list",
"of",
"objects",
"with",
"stetson",
"J",
"IQR",
"and",
"1",
".",
"0",
"/",
"eta",
"above",
"some",
"threshold",
"value",
"to",
"select",
"them",
"as",
"potential",
"variable",
"stars",
"."
] | python | valid | 37.875828 |
abusque/qng | qng/generator.py | https://github.com/abusque/qng/blob/93d2efd637b2a6bba7d3872fb9ff2bb3fc5c979d/qng/generator.py#L83-L91 | def _get_names(self):
"""Get the list of first names.
:return: A list of first name entries.
"""
names = self._read_name_file('names.json')
names = self._compute_weights(names)
return names | [
"def",
"_get_names",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"_read_name_file",
"(",
"'names.json'",
")",
"names",
"=",
"self",
".",
"_compute_weights",
"(",
"names",
")",
"return",
"names"
] | Get the list of first names.
:return: A list of first name entries. | [
"Get",
"the",
"list",
"of",
"first",
"names",
"."
] | python | train | 25.666667 |
pywbem/pywbem | examples/enuminstances.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/enuminstances.py#L74-L100 | def main():
""" Get arguments and call the execution function"""
if len(sys.argv) < 6:
print("Usage: %s server_url username password namespace' \
' classname" % sys.argv[0])
print('Using internal defaults')
server_url = SERVER_URL
namespace = TEST_NAMESPACE
... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"6",
":",
"print",
"(",
"\"Usage: %s server_url username password namespace' \\\n ' classname\"",
"%",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"print",
"(",
"'Using inte... | Get arguments and call the execution function | [
"Get",
"arguments",
"and",
"call",
"the",
"execution",
"function"
] | python | train | 29.777778 |
saltstack/salt | salt/utils/dictdiffer.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictdiffer.py#L247-L269 | def added(self):
'''
Returns all keys that have been added.
If the keys are in child dictionaries they will be represented with
. notation
'''
def _added(diffs, prefix):
keys = []
for key in diffs.keys():
if isinstance(diffs[key], ... | [
"def",
"added",
"(",
"self",
")",
":",
"def",
"_added",
"(",
"diffs",
",",
"prefix",
")",
":",
"keys",
"=",
"[",
"]",
"for",
"key",
"in",
"diffs",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"diffs",
"[",
"key",
"]",
",",
"dict",
")",
... | Returns all keys that have been added.
If the keys are in child dictionaries they will be represented with
. notation | [
"Returns",
"all",
"keys",
"that",
"have",
"been",
"added",
"."
] | python | train | 39.826087 |
couchbase/couchbase-python-client | couchbase/subdocument.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L132-L141 | def replace(path, value, **kwargs):
"""
Replace an existing path. This works on any valid path if the path already
exists. Valid only in :cb_bmeth:`mutate_in`
:param path: The path to replace
:param value: The new value
"""
return _gen_4spec(LCB_SDCMD_REPLACE, path, value,
... | [
"def",
"replace",
"(",
"path",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gen_4spec",
"(",
"LCB_SDCMD_REPLACE",
",",
"path",
",",
"value",
",",
"create_path",
"=",
"False",
",",
"*",
"*",
"kwargs",
")"
] | Replace an existing path. This works on any valid path if the path already
exists. Valid only in :cb_bmeth:`mutate_in`
:param path: The path to replace
:param value: The new value | [
"Replace",
"an",
"existing",
"path",
".",
"This",
"works",
"on",
"any",
"valid",
"path",
"if",
"the",
"path",
"already",
"exists",
".",
"Valid",
"only",
"in",
":",
"cb_bmeth",
":",
"mutate_in"
] | python | train | 34.4 |
mottosso/Qt.py | examples/loadUi/baseinstance2.py | https://github.com/mottosso/Qt.py/blob/d88a0c1762ad90d1965008cc14c53504bbcc0061/examples/loadUi/baseinstance2.py#L54-L89 | def pyside_load_ui(uifile, base_instance=None):
"""Provide PyQt4.uic.loadUi functionality to PySide
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Note:
pysideuic is required for this to work with PySide.
... | [
"def",
"pyside_load_ui",
"(",
"uifile",
",",
"base_instance",
"=",
"None",
")",
":",
"form_class",
",",
"base_class",
"=",
"load_ui_type",
"(",
"uifile",
")",
"if",
"not",
"base_instance",
":",
"typeName",
"=",
"form_class",
".",
"__name__",
"finalType",
"=",
... | Provide PyQt4.uic.loadUi functionality to PySide
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Note:
pysideuic is required for this to work with PySide.
This seems to work correctly in Maya as well as outsid... | [
"Provide",
"PyQt4",
".",
"uic",
".",
"loadUi",
"functionality",
"to",
"PySide"
] | python | train | 35.083333 |
gwpy/gwpy | gwpy/io/datafind.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/datafind.py#L615-L626 | def find_types(observatory, match=None, trend=None,
connection=None, **connection_kw):
"""Find the available data types for a given observatory.
See also
--------
gwdatafind.http.HTTPConnection.find_types
FflConnection.find_types
for details on the underlying method(s)
""... | [
"def",
"find_types",
"(",
"observatory",
",",
"match",
"=",
"None",
",",
"trend",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"*",
"*",
"connection_kw",
")",
":",
"return",
"sorted",
"(",
"connection",
".",
"find_types",
"(",
"observatory",
",",
"m... | Find the available data types for a given observatory.
See also
--------
gwdatafind.http.HTTPConnection.find_types
FflConnection.find_types
for details on the underlying method(s) | [
"Find",
"the",
"available",
"data",
"types",
"for",
"a",
"given",
"observatory",
"."
] | python | train | 37.833333 |
O365/python-o365 | O365/connection.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/connection.py#L140-L165 | def get_scopes_for(self, user_provided_scopes):
""" Returns a list of scopes needed for each of the
scope_helpers provided, by adding the prefix to them if required
:param user_provided_scopes: a list of scopes or scope helpers
:type user_provided_scopes: list or tuple or str
:r... | [
"def",
"get_scopes_for",
"(",
"self",
",",
"user_provided_scopes",
")",
":",
"if",
"user_provided_scopes",
"is",
"None",
":",
"# return all available scopes",
"user_provided_scopes",
"=",
"[",
"app_part",
"for",
"app_part",
"in",
"self",
".",
"_oauth_scopes",
"]",
"... | Returns a list of scopes needed for each of the
scope_helpers provided, by adding the prefix to them if required
:param user_provided_scopes: a list of scopes or scope helpers
:type user_provided_scopes: list or tuple or str
:return: scopes with url prefix added
:rtype: list
... | [
"Returns",
"a",
"list",
"of",
"scopes",
"needed",
"for",
"each",
"of",
"the",
"scope_helpers",
"provided",
"by",
"adding",
"the",
"prefix",
"to",
"them",
"if",
"required"
] | python | train | 42.692308 |
ramses-tech/ramses | ramses/utils.py | https://github.com/ramses-tech/ramses/blob/ea2e1e896325b7256cdf5902309e05fd98e0c14c/ramses/utils.py#L345-L354 | def get_route_name(resource_uri):
""" Get route name from RAML resource URI.
:param resource_uri: String representing RAML resource URI.
:returns string: String with route name, which is :resource_uri:
stripped of non-word characters.
"""
resource_uri = resource_uri.strip('/')
resource_... | [
"def",
"get_route_name",
"(",
"resource_uri",
")",
":",
"resource_uri",
"=",
"resource_uri",
".",
"strip",
"(",
"'/'",
")",
"resource_uri",
"=",
"re",
".",
"sub",
"(",
"'\\W'",
",",
"''",
",",
"resource_uri",
")",
"return",
"resource_uri"
] | Get route name from RAML resource URI.
:param resource_uri: String representing RAML resource URI.
:returns string: String with route name, which is :resource_uri:
stripped of non-word characters. | [
"Get",
"route",
"name",
"from",
"RAML",
"resource",
"URI",
"."
] | python | train | 37.1 |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/extract.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/extract.py#L268-L315 | def psd(tachogram_time, tachogram_data):
"""
-----
Brief
-----
Determination of the Power Spectral Density Function (Fourier Domain)
-----------
Description
-----------
The Power Spectral Density Function allows to perceive the behavior of a given signal in terms of its frequency.
... | [
"def",
"psd",
"(",
"tachogram_time",
",",
"tachogram_data",
")",
":",
"init_time",
"=",
"tachogram_time",
"[",
"0",
"]",
"fin_time",
"=",
"tachogram_time",
"[",
"-",
"1",
"]",
"tck",
"=",
"interpol",
".",
"splrep",
"(",
"tachogram_time",
",",
"tachogram_data... | -----
Brief
-----
Determination of the Power Spectral Density Function (Fourier Domain)
-----------
Description
-----------
The Power Spectral Density Function allows to perceive the behavior of a given signal in terms of its frequency.
This procedure costs the time resolution of the si... | [
"-----",
"Brief",
"-----",
"Determination",
"of",
"the",
"Power",
"Spectral",
"Density",
"Function",
"(",
"Fourier",
"Domain",
")"
] | python | train | 35.125 |
pkgw/pwkit | pwkit/astutil.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/astutil.py#L338-L354 | def parsedeglat (latstr):
"""Parse a latitude formatted as sexagesimal degrees into an angle.
This function converts a textual representation of a latitude, measured in
degrees, into a floating point value measured in radians. The format of
*latstr* is very limited: it may not have leading or trailing ... | [
"def",
"parsedeglat",
"(",
"latstr",
")",
":",
"deg",
"=",
"_parsesexagesimal",
"(",
"latstr",
",",
"'latitude'",
",",
"True",
")",
"if",
"abs",
"(",
"deg",
")",
">",
"90",
":",
"raise",
"ValueError",
"(",
"'illegal latitude specification: '",
"+",
"latstr",... | Parse a latitude formatted as sexagesimal degrees into an angle.
This function converts a textual representation of a latitude, measured in
degrees, into a floating point value measured in radians. The format of
*latstr* is very limited: it may not have leading or trailing whitespace,
and the component... | [
"Parse",
"a",
"latitude",
"formatted",
"as",
"sexagesimal",
"degrees",
"into",
"an",
"angle",
"."
] | python | train | 47.823529 |
saltstack/salt | salt/modules/lxd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxd.py#L804-L850 | def container_rename(name, newname, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Rename a container
name :
Name of the container to Rename
newname :
The new name of the contianer
remote_addr :
An URL to a remote Server, you also have t... | [
"def",
"container_rename",
"(",
"name",
",",
"newname",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
"container",
"=",
"container_get",
"(",
"name",
",",
"remote_addr",
","... | Rename a container
name :
Name of the container to Rename
newname :
The new name of the contianer
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!
Examples:
https://myserver.l... | [
"Rename",
"a",
"container"
] | python | train | 25.617021 |
Capitains/MyCapytain | MyCapytain/resources/texts/local/capitains/cts.py | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L672-L676 | def next(self):
""" Next CapitainsCtsPassage (Interactive CapitainsCtsPassage)
"""
if self.nextId is not None:
return super(CapitainsCtsPassage, self).getTextualNode(subreference=self.nextId) | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"nextId",
"is",
"not",
"None",
":",
"return",
"super",
"(",
"CapitainsCtsPassage",
",",
"self",
")",
".",
"getTextualNode",
"(",
"subreference",
"=",
"self",
".",
"nextId",
")"
] | Next CapitainsCtsPassage (Interactive CapitainsCtsPassage) | [
"Next",
"CapitainsCtsPassage",
"(",
"Interactive",
"CapitainsCtsPassage",
")"
] | python | train | 44.6 |
aboSamoor/polyglot | polyglot/load.py | https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/load.py#L107-L117 | def load_pos_model(lang="en", version="2"):
"""Return a part of speech tagger parameters for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used.
"""
src_dir = "pos{}".format(version)
p = locate_resource(src_dir, lang)
fh = _ope... | [
"def",
"load_pos_model",
"(",
"lang",
"=",
"\"en\"",
",",
"version",
"=",
"\"2\"",
")",
":",
"src_dir",
"=",
"\"pos{}\"",
".",
"format",
"(",
"version",
")",
"p",
"=",
"locate_resource",
"(",
"src_dir",
",",
"lang",
")",
"fh",
"=",
"_open",
"(",
"p",
... | Return a part of speech tagger parameters for `lang` and of version `version`
Args:
lang (string): language code.
version (string): version of the parameters to be used. | [
"Return",
"a",
"part",
"of",
"speech",
"tagger",
"parameters",
"for",
"lang",
"and",
"of",
"version",
"version"
] | python | train | 31 |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L25044-L25075 | def set_visible_region(self, rectangles, count):
"""Suggests a new visible region to this frame buffer. This region
represents the area of the VM display which is a union of regions of
all top-level windows of the guest operating system running inside the
VM (if the Guest Additions for t... | [
"def",
"set_visible_region",
"(",
"self",
",",
"rectangles",
",",
"count",
")",
":",
"if",
"not",
"isinstance",
"(",
"rectangles",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"rectangles can only be an instance of type basestring\"",
")",
"if",
"not",
... | Suggests a new visible region to this frame buffer. This region
represents the area of the VM display which is a union of regions of
all top-level windows of the guest operating system running inside the
VM (if the Guest Additions for this system support this
functionality). This informa... | [
"Suggests",
"a",
"new",
"visible",
"region",
"to",
"this",
"frame",
"buffer",
".",
"This",
"region",
"represents",
"the",
"area",
"of",
"the",
"VM",
"display",
"which",
"is",
"a",
"union",
"of",
"regions",
"of",
"all",
"top",
"-",
"level",
"windows",
"of... | python | train | 40.1875 |
MSchnei/pyprf_feature | pyprf_feature/analysis/save_fit_tc_nii.py | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/save_fit_tc_nii.py#L39-L292 | def save_tc_to_nii(strCsvCnfg, lgcTest=False, lstRat=None, lgcMdlRsp=False,
strPathHrf=None, lgcSaveRam=False):
"""
Save empirical and fitted time courses to nii file format.
Parameters
----------
strCsvCnfg : str
Absolute file path of config file used for pRF fitting.
... | [
"def",
"save_tc_to_nii",
"(",
"strCsvCnfg",
",",
"lgcTest",
"=",
"False",
",",
"lstRat",
"=",
"None",
",",
"lgcMdlRsp",
"=",
"False",
",",
"strPathHrf",
"=",
"None",
",",
"lgcSaveRam",
"=",
"False",
")",
":",
"# %% Load configuration settings that were used for fi... | Save empirical and fitted time courses to nii file format.
Parameters
----------
strCsvCnfg : str
Absolute file path of config file used for pRF fitting.
lgcTest : boolean
Whether this is a test (pytest). If yes, absolute path of pyprf libary
will be prepended to config file pat... | [
"Save",
"empirical",
"and",
"fitted",
"time",
"courses",
"to",
"nii",
"file",
"format",
"."
] | python | train | 41.066929 |
elastic/elasticsearch-py | elasticsearch/client/indices.py | https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/indices.py#L478-L496 | def delete_alias(self, index, name, params=None):
"""
Delete specific alias.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names (supports wildcards);
use `_all` for all indices
:a... | [
"def",
"delete_alias",
"(",
"self",
",",
"index",
",",
"name",
",",
"params",
"=",
"None",
")",
":",
"for",
"param",
"in",
"(",
"index",
",",
"name",
")",
":",
"if",
"param",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(",
"\"Empty value passed fo... | Delete specific alias.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names (supports wildcards);
use `_all` for all indices
:arg name: A comma-separated list of aliases to delete (supports
... | [
"Delete",
"specific",
"alias",
".",
"<http",
":",
"//",
"www",
".",
"elastic",
".",
"co",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"current",
"/",
"indices",
"-",
"aliases",
".",
"html",
">",
"_"
] | python | train | 46.789474 |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L344-L359 | def send_response(self, body, set_content_type=True):
"""
Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True`
"""
s... | [
"def",
"send_response",
"(",
"self",
",",
"body",
",",
"set_content_type",
"=",
"True",
")",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"handler",
"=",
"settings",
"[",
"self",
".",
"get_... | Serialize and send ``body`` in the response.
:param dict body: the body to serialize
:param bool set_content_type: should the :http:header:`Content-Type`
header be set? Defaults to :data:`True` | [
"Serialize",
"and",
"send",
"body",
"in",
"the",
"response",
"."
] | python | train | 40.5625 |
scot-dev/scot | scot/matfiles.py | https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/matfiles.py#L25-L33 | def _check_keys(dictionary):
"""
checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
"""
for key in dictionary:
if isinstance(dictionary[key], matlab.mio5_params.mat_struct):
dictionary[key] = _todict(dictionary[key])
... | [
"def",
"_check_keys",
"(",
"dictionary",
")",
":",
"for",
"key",
"in",
"dictionary",
":",
"if",
"isinstance",
"(",
"dictionary",
"[",
"key",
"]",
",",
"matlab",
".",
"mio5_params",
".",
"mat_struct",
")",
":",
"dictionary",
"[",
"key",
"]",
"=",
"_todict... | checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries | [
"checks",
"if",
"entries",
"in",
"dictionary",
"are",
"mat",
"-",
"objects",
".",
"If",
"yes",
"todict",
"is",
"called",
"to",
"change",
"them",
"to",
"nested",
"dictionaries"
] | python | train | 36.666667 |
astrocatalogs/astrocats | astrocats/catalog/spectrum.py | https://github.com/astrocatalogs/astrocats/blob/11abc3131c6366ecd23964369e55ff264add7805/astrocats/catalog/spectrum.py#L135-L158 | def is_duplicate_of(self, other):
"""Check if spectrum is duplicate of another."""
if super(Spectrum, self).is_duplicate_of(other):
return True
row_matches = 0
for ri, row in enumerate(self.get(self._KEYS.DATA, [])):
lambda1, flux1 = tuple(row[0:2])
if... | [
"def",
"is_duplicate_of",
"(",
"self",
",",
"other",
")",
":",
"if",
"super",
"(",
"Spectrum",
",",
"self",
")",
".",
"is_duplicate_of",
"(",
"other",
")",
":",
"return",
"True",
"row_matches",
"=",
"0",
"for",
"ri",
",",
"row",
"in",
"enumerate",
"(",... | Check if spectrum is duplicate of another. | [
"Check",
"if",
"spectrum",
"is",
"duplicate",
"of",
"another",
"."
] | python | train | 45.666667 |
pndurette/gTTS | gtts/tts.py | https://github.com/pndurette/gTTS/blob/b01ac4eb22d40c6241202e202d0418ccf4f98460/gtts/tts.py#L238-L250 | def save(self, savefile):
"""Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
"""
with open(str(savefile), 'w... | [
"def",
"save",
"(",
"self",
",",
"savefile",
")",
":",
"with",
"open",
"(",
"str",
"(",
"savefile",
")",
",",
"'wb'",
")",
"as",
"f",
":",
"self",
".",
"write_to_fp",
"(",
"f",
")",
"log",
".",
"debug",
"(",
"\"Saved to %s\"",
",",
"savefile",
")"
... | Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request. | [
"Do",
"the",
"TTS",
"API",
"request",
"and",
"write",
"result",
"to",
"file",
"."
] | python | train | 30.461538 |
peri-source/peri | peri/runner.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/runner.py#L583-L617 | def _pick_state_im_name(state_name, im_name, use_full_path=False):
"""
If state_name or im_name is None, picks them interactively through Tk,
and then sets with or without the full path.
Parameters
----------
state_name : {string, None}
The name of the state. If None, selected t... | [
"def",
"_pick_state_im_name",
"(",
"state_name",
",",
"im_name",
",",
"use_full_path",
"=",
"False",
")",
":",
"initial_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"(",
"state_name",
"is",
"None",
")",
"or",
"(",
"im_name",
"is",
"None",
")",
":",
... | If state_name or im_name is None, picks them interactively through Tk,
and then sets with or without the full path.
Parameters
----------
state_name : {string, None}
The name of the state. If None, selected through Tk.
im_name : {string, None}
The name of the image. ... | [
"If",
"state_name",
"or",
"im_name",
"is",
"None",
"picks",
"them",
"interactively",
"through",
"Tk",
"and",
"then",
"sets",
"with",
"or",
"without",
"the",
"full",
"path",
"."
] | python | valid | 36.285714 |
Baguage/django-auth-pubtkt | django_auth_pubtkt/auth_pubtkt.py | https://github.com/Baguage/django-auth-pubtkt/blob/d3f4284212ffbfdc3588929a31e36a4cc7f39786/django_auth_pubtkt/auth_pubtkt.py#L45-L73 | def verify_ticket_signature(self, data, sig):
"""Verify ticket signature. """
try:
signature = base64.b64decode(sig)
except TypeError as e:
if hasattr(self, "debug"):
print("Exception in function base64.b64decode. File %s" % (__file__))
... | [
"def",
"verify_ticket_signature",
"(",
"self",
",",
"data",
",",
"sig",
")",
":",
"try",
":",
"signature",
"=",
"base64",
".",
"b64decode",
"(",
"sig",
")",
"except",
"TypeError",
"as",
"e",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"debug\"",
")",
":"... | Verify ticket signature. | [
"Verify",
"ticket",
"signature",
"."
] | python | train | 40.896552 |
xapple/plumbing | plumbing/databases/sqlite_database.py | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/databases/sqlite_database.py#L134-L140 | def new_connection(self):
"""Make a new connection."""
if not self.prepared: self.prepare()
con = sqlite3.connect(self.path, isolation_level=self.isolation)
con.row_factory = self.factory
if self.text_fact: con.text_factory = self.text_fact
return con | [
"def",
"new_connection",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"prepared",
":",
"self",
".",
"prepare",
"(",
")",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"path",
",",
"isolation_level",
"=",
"self",
".",
"isolation",
")",
... | Make a new connection. | [
"Make",
"a",
"new",
"connection",
"."
] | python | train | 41.857143 |
fastai/fastai | fastai/vision/image.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L547-L556 | def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField:
"Multiply `c` by `m` - can adjust for rectangular shaped `c`."
if m is None: return c
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).vie... | [
"def",
"_affine_mult",
"(",
"c",
":",
"FlowField",
",",
"m",
":",
"AffineMatrix",
")",
"->",
"FlowField",
":",
"if",
"m",
"is",
"None",
":",
"return",
"c",
"size",
"=",
"c",
".",
"flow",
".",
"size",
"(",
")",
"h",
",",
"w",
"=",
"c",
".",
"siz... | Multiply `c` by `m` - can adjust for rectangular shaped `c`. | [
"Multiply",
"c",
"by",
"m",
"-",
"can",
"adjust",
"for",
"rectangular",
"shaped",
"c",
"."
] | python | train | 33.1 |
saltstack/salt | salt/renderers/aws_kms.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/aws_kms.py#L125-L151 | def _session():
'''
Return the boto3 session to use for the KMS client.
If aws_kms:profile_name is set in the salt configuration, use that profile.
Otherwise, fall back on the default aws profile.
We use the boto3 profile system to avoid having to duplicate
individual boto3 configuration setti... | [
"def",
"_session",
"(",
")",
":",
"profile_name",
"=",
"_cfg",
"(",
"'profile_name'",
")",
"if",
"profile_name",
":",
"log",
".",
"info",
"(",
"'Using the \"%s\" aws profile.'",
",",
"profile_name",
")",
"else",
":",
"log",
".",
"info",
"(",
"'aws_kms:profile_... | Return the boto3 session to use for the KMS client.
If aws_kms:profile_name is set in the salt configuration, use that profile.
Otherwise, fall back on the default aws profile.
We use the boto3 profile system to avoid having to duplicate
individual boto3 configuration settings in salt configuration. | [
"Return",
"the",
"boto3",
"session",
"to",
"use",
"for",
"the",
"KMS",
"client",
"."
] | python | train | 46.555556 |
cozy/python_cozy_management | cozy_management/couchdb.py | https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/couchdb.py#L62-L81 | def curl_couchdb(url, method='GET', base_url=BASE_URL, data=None):
'''
Launch a curl on CouchDB instance
'''
(username, password) = get_admin()
if username is None:
auth = None
else:
auth = (username, password)
if method == 'PUT':
req = requests.put('{}{}'.format... | [
"def",
"curl_couchdb",
"(",
"url",
",",
"method",
"=",
"'GET'",
",",
"base_url",
"=",
"BASE_URL",
",",
"data",
"=",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"get_admin",
"(",
")",
"if",
"username",
"is",
"None",
":",
"auth",
"=",... | Launch a curl on CouchDB instance | [
"Launch",
"a",
"curl",
"on",
"CouchDB",
"instance"
] | python | train | 32.15 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L188-L200 | def _infinite_iterator(self):
"""this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is up to the implementation of t... | [
"def",
"_infinite_iterator",
"(",
"self",
")",
":",
"while",
"True",
":",
"for",
"crash_id",
"in",
"self",
".",
"_basic_iterator",
"(",
")",
":",
"if",
"self",
".",
"_filter_disallowed_values",
"(",
"crash_id",
")",
":",
"continue",
"yield",
"crash_id"
] | this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is up to the implementation of the innermost
iterator to define w... | [
"this",
"iterator",
"wraps",
"the",
"_basic_iterator",
"when",
"the",
"configuration",
"specifies",
"that",
"the",
"number_of_submissions",
"is",
"set",
"to",
"forever",
".",
"Whenever",
"the",
"_basic_iterator",
"is",
"exhausted",
"it",
"is",
"called",
"again",
"... | python | train | 52.538462 |
Richienb/quilt | src/quilt_lang/__init__.py | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L200-L235 | def binboolflip(item):
"""
Convert 0 or 1 to False or True (or vice versa).
The converter works as follows:
- 0 > False
- False > 0
- 1 > True
- True > 1
:type item: integer or boolean
:param item: The item to convert.
>>> binboolflip(0)
False
>>> binboolflip(False)
... | [
"def",
"binboolflip",
"(",
"item",
")",
":",
"if",
"item",
"in",
"[",
"0",
",",
"False",
",",
"1",
",",
"True",
"]",
":",
"return",
"int",
"(",
"item",
")",
"if",
"isinstance",
"(",
"item",
",",
"bool",
")",
"else",
"bool",
"(",
"item",
")",
"#... | Convert 0 or 1 to False or True (or vice versa).
The converter works as follows:
- 0 > False
- False > 0
- 1 > True
- True > 1
:type item: integer or boolean
:param item: The item to convert.
>>> binboolflip(0)
False
>>> binboolflip(False)
0
>>> binboolflip(1)
Tr... | [
"Convert",
"0",
"or",
"1",
"to",
"False",
"or",
"True",
"(",
"or",
"vice",
"versa",
")",
".",
"The",
"converter",
"works",
"as",
"follows",
":"
] | python | train | 18.194444 |
saltstack/salt | salt/modules/glusterfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glusterfs.py#L442-L472 | def start_volume(name, force=False):
'''
Start a gluster volume
name
Volume name
force
Force the volume start even if the volume is started
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.start mycluster
'''
cmd = 'volu... | [
"def",
"start_volume",
"(",
"name",
",",
"force",
"=",
"False",
")",
":",
"cmd",
"=",
"'volume start {0}'",
".",
"format",
"(",
"name",
")",
"if",
"force",
":",
"cmd",
"=",
"'{0} force'",
".",
"format",
"(",
"cmd",
")",
"volinfo",
"=",
"info",
"(",
"... | Start a gluster volume
name
Volume name
force
Force the volume start even if the volume is started
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.start mycluster | [
"Start",
"a",
"gluster",
"volume"
] | python | train | 21.225806 |
tensorflow/tensor2tensor | tensor2tensor/utils/expert_utils.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/expert_utils.py#L405-L434 | def _my_top_k(x, k):
"""GPU-compatible version of top-k that works for very small constant k.
Calls argmax repeatedly.
tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,
seems not to be, so if we use tf.nn.top_k, then both the top_k and its
gradient go on cpu. Once this is not an issue,... | [
"def",
"_my_top_k",
"(",
"x",
",",
"k",
")",
":",
"if",
"k",
">",
"10",
":",
"return",
"tf",
".",
"nn",
".",
"top_k",
"(",
"x",
",",
"k",
")",
"values",
"=",
"[",
"]",
"indices",
"=",
"[",
"]",
"depth",
"=",
"tf",
".",
"shape",
"(",
"x",
... | GPU-compatible version of top-k that works for very small constant k.
Calls argmax repeatedly.
tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,
seems not to be, so if we use tf.nn.top_k, then both the top_k and its
gradient go on cpu. Once this is not an issue, this function becomes
o... | [
"GPU",
"-",
"compatible",
"version",
"of",
"top",
"-",
"k",
"that",
"works",
"for",
"very",
"small",
"constant",
"k",
"."
] | python | train | 29.333333 |
klen/makesite | makesite/main.py | https://github.com/klen/makesite/blob/f6f77a43a04a256189e8fffbeac1ffd63f35a10c/makesite/main.py#L161-L168 | def shell(args):
" A helper command to be used for shell integration "
print
print "# Makesite integration "
print "# ==================== "
print "export MAKESITE_HOME=%s" % args.path
print "source %s" % op.join(settings.BASEDIR, 'shell.sh')
print | [
"def",
"shell",
"(",
"args",
")",
":",
"print",
"print",
"\"# Makesite integration \"",
"print",
"\"# ==================== \"",
"print",
"\"export MAKESITE_HOME=%s\"",
"%",
"args",
".",
"path",
"print",
"\"source %s\"",
"%",
"op",
".",
"join",
"(",
"settings",
".",
... | A helper command to be used for shell integration | [
"A",
"helper",
"command",
"to",
"be",
"used",
"for",
"shell",
"integration"
] | python | train | 33.625 |
Garee/pytodoist | pytodoist/todoist.py | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/todoist.py#L625-L639 | def get_label(self, label_name):
"""Return the user's label that has a given name.
:param label_name: The name to search for.
:type label_name: str
:return: A label that has a matching name or ``None`` if not found.
:rtype: :class:`pytodoist.todoist.Label`
>>> from pyto... | [
"def",
"get_label",
"(",
"self",
",",
"label_name",
")",
":",
"for",
"label",
"in",
"self",
".",
"get_labels",
"(",
")",
":",
"if",
"label",
".",
"name",
"==",
"label_name",
":",
"return",
"label"
] | Return the user's label that has a given name.
:param label_name: The name to search for.
:type label_name: str
:return: A label that has a matching name or ``None`` if not found.
:rtype: :class:`pytodoist.todoist.Label`
>>> from pytodoist import todoist
>>> user = todo... | [
"Return",
"the",
"user",
"s",
"label",
"that",
"has",
"a",
"given",
"name",
"."
] | python | train | 37.333333 |
omza/azurestoragewrap | azurestoragewrap/blob.py | https://github.com/omza/azurestoragewrap/blob/976878e95d82ff0f7d8a00a5e4a7a3fb6268ab08/azurestoragewrap/blob.py#L449-L473 | def download(self, storagemodel:object, modeldefinition = None):
""" load blob from storage into StorageBlobModelInstance """
if (storagemodel.name is None):
# No content to download
raise AzureStorageWrapException(storagemodel, "StorageBlobModel does not contain content nor con... | [
"def",
"download",
"(",
"self",
",",
"storagemodel",
":",
"object",
",",
"modeldefinition",
"=",
"None",
")",
":",
"if",
"(",
"storagemodel",
".",
"name",
"is",
"None",
")",
":",
"# No content to download",
"raise",
"AzureStorageWrapException",
"(",
"storagemode... | load blob from storage into StorageBlobModelInstance | [
"load",
"blob",
"from",
"storage",
"into",
"StorageBlobModelInstance"
] | python | train | 45.32 |
slackapi/python-slackclient | slack/web/client.py | https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/web/client.py#L591-L598 | def files_info(self, *, id: str, **kwargs) -> SlackResponse:
"""Gets information about a team file.
Args:
id (str): The file id. e.g. 'F1234467890'
"""
kwargs.update({"id": id})
return self.api_call("files.info", http_verb="GET", params=kwargs) | [
"def",
"files_info",
"(",
"self",
",",
"*",
",",
"id",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"id\"",
":",
"id",
"}",
")",
"return",
"self",
".",
"api_call",
"(",
"\"files.info\"",
... | Gets information about a team file.
Args:
id (str): The file id. e.g. 'F1234467890' | [
"Gets",
"information",
"about",
"a",
"team",
"file",
"."
] | python | train | 36.25 |
edx/edx-enterprise | integrated_channels/sap_success_factors/exporters/utils.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/exporters/utils.py#L29-L47 | def transform_language_code(code):
"""
Transform ISO language code (e.g. en-us) to the language name expected by SAPSF.
"""
if code is None:
return 'English'
components = code.split('-', 2)
language_code = components[0]
try:
country_code = components[1]
except IndexError... | [
"def",
"transform_language_code",
"(",
"code",
")",
":",
"if",
"code",
"is",
"None",
":",
"return",
"'English'",
"components",
"=",
"code",
".",
"split",
"(",
"'-'",
",",
"2",
")",
"language_code",
"=",
"components",
"[",
"0",
"]",
"try",
":",
"country_c... | Transform ISO language code (e.g. en-us) to the language name expected by SAPSF. | [
"Transform",
"ISO",
"language",
"code",
"(",
"e",
".",
"g",
".",
"en",
"-",
"us",
")",
"to",
"the",
"language",
"name",
"expected",
"by",
"SAPSF",
"."
] | python | valid | 27.736842 |
saltstack/salt | salt/modules/bluecoat_sslv.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L101-L121 | def add_distinguished_name_list(list_name):
'''
Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList
'''
... | [
"def",
"add_distinguished_name_list",
"(",
"list_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"add_policy_distinguished_names_list\"",
",",
"\"params\"",
":",
"[",
"{",
"\"list_name\"",... | Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList | [
"Add",
"a",
"list",
"of",
"policy",
"distinguished",
"names",
"."
] | python | train | 27.714286 |
mediawiki-utilities/python-mwreverts | mwreverts/historical_dict.py | https://github.com/mediawiki-utilities/python-mwreverts/blob/d379ac941e14e235ad82a48bd445a3dfa6cc022e/mwreverts/historical_dict.py#L28-L52 | def insert(self, key, value):
'''Adds a new key-value pair. Returns any discarded values.'''
# Add to history and catch expectorate
if len(self.history) == self.maxsize:
expectorate = self.history[0]
else:
expectorate = None
self.history.append((key, val... | [
"def",
"insert",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# Add to history and catch expectorate",
"if",
"len",
"(",
"self",
".",
"history",
")",
"==",
"self",
".",
"maxsize",
":",
"expectorate",
"=",
"self",
".",
"history",
"[",
"0",
"]",
"else... | Adds a new key-value pair. Returns any discarded values. | [
"Adds",
"a",
"new",
"key",
"-",
"value",
"pair",
".",
"Returns",
"any",
"discarded",
"values",
"."
] | python | train | 31.4 |
mattja/nsim | nsim/timeseries.py | https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/timeseries.py#L448-L455 | def absolute(self):
"""Calculate the absolute value element-wise.
Returns:
absolute (Timeseries):
Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2)
"""
return Timeseries(np.absolute(self), self.tspan, self.labels) | [
"def",
"absolute",
"(",
"self",
")",
":",
"return",
"Timeseries",
"(",
"np",
".",
"absolute",
"(",
"self",
")",
",",
"self",
".",
"tspan",
",",
"self",
".",
"labels",
")"
] | Calculate the absolute value element-wise.
Returns:
absolute (Timeseries):
Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2) | [
"Calculate",
"the",
"absolute",
"value",
"element",
"-",
"wise",
"."
] | python | train | 34.875 |
obriencj/python-javatools | javatools/report.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/report.py#L123-L143 | def setup(self):
"""
instantiates all report formats that have been added to this
reporter, and calls their setup methods.
"""
if self._formats:
# setup has been run already.
return
basedir = self.basedir
options = self.options
cr... | [
"def",
"setup",
"(",
"self",
")",
":",
"if",
"self",
".",
"_formats",
":",
"# setup has been run already.",
"return",
"basedir",
"=",
"self",
".",
"basedir",
"options",
"=",
"self",
".",
"options",
"crumbs",
"=",
"self",
".",
"get_relative_breadcrumbs",
"(",
... | instantiates all report formats that have been added to this
reporter, and calls their setup methods. | [
"instantiates",
"all",
"report",
"formats",
"that",
"have",
"been",
"added",
"to",
"this",
"reporter",
"and",
"calls",
"their",
"setup",
"methods",
"."
] | python | train | 25.571429 |
pmacosta/peng | peng/functions.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/functions.py#L700-L761 | def remove_extra_delims(expr, ldelim="(", rdelim=")"):
r"""
Remove unnecessary delimiters in mathematical expressions.
Delimiters (parenthesis, brackets, etc.) may be removed either because
there are multiple consecutive delimiters enclosing a single expressions or
because the delimiters are implie... | [
"def",
"remove_extra_delims",
"(",
"expr",
",",
"ldelim",
"=",
"\"(\"",
",",
"rdelim",
"=",
"\")\"",
")",
":",
"op_group",
"=",
"\"\"",
"for",
"item1",
"in",
"_OP_PREC",
":",
"if",
"isinstance",
"(",
"item1",
",",
"list",
")",
":",
"for",
"item2",
"in"... | r"""
Remove unnecessary delimiters in mathematical expressions.
Delimiters (parenthesis, brackets, etc.) may be removed either because
there are multiple consecutive delimiters enclosing a single expressions or
because the delimiters are implied by operator precedence rules. Function
names must sta... | [
"r",
"Remove",
"unnecessary",
"delimiters",
"in",
"mathematical",
"expressions",
"."
] | python | test | 36.370968 |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnode.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnode.py#L1922-L1930 | def setPalette(self, palette):
"""
Sets the palette for this node to the inputed palette. If None is
provided, then the scene's palette will be used for this node.
:param palette | <XNodePalette> || None
"""
self._palette = XNodePalette(palette) if palette ... | [
"def",
"setPalette",
"(",
"self",
",",
"palette",
")",
":",
"self",
".",
"_palette",
"=",
"XNodePalette",
"(",
"palette",
")",
"if",
"palette",
"is",
"not",
"None",
"else",
"None",
"self",
".",
"setDirty",
"(",
")"
] | Sets the palette for this node to the inputed palette. If None is
provided, then the scene's palette will be used for this node.
:param palette | <XNodePalette> || None | [
"Sets",
"the",
"palette",
"for",
"this",
"node",
"to",
"the",
"inputed",
"palette",
".",
"If",
"None",
"is",
"provided",
"then",
"the",
"scene",
"s",
"palette",
"will",
"be",
"used",
"for",
"this",
"node",
".",
":",
"param",
"palette",
"|",
"<XNodePalett... | python | train | 39.666667 |
googleapis/google-cloud-python | storage/google/cloud/storage/batch.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/batch.py#L304-L335 | def _unpack_batch_response(response):
"""Convert requests.Response -> [(headers, payload)].
Creates a generator of tuples of emulating the responses to
:meth:`requests.Session.request`.
:type response: :class:`requests.Response`
:param response: HTTP response / headers from a request.
"""
... | [
"def",
"_unpack_batch_response",
"(",
"response",
")",
":",
"parser",
"=",
"Parser",
"(",
")",
"message",
"=",
"_generate_faux_mime_message",
"(",
"parser",
",",
"response",
")",
"if",
"not",
"isinstance",
"(",
"message",
".",
"_payload",
",",
"list",
")",
"... | Convert requests.Response -> [(headers, payload)].
Creates a generator of tuples of emulating the responses to
:meth:`requests.Session.request`.
:type response: :class:`requests.Response`
:param response: HTTP response / headers from a request. | [
"Convert",
"requests",
".",
"Response",
"-",
">",
"[",
"(",
"headers",
"payload",
")",
"]",
"."
] | python | train | 36.34375 |
gem/oq-engine | openquake/calculators/getters.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/getters.py#L433-L460 | def gen_rupture_getters(dstore, slc=slice(None),
concurrent_tasks=1, hdf5cache=None):
"""
:yields: RuptureGetters
"""
if dstore.parent:
dstore = dstore.parent
csm_info = dstore['csm_info']
trt_by_grp = csm_info.grp_by("trt")
samples = csm_info.get_samples_by_g... | [
"def",
"gen_rupture_getters",
"(",
"dstore",
",",
"slc",
"=",
"slice",
"(",
"None",
")",
",",
"concurrent_tasks",
"=",
"1",
",",
"hdf5cache",
"=",
"None",
")",
":",
"if",
"dstore",
".",
"parent",
":",
"dstore",
"=",
"dstore",
".",
"parent",
"csm_info",
... | :yields: RuptureGetters | [
":",
"yields",
":",
"RuptureGetters"
] | python | train | 42.142857 |
twilio/authy-python | authy/api/resources.py | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L543-L582 | def __make_http_query(self, params, topkey=''):
"""
Function to covert params into url encoded query string
:param dict params: Json string sent by Authy.
:param string topkey: params key
:return string: url encoded Query.
"""
if len(params) == 0:
ret... | [
"def",
"__make_http_query",
"(",
"self",
",",
"params",
",",
"topkey",
"=",
"''",
")",
":",
"if",
"len",
"(",
"params",
")",
"==",
"0",
":",
"return",
"\"\"",
"result",
"=",
"\"\"",
"# is a dictionary?",
"if",
"type",
"(",
"params",
")",
"is",
"dict",
... | Function to covert params into url encoded query string
:param dict params: Json string sent by Authy.
:param string topkey: params key
:return string: url encoded Query. | [
"Function",
"to",
"covert",
"params",
"into",
"url",
"encoded",
"query",
"string",
":",
"param",
"dict",
"params",
":",
"Json",
"string",
"sent",
"by",
"Authy",
".",
":",
"param",
"string",
"topkey",
":",
"params",
"key",
":",
"return",
"string",
":",
"u... | python | train | 42.8 |
synw/dataswim | dataswim/data/clean.py | https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/clean.py#L52-L68 | def zero_nan(self, *cols):
"""
Converts zero values to nan values in selected columns
:param \*cols: names of the colums
:type \*cols: str, at least one
:example: ``ds.zero_nan("mycol1", "mycol2")``
"""
if len(cols) == 0:
self.warning("Can not nan ze... | [
"def",
"zero_nan",
"(",
"self",
",",
"*",
"cols",
")",
":",
"if",
"len",
"(",
"cols",
")",
"==",
"0",
":",
"self",
".",
"warning",
"(",
"\"Can not nan zero values if a column name \"",
"\"is not provided\"",
")",
"df",
"=",
"self",
".",
"_zero_nan",
"(",
"... | Converts zero values to nan values in selected columns
:param \*cols: names of the colums
:type \*cols: str, at least one
:example: ``ds.zero_nan("mycol1", "mycol2")`` | [
"Converts",
"zero",
"values",
"to",
"nan",
"values",
"in",
"selected",
"columns"
] | python | train | 31.294118 |
taxpon/pymesh | pymesh/base.py | https://github.com/taxpon/pymesh/blob/a90b3b2ed1408d793f3b5208dd8087b08fb7c92e/pymesh/base.py#L193-L206 | def __calc_signed_volume(triangle):
""" Calculate signed volume of given triangle
:param list of list triangle:
:rtype float
"""
v321 = triangle[2][0] * triangle[1][1] * triangle[0][2]
v231 = triangle[1][0] * triangle[2][1] * triangle[0][2]
v312 = triangle[2][0] *... | [
"def",
"__calc_signed_volume",
"(",
"triangle",
")",
":",
"v321",
"=",
"triangle",
"[",
"2",
"]",
"[",
"0",
"]",
"*",
"triangle",
"[",
"1",
"]",
"[",
"1",
"]",
"*",
"triangle",
"[",
"0",
"]",
"[",
"2",
"]",
"v231",
"=",
"triangle",
"[",
"1",
"]... | Calculate signed volume of given triangle
:param list of list triangle:
:rtype float | [
"Calculate",
"signed",
"volume",
"of",
"given",
"triangle",
":",
"param",
"list",
"of",
"list",
"triangle",
":",
":",
"rtype",
"float"
] | python | train | 45.285714 |
aouyar/PyMunin | pysysinfo/diskio.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pysysinfo/diskio.py#L418-L430 | def getSwapStats(self, dev):
"""Returns I/O stats for swap partition.
@param dev: Device name for swap partition.
@return: Dict of stats.
"""
if self._swapList is None:
self._initSwapInfo()
if dev in self._swapList:
return self.ge... | [
"def",
"getSwapStats",
"(",
"self",
",",
"dev",
")",
":",
"if",
"self",
".",
"_swapList",
"is",
"None",
":",
"self",
".",
"_initSwapInfo",
"(",
")",
"if",
"dev",
"in",
"self",
".",
"_swapList",
":",
"return",
"self",
".",
"getDevStats",
"(",
"dev",
"... | Returns I/O stats for swap partition.
@param dev: Device name for swap partition.
@return: Dict of stats. | [
"Returns",
"I",
"/",
"O",
"stats",
"for",
"swap",
"partition",
"."
] | python | train | 27.692308 |
bkabrda/flask-whooshee | flask_whooshee.py | https://github.com/bkabrda/flask-whooshee/blob/773fc51ed53043bd5e92c65eadef5663845ae8c4/flask_whooshee.py#L138-L163 | def search(cls, search_string, values_of='', group=whoosh.qparser.OrGroup, match_substrings=True, limit=None):
"""Searches the fields for given search_string.
Returns the found records if 'values_of' is left empty,
else the values of the given columns.
:param search_string: The string t... | [
"def",
"search",
"(",
"cls",
",",
"search_string",
",",
"values_of",
"=",
"''",
",",
"group",
"=",
"whoosh",
".",
"qparser",
".",
"OrGroup",
",",
"match_substrings",
"=",
"True",
",",
"limit",
"=",
"None",
")",
":",
"index",
"=",
"Whooshee",
".",
"get_... | Searches the fields for given search_string.
Returns the found records if 'values_of' is left empty,
else the values of the given columns.
:param search_string: The string to search for.
:param values_of: If given, the method will not return the whole
records, ... | [
"Searches",
"the",
"fields",
"for",
"given",
"search_string",
".",
"Returns",
"the",
"found",
"records",
"if",
"values_of",
"is",
"left",
"empty",
"else",
"the",
"values",
"of",
"the",
"given",
"columns",
"."
] | python | train | 57.192308 |
hhromic/python-oslom-runner | oslom/runner.py | https://github.com/hhromic/python-oslom-runner/blob/f5991bd5014c65d0a9852641d51cbc344407d6a2/oslom/runner.py#L66-L70 | def store_mapping(self, path):
"""Store the current Id mappings into a TSV file."""
with open(path, "w") as writer:
for key, value in self.mapping.iteritems():
writer.write("{}\t{}\n".format(key, value)) | [
"def",
"store_mapping",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
"writer",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"mapping",
".",
"iteritems",
"(",
")",
":",
"writer",
".",
"write",
"(",... | Store the current Id mappings into a TSV file. | [
"Store",
"the",
"current",
"Id",
"mappings",
"into",
"a",
"TSV",
"file",
"."
] | python | train | 48.6 |
divio/django-filer | filer/admin/folderadmin.py | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/folderadmin.py#L697-L792 | def delete_files_or_folders(self, request, files_queryset, folders_queryset):
"""
Action which deletes the selected files and/or folders.
This action first displays a confirmation page whichs shows all the
deleteable files and/or folders, or, if the user has no permission on
one... | [
"def",
"delete_files_or_folders",
"(",
"self",
",",
"request",
",",
"files_queryset",
",",
"folders_queryset",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"app_label",
"=",
"opts",
".",
"app_label",
"# Check that the user has delete permission for the a... | Action which deletes the selected files and/or folders.
This action first displays a confirmation page whichs shows all the
deleteable files and/or folders, or, if the user has no permission on
one of the related childs (foreignkeys), a "permission denied" message.
Next, it deletes all... | [
"Action",
"which",
"deletes",
"the",
"selected",
"files",
"and",
"/",
"or",
"folders",
"."
] | python | train | 45.958333 |
pyca/pyopenssl | src/OpenSSL/crypto.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L2569-L2579 | def b64_encode(self):
"""
Generate a base64 encoded representation of this SPKI object.
:return: The base64 encoded string.
:rtype: :py:class:`bytes`
"""
encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
result = _ffi.string(encoded)
_lib.OPENSSL_free(e... | [
"def",
"b64_encode",
"(",
"self",
")",
":",
"encoded",
"=",
"_lib",
".",
"NETSCAPE_SPKI_b64_encode",
"(",
"self",
".",
"_spki",
")",
"result",
"=",
"_ffi",
".",
"string",
"(",
"encoded",
")",
"_lib",
".",
"OPENSSL_free",
"(",
"encoded",
")",
"return",
"r... | Generate a base64 encoded representation of this SPKI object.
:return: The base64 encoded string.
:rtype: :py:class:`bytes` | [
"Generate",
"a",
"base64",
"encoded",
"representation",
"of",
"this",
"SPKI",
"object",
"."
] | python | test | 30.818182 |
mathiasertl/xmpp-backends | xmpp_backends/django/models.py | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/django/models.py#L39-L47 | def set_password(self, raw_password):
"""Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user.
If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`.
"""
if raw_password is None:
self.set_unusable_passwo... | [
"def",
"set_password",
"(",
"self",
",",
"raw_password",
")",
":",
"if",
"raw_password",
"is",
"None",
":",
"self",
".",
"set_unusable_password",
"(",
")",
"else",
":",
"xmpp_backend",
".",
"set_password",
"(",
"self",
".",
"node",
",",
"self",
".",
"domai... | Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user.
If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`. | [
"Calls",
":",
"py",
":",
"func",
":",
"~xmpp_backends",
".",
"base",
".",
"XmppBackendBase",
".",
"set_password",
"for",
"the",
"user",
"."
] | python | train | 45.111111 |
zsimic/runez | src/runez/logsetup.py | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/logsetup.py#L383-L401 | def enable_faulthandler(cls, signum=signal.SIGUSR1):
"""
Enable dumping thread stack traces when specified signals are received, similar to java's handling of SIGQUIT
Note: this must be called from the surviving process in case of daemonization.
Note that SIGQUIT does not work in all en... | [
"def",
"enable_faulthandler",
"(",
"cls",
",",
"signum",
"=",
"signal",
".",
"SIGUSR1",
")",
":",
"with",
"cls",
".",
"_lock",
":",
"if",
"not",
"signum",
":",
"cls",
".",
"_disable_faulthandler",
"(",
")",
"return",
"if",
"not",
"cls",
".",
"file_handle... | Enable dumping thread stack traces when specified signals are received, similar to java's handling of SIGQUIT
Note: this must be called from the surviving process in case of daemonization.
Note that SIGQUIT does not work in all environments with a python process.
:param int|None signum: Signal... | [
"Enable",
"dumping",
"thread",
"stack",
"traces",
"when",
"specified",
"signals",
"are",
"received",
"similar",
"to",
"java",
"s",
"handling",
"of",
"SIGQUIT"
] | python | train | 47.631579 |
mdgoldberg/sportsref | sportsref/nfl/teams.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nfl/teams.py#L337-L349 | def def_alignment(self, year):
"""Returns the name of the defensive alignment the team ran in the
given year.
:year: Int representing the season year.
:returns: A string representing the defensive alignment.
"""
scheme_text = self._year_info_pq(year, 'Defensive Alignment... | [
"def",
"def_alignment",
"(",
"self",
",",
"year",
")",
":",
"scheme_text",
"=",
"self",
".",
"_year_info_pq",
"(",
"year",
",",
"'Defensive Alignment'",
")",
".",
"text",
"(",
")",
"m",
"=",
"re",
".",
"search",
"(",
"r'Defensive Alignment[:\\s]*(.+)\\s*'",
... | Returns the name of the defensive alignment the team ran in the
given year.
:year: Int representing the season year.
:returns: A string representing the defensive alignment. | [
"Returns",
"the",
"name",
"of",
"the",
"defensive",
"alignment",
"the",
"team",
"ran",
"in",
"the",
"given",
"year",
"."
] | python | test | 36.692308 |
GPflow/GPflow | gpflow/training/natgrad_optimizer.py | https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/training/natgrad_optimizer.py#L386-L398 | def _inverse_lower_triangular(M):
"""
Take inverse of lower triangular (e.g. Cholesky) matrix. This function
broadcasts over the first index.
:param M: Tensor with lower triangular structure of shape DxNxN
:return: The inverse of the Cholesky decomposition. Same shape as input.
"""
if M.get... | [
"def",
"_inverse_lower_triangular",
"(",
"M",
")",
":",
"if",
"M",
".",
"get_shape",
"(",
")",
".",
"ndims",
"!=",
"3",
":",
"# pragma: no cover",
"raise",
"ValueError",
"(",
"\"Number of dimensions for input is required to be 3.\"",
")",
"D",
",",
"N",
"=",
"tf... | Take inverse of lower triangular (e.g. Cholesky) matrix. This function
broadcasts over the first index.
:param M: Tensor with lower triangular structure of shape DxNxN
:return: The inverse of the Cholesky decomposition. Same shape as input. | [
"Take",
"inverse",
"of",
"lower",
"triangular",
"(",
"e",
".",
"g",
".",
"Cholesky",
")",
"matrix",
".",
"This",
"function",
"broadcasts",
"over",
"the",
"first",
"index",
"."
] | python | train | 46.384615 |
benoitkugler/abstractDataLibrary | pyDLib/Core/groups.py | https://github.com/benoitkugler/abstractDataLibrary/blob/16be28e99837e40287a63803bbfdf67ac1806b7b/pyDLib/Core/groups.py#L135-L143 | def extend(self, collection):
"""Merges collections. Ensure uniqueness of ids"""
l_ids = set([a.Id for a in self])
for acces in collection:
if not acces.Id in l_ids:
list.append(self,acces)
info = collection.get_info(Id=acces.Id)
if inf... | [
"def",
"extend",
"(",
"self",
",",
"collection",
")",
":",
"l_ids",
"=",
"set",
"(",
"[",
"a",
".",
"Id",
"for",
"a",
"in",
"self",
"]",
")",
"for",
"acces",
"in",
"collection",
":",
"if",
"not",
"acces",
".",
"Id",
"in",
"l_ids",
":",
"list",
... | Merges collections. Ensure uniqueness of ids | [
"Merges",
"collections",
".",
"Ensure",
"uniqueness",
"of",
"ids"
] | python | train | 40.222222 |
mwgielen/jackal | jackal/utils.py | https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/utils.py#L85-L189 | def draw_interface(objects, callback, callback_text):
"""
Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object.
Rest of the code is modified from:
https://stackov... | [
"def",
"draw_interface",
"(",
"objects",
",",
"callback",
",",
"callback_text",
")",
":",
"screen",
"=",
"curses",
".",
"initscr",
"(",
")",
"height",
",",
"width",
"=",
"screen",
".",
"getmaxyx",
"(",
")",
"curses",
".",
"noecho",
"(",
")",
"curses",
... | Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object.
Rest of the code is modified from:
https://stackoverflow.com/a/30834868 | [
"Draws",
"a",
"ncurses",
"interface",
".",
"Based",
"on",
"the",
"given",
"object",
"list",
"every",
"object",
"should",
"have",
"a",
"string",
"key",
"this",
"is",
"whats",
"displayed",
"on",
"the",
"screen",
"callback",
"is",
"called",
"with",
"the",
"se... | python | valid | 35.304762 |
rochacbruno/flask_simplelogin | example/manage.py | https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/example/manage.py#L23-L41 | def create_user(**data):
"""Creates user with encrypted password"""
if 'username' not in data or 'password' not in data:
raise ValueError('username and password are required.')
# Hash the user password
data['password'] = generate_password_hash(
data.pop('password'),
method='pbkd... | [
"def",
"create_user",
"(",
"*",
"*",
"data",
")",
":",
"if",
"'username'",
"not",
"in",
"data",
"or",
"'password'",
"not",
"in",
"data",
":",
"raise",
"ValueError",
"(",
"'username and password are required.'",
")",
"# Hash the user password",
"data",
"[",
"'pas... | Creates user with encrypted password | [
"Creates",
"user",
"with",
"encrypted",
"password"
] | python | train | 34.578947 |
edoburu/django-tag-parser | tag_parser/basetags.py | https://github.com/edoburu/django-tag-parser/blob/c24256cfdd0248434f2e3df3444ed9f945d4181f/tag_parser/basetags.py#L272-L299 | def get_context(self, parent_context, data):
"""
Wrap the context data in a :class:`~django.template.Context` object.
:param parent_context: The context of the parent template.
:type parent_context: :class:`~django.template.Context`
:param data: The result from :func:`get_contex... | [
"def",
"get_context",
"(",
"self",
",",
"parent_context",
",",
"data",
")",
":",
"if",
"django",
".",
"VERSION",
">=",
"(",
"1",
",",
"8",
")",
":",
"new_context",
"=",
"parent_context",
".",
"new",
"(",
"data",
")",
"else",
":",
"settings",
"=",
"{"... | Wrap the context data in a :class:`~django.template.Context` object.
:param parent_context: The context of the parent template.
:type parent_context: :class:`~django.template.Context`
:param data: The result from :func:`get_context_data`
:type data: dict
:return: Context data.
... | [
"Wrap",
"the",
"context",
"data",
"in",
"a",
":",
"class",
":",
"~django",
".",
"template",
".",
"Context",
"object",
"."
] | python | test | 38.571429 |
jd/tenacity | tenacity/compat.py | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L120-L136 | def stop_func_accept_retry_state(stop_func):
"""Wrap "stop" function to accept "retry_state" parameter."""
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
wa... | [
"def",
"stop_func_accept_retry_state",
"(",
"stop_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"stop_func",
")",
":",
"return",
"stop_func",
"if",
"func_takes_retry_state",
"(",
"stop_func",
")",
":",
"return",
"stop_func",
"@",
"_utils",
".",
"w... | Wrap "stop" function to accept "retry_state" parameter. | [
"Wrap",
"stop",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | python | train | 31.529412 |
Falkonry/falkonry-python-client | falkonryclient/service/http.py | https://github.com/Falkonry/falkonry-python-client/blob/0aeb2b00293ee94944f1634e9667401b03da29c1/falkonryclient/service/http.py#L197-L215 | def delete(self, url):
"""
To make a DELETE request to Falkonry API server
:param url: string
"""
response = requests.delete(
self.host + url,
headers={
'Authorization': 'Bearer ' + self.token,
'x-falkonry-source':self.sourceHea... | [
"def",
"delete",
"(",
"self",
",",
"url",
")",
":",
"response",
"=",
"requests",
".",
"delete",
"(",
"self",
".",
"host",
"+",
"url",
",",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"self",
".",
"token",
",",
"'x-falkonry-source'",
... | To make a DELETE request to Falkonry API server
:param url: string | [
"To",
"make",
"a",
"DELETE",
"request",
"to",
"Falkonry",
"API",
"server",
":",
"param",
"url",
":",
"string"
] | python | train | 31.368421 |
angr/claripy | claripy/vsa/strided_interval.py | https://github.com/angr/claripy/blob/4ed61924880af1ea8fb778047d896ec0156412a6/claripy/vsa/strided_interval.py#L507-L542 | def _nsplit(self):
"""
Split `self` at the north pole, which is the same as in signed arithmetic.
:return: A list of split StridedIntervals
"""
north_pole_left = self.max_int(self.bits - 1) # 01111...1
north_pole_right = 2 ** (self.bits - 1) # 1000...0
# Is `se... | [
"def",
"_nsplit",
"(",
"self",
")",
":",
"north_pole_left",
"=",
"self",
".",
"max_int",
"(",
"self",
".",
"bits",
"-",
"1",
")",
"# 01111...1",
"north_pole_right",
"=",
"2",
"**",
"(",
"self",
".",
"bits",
"-",
"1",
")",
"# 1000...0",
"# Is `self` strad... | Split `self` at the north pole, which is the same as in signed arithmetic.
:return: A list of split StridedIntervals | [
"Split",
"self",
"at",
"the",
"north",
"pole",
"which",
"is",
"the",
"same",
"as",
"in",
"signed",
"arithmetic",
"."
] | python | train | 38.277778 |
SmokinCaterpillar/pypet | pypet/pypetlogging.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L375-L393 | def show_progress(self, n, total_runs):
"""Displays a progressbar"""
if self.report_progress:
percentage, logger_name, log_level = self.report_progress
if logger_name == 'print':
logger = 'print'
else:
logger = logging.getLogger(logger_... | [
"def",
"show_progress",
"(",
"self",
",",
"n",
",",
"total_runs",
")",
":",
"if",
"self",
".",
"report_progress",
":",
"percentage",
",",
"logger_name",
",",
"log_level",
"=",
"self",
".",
"report_progress",
"if",
"logger_name",
"==",
"'print'",
":",
"logger... | Displays a progressbar | [
"Displays",
"a",
"progressbar"
] | python | test | 45.052632 |
senaite/senaite.core | bika/lims/content/batch.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/batch.py#L355-L362 | def getAnalysisRequestsBrains(self, **kwargs):
"""Return all the Analysis Requests brains linked to the Batch
kargs are passed directly to the catalog.
"""
kwargs['getBatchUID'] = self.UID()
catalog = getToolByName(self, CATALOG_ANALYSIS_REQUEST_LISTING)
brains = catalog(... | [
"def",
"getAnalysisRequestsBrains",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'getBatchUID'",
"]",
"=",
"self",
".",
"UID",
"(",
")",
"catalog",
"=",
"getToolByName",
"(",
"self",
",",
"CATALOG_ANALYSIS_REQUEST_LISTING",
")",
"brains",
... | Return all the Analysis Requests brains linked to the Batch
kargs are passed directly to the catalog. | [
"Return",
"all",
"the",
"Analysis",
"Requests",
"brains",
"linked",
"to",
"the",
"Batch",
"kargs",
"are",
"passed",
"directly",
"to",
"the",
"catalog",
"."
] | python | train | 42.75 |
senaite/senaite.core | bika/lims/utils/analysis.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/utils/analysis.py#L303-L373 | def format_numeric_result(analysis, result, decimalmark='.', sciformat=1):
"""
Returns the formatted number part of a results value. This is
responsible for deciding the precision, and notation of numeric
values in accordance to the uncertainty. If a non-numeric
result value is given, the value wil... | [
"def",
"format_numeric_result",
"(",
"analysis",
",",
"result",
",",
"decimalmark",
"=",
"'.'",
",",
"sciformat",
"=",
"1",
")",
":",
"try",
":",
"result",
"=",
"float",
"(",
"result",
")",
"except",
"ValueError",
":",
"return",
"result",
"# continuing with ... | Returns the formatted number part of a results value. This is
responsible for deciding the precision, and notation of numeric
values in accordance to the uncertainty. If a non-numeric
result value is given, the value will be returned unchanged.
The following rules apply:
If the "Calculate precisi... | [
"Returns",
"the",
"formatted",
"number",
"part",
"of",
"a",
"results",
"value",
".",
"This",
"is",
"responsible",
"for",
"deciding",
"the",
"precision",
"and",
"notation",
"of",
"numeric",
"values",
"in",
"accordance",
"to",
"the",
"uncertainty",
".",
"If",
... | python | train | 42.521127 |
inveniosoftware/invenio-github | invenio_github/api.py | https://github.com/inveniosoftware/invenio-github/blob/ec42fd6a06079310dcbe2c46d9fd79d5197bbe26/invenio_github/api.py#L133-L185 | def sync(self, hooks=True, async_hooks=True):
"""Synchronize user repositories.
:param bool hooks: True for syncing hooks.
:param bool async_hooks: True for sending of an asynchronous task to
sync hooks.
.. note::
Syncing happens from GitHu... | [
"def",
"sync",
"(",
"self",
",",
"hooks",
"=",
"True",
",",
"async_hooks",
"=",
"True",
")",
":",
"active_repos",
"=",
"{",
"}",
"github_repos",
"=",
"{",
"repo",
".",
"id",
":",
"repo",
"for",
"repo",
"in",
"self",
".",
"api",
".",
"repositories",
... | Synchronize user repositories.
:param bool hooks: True for syncing hooks.
:param bool async_hooks: True for sending of an asynchronous task to
sync hooks.
.. note::
Syncing happens from GitHub's direction only. This means that we
consid... | [
"Synchronize",
"user",
"repositories",
"."
] | python | train | 37.886792 |
HydraChain/hydrachain | hydrachain/examples/native/fungible/fungible_contract.py | https://github.com/HydraChain/hydrachain/blob/6c0919b0575dc8aa481f3a8c703e1a7f0575ecc3/hydrachain/examples/native/fungible/fungible_contract.py#L49-L60 | def transfer(ctx, _to='address', _value='uint256', returns=STATUS):
""" Standardized Contract API:
function transfer(address _to, uint256 _value) returns (bool _success)
"""
log.DEV('In Fungible.transfer')
if ctx.accounts[ctx.msg_sender] >= _value:
ctx.accounts[ctx.ms... | [
"def",
"transfer",
"(",
"ctx",
",",
"_to",
"=",
"'address'",
",",
"_value",
"=",
"'uint256'",
",",
"returns",
"=",
"STATUS",
")",
":",
"log",
".",
"DEV",
"(",
"'In Fungible.transfer'",
")",
"if",
"ctx",
".",
"accounts",
"[",
"ctx",
".",
"msg_sender",
"... | Standardized Contract API:
function transfer(address _to, uint256 _value) returns (bool _success) | [
"Standardized",
"Contract",
"API",
":",
"function",
"transfer",
"(",
"address",
"_to",
"uint256",
"_value",
")",
"returns",
"(",
"bool",
"_success",
")"
] | python | test | 41.25 |
elliterate/capybara.py | capybara/node/matchers.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/node/matchers.py#L784-L798 | def has_unchecked_field(self, locator, **kwargs):
"""
Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: A... | [
"def",
"has_unchecked_field",
"(",
"self",
",",
"locator",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"checked\"",
"]",
"=",
"False",
"return",
"self",
".",
"has_selector",
"(",
"\"field\"",
",",
"locator",
",",
"*",
"*",
"kwargs",
")"
] | Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Return... | [
"Checks",
"if",
"the",
"page",
"or",
"current",
"node",
"has",
"a",
"radio",
"button",
"or",
"checkbox",
"with",
"the",
"given",
"label",
"value",
"or",
"id",
"that",
"is",
"currently",
"unchecked",
"."
] | python | test | 34.866667 |
tyarkoni/pliers | pliers/diagnostics/diagnostics.py | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L49-L60 | def variance_inflation_factors(df):
'''
Computes the variance inflation factor (VIF) for each column in the df.
Returns a pandas Series of VIFs
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
corr = np.corrcoef(df, rowvar=0)
corr_inv = np.linalg.inv(corr)
vifs ... | [
"def",
"variance_inflation_factors",
"(",
"df",
")",
":",
"corr",
"=",
"np",
".",
"corrcoef",
"(",
"df",
",",
"rowvar",
"=",
"0",
")",
"corr_inv",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"corr",
")",
"vifs",
"=",
"np",
".",
"diagonal",
"(",
"cor... | Computes the variance inflation factor (VIF) for each column in the df.
Returns a pandas Series of VIFs
Args:
df: pandas DataFrame with columns to run diagnostics on | [
"Computes",
"the",
"variance",
"inflation",
"factor",
"(",
"VIF",
")",
"for",
"each",
"column",
"in",
"the",
"df",
".",
"Returns",
"a",
"pandas",
"Series",
"of",
"VIFs"
] | python | train | 31.916667 |
log2timeline/plaso | plaso/parsers/systemd_journal.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/systemd_journal.py#L131-L164 | def _ParseEntryArrayObject(self, file_object, file_offset):
"""Parses an entry array object.
Args:
file_object (dfvfs.FileIO): a file-like object.
file_offset (int): offset of the entry array object relative to the start
of the file-like object.
Returns:
systemd_journal_entry_a... | [
"def",
"_ParseEntryArrayObject",
"(",
"self",
",",
"file_object",
",",
"file_offset",
")",
":",
"entry_array_object_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'systemd_journal_entry_array_object'",
")",
"try",
":",
"entry_array_object",
",",
"_",
"=",
"self",
... | Parses an entry array object.
Args:
file_object (dfvfs.FileIO): a file-like object.
file_offset (int): offset of the entry array object relative to the start
of the file-like object.
Returns:
systemd_journal_entry_array_object: entry array object.
Raises:
ParseError: if ... | [
"Parses",
"an",
"entry",
"array",
"object",
"."
] | python | train | 36.5 |
Crunch-io/crunch-cube | src/cr/cube/crunch_cube.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1445-L1449 | def weighted_n(self):
"""float count of returned rows adjusted for weighting."""
if not self.is_weighted:
return float(self.unweighted_n)
return float(sum(self._cube_dict["result"]["measures"]["count"]["data"])) | [
"def",
"weighted_n",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_weighted",
":",
"return",
"float",
"(",
"self",
".",
"unweighted_n",
")",
"return",
"float",
"(",
"sum",
"(",
"self",
".",
"_cube_dict",
"[",
"\"result\"",
"]",
"[",
"\"measures\""... | float count of returned rows adjusted for weighting. | [
"float",
"count",
"of",
"returned",
"rows",
"adjusted",
"for",
"weighting",
"."
] | python | train | 48.6 |
ray-project/ray | python/ray/function_manager.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/function_manager.py#L455-L489 | def get_execution_info(self, driver_id, function_descriptor):
"""Get the FunctionExecutionInfo of a remote function.
Args:
driver_id: ID of the driver that the function belongs to.
function_descriptor: The FunctionDescriptor of the function to get.
Returns:
... | [
"def",
"get_execution_info",
"(",
"self",
",",
"driver_id",
",",
"function_descriptor",
")",
":",
"if",
"self",
".",
"_worker",
".",
"load_code_from_local",
":",
"# Load function from local code.",
"# Currently, we don't support isolating code by drivers,",
"# thus always set d... | Get the FunctionExecutionInfo of a remote function.
Args:
driver_id: ID of the driver that the function belongs to.
function_descriptor: The FunctionDescriptor of the function to get.
Returns:
A FunctionExecutionInfo object. | [
"Get",
"the",
"FunctionExecutionInfo",
"of",
"a",
"remote",
"function",
"."
] | python | train | 46.914286 |
tarzanjw/python-mysql-binlog-to-blinker | mysqlbinlog2blinker/__init__.py | https://github.com/tarzanjw/python-mysql-binlog-to-blinker/blob/d61ab5962345377e142a225b16f731ab4196fc26/mysqlbinlog2blinker/__init__.py#L56-L90 | def start_replication(mysql_settings,
binlog_pos_memory=(None, 2),
**kwargs):
""" Start replication on server specified by *mysql_settings*
Args:
mysql_settings (dict): mysql settings that is used to connect to
mysql via pymys... | [
"def",
"start_replication",
"(",
"mysql_settings",
",",
"binlog_pos_memory",
"=",
"(",
"None",
",",
"2",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"binlog_pos_memory",
",",
"_bpm",
".",
"BaseBinlogPosMemory",
")",
":",
"if",
"... | Start replication on server specified by *mysql_settings*
Args:
mysql_settings (dict): mysql settings that is used to connect to
mysql via pymysql
binlog_pos_memory (_bpm.BaseBinlogPosMemory):
Binlog Position Memory, it should be an instance of subclass ... | [
"Start",
"replication",
"on",
"server",
"specified",
"by",
"*",
"mysql_settings",
"*"
] | python | train | 46.342857 |
tableau/document-api-python | tableaudocumentapi/xfile.py | https://github.com/tableau/document-api-python/blob/9097a5b351622c5dd2653fa94624bc012316d8a4/tableaudocumentapi/xfile.py#L58-L74 | def find_file_in_zip(zip_file):
'''Returns the twb/tds file from a Tableau packaged file format. Packaged
files can contain cache entries which are also valid XML, so only look for
files with a .tds or .twb extension.
'''
candidate_files = filter(lambda x: x.split('.')[-1] in ('twb', 'tds'),
... | [
"def",
"find_file_in_zip",
"(",
"zip_file",
")",
":",
"candidate_files",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"in",
"(",
"'twb'",
",",
"'tds'",
")",
",",
"zip_file",
".",
"namelist",
"(",
"... | Returns the twb/tds file from a Tableau packaged file format. Packaged
files can contain cache entries which are also valid XML, so only look for
files with a .tds or .twb extension. | [
"Returns",
"the",
"twb",
"/",
"tds",
"file",
"from",
"a",
"Tableau",
"packaged",
"file",
"format",
".",
"Packaged",
"files",
"can",
"contain",
"cache",
"entries",
"which",
"are",
"also",
"valid",
"XML",
"so",
"only",
"look",
"for",
"files",
"with",
"a",
... | python | train | 37.235294 |
awslabs/aws-sam-cli | samcli/local/lambdafn/runtime.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/runtime.py#L118-L149 | def _configure_interrupt(self, function_name, timeout, container, is_debugging):
"""
When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
... | [
"def",
"_configure_interrupt",
"(",
"self",
",",
"function_name",
",",
"timeout",
",",
"container",
",",
"is_debugging",
")",
":",
"def",
"timer_handler",
"(",
")",
":",
"# NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures"... | When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C and terminate the c... | [
"When",
"a",
"Lambda",
"function",
"is",
"executing",
"we",
"setup",
"certain",
"interrupt",
"handlers",
"to",
"stop",
"the",
"execution",
".",
"Usually",
"we",
"setup",
"a",
"function",
"timeout",
"interrupt",
"to",
"kill",
"the",
"container",
"after",
"timeo... | python | train | 57.375 |
rigetti/pyquil | pyquil/device.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/device.py#L255-L263 | def fCPHASEs(self):
"""
Get a dictionary of CPHASE fidelities (normalized to unity) from the specs,
keyed by targets (qubit-qubit pairs).
:return: A dictionary of CPHASE fidelities, normalized to unity.
:rtype: Dict[tuple(int, int), float]
"""
return {tuple(es.ta... | [
"def",
"fCPHASEs",
"(",
"self",
")",
":",
"return",
"{",
"tuple",
"(",
"es",
".",
"targets",
")",
":",
"es",
".",
"fCPHASE",
"for",
"es",
"in",
"self",
".",
"edges_specs",
"}"
] | Get a dictionary of CPHASE fidelities (normalized to unity) from the specs,
keyed by targets (qubit-qubit pairs).
:return: A dictionary of CPHASE fidelities, normalized to unity.
:rtype: Dict[tuple(int, int), float] | [
"Get",
"a",
"dictionary",
"of",
"CPHASE",
"fidelities",
"(",
"normalized",
"to",
"unity",
")",
"from",
"the",
"specs",
"keyed",
"by",
"targets",
"(",
"qubit",
"-",
"qubit",
"pairs",
")",
"."
] | python | train | 39.777778 |
ThreatConnect-Inc/tcex | tcex/tcex.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L427-L433 | def error_codes(self):
"""ThreatConnect error codes."""
if self._error_codes is None:
from .tcex_error_codes import TcExErrorCodes
self._error_codes = TcExErrorCodes()
return self._error_codes | [
"def",
"error_codes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_error_codes",
"is",
"None",
":",
"from",
".",
"tcex_error_codes",
"import",
"TcExErrorCodes",
"self",
".",
"_error_codes",
"=",
"TcExErrorCodes",
"(",
")",
"return",
"self",
".",
"_error_codes"
... | ThreatConnect error codes. | [
"ThreatConnect",
"error",
"codes",
"."
] | python | train | 33.571429 |
apache/airflow | airflow/contrib/operators/cassandra_to_gcs.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/cassandra_to_gcs.py#L258-L266 | def convert_tuple_type(cls, name, value):
"""
Converts a tuple to RECORD that contains n fields, each will be converted
to its corresponding data type in bq and will be named 'field_<index>', where
index is determined by the order of the tuple elements defined in cassandra.
"""
... | [
"def",
"convert_tuple_type",
"(",
"cls",
",",
"name",
",",
"value",
")",
":",
"names",
"=",
"[",
"'field_'",
"+",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"value",
")",
")",
"]",
"values",
"=",
"[",
"cls",
".",
"convert_v... | Converts a tuple to RECORD that contains n fields, each will be converted
to its corresponding data type in bq and will be named 'field_<index>', where
index is determined by the order of the tuple elements defined in cassandra. | [
"Converts",
"a",
"tuple",
"to",
"RECORD",
"that",
"contains",
"n",
"fields",
"each",
"will",
"be",
"converted",
"to",
"its",
"corresponding",
"data",
"type",
"in",
"bq",
"and",
"will",
"be",
"named",
"field_<index",
">",
"where",
"index",
"is",
"determined",... | python | test | 57 |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L144-L164 | def _check_vmware_player_requirements(self, player_version):
"""
Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMw... | [
"def",
"_check_vmware_player_requirements",
"(",
"self",
",",
"player_version",
")",
":",
"player_version",
"=",
"int",
"(",
"player_version",
")",
"if",
"player_version",
"<",
"6",
":",
"raise",
"VMwareError",
"(",
"\"Using VMware Player requires version 6 or above\"",
... | Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMware Player major version. | [
"Check",
"minimum",
"requirements",
"to",
"use",
"VMware",
"Player",
"."
] | python | train | 42 |
ellmetha/django-machina | machina/apps/forum_moderation/views.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_moderation/views.py#L454-L456 | def post(self, request, *args, **kwargs):
""" Handles POST requests. """
return self.disapprove(request, *args, **kwargs) | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"disapprove",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Handles POST requests. | [
"Handles",
"POST",
"requests",
"."
] | python | train | 45 |
noirbizarre/django.js | setup.py | https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/setup.py#L22-L32 | def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badge
'''
content = codecs.open(filename, encoding='utf-8').read()
for regex, replacement in PYPI_RST_FILTERS:
content = re.sub(regex, replace... | [
"def",
"rst",
"(",
"filename",
")",
":",
"content",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
".",
"read",
"(",
")",
"for",
"regex",
",",
"replacement",
"in",
"PYPI_RST_FILTERS",
":",
"content",
"=",
"re",
".",
... | Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badge | [
"Load",
"rst",
"file",
"and",
"sanitize",
"it",
"for",
"PyPI",
".",
"Remove",
"unsupported",
"github",
"tags",
":",
"-",
"code",
"-",
"block",
"directive",
"-",
"travis",
"ci",
"build",
"badge"
] | python | train | 31.181818 |
assamite/creamas | creamas/mp.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L692-L702 | async def _get_smallest_env(self):
"""Get address of the slave environment manager with the smallest
number of agents.
"""
async def slave_task(mgr_addr):
r_manager = await self.env.connect(mgr_addr, timeout=TIMEOUT)
ret = await r_manager.get_agents(addr=True)
... | [
"async",
"def",
"_get_smallest_env",
"(",
"self",
")",
":",
"async",
"def",
"slave_task",
"(",
"mgr_addr",
")",
":",
"r_manager",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"mgr_addr",
",",
"timeout",
"=",
"TIMEOUT",
")",
"ret",
"=",
"await",... | Get address of the slave environment manager with the smallest
number of agents. | [
"Get",
"address",
"of",
"the",
"slave",
"environment",
"manager",
"with",
"the",
"smallest",
"number",
"of",
"agents",
"."
] | python | train | 43.090909 |
nad2000/W3C-Validator | w3c_validator/validator.py | https://github.com/nad2000/W3C-Validator/blob/81eb35ef9c1fa87c82731b335c46f873e97a4dea/w3c_validator/validator.py#L69-L128 | def main():
"""Parser the command line and run the validator."""
parser = argparse.ArgumentParser(
description="[v" + __version__ + "] " + __doc__,
prog="w3c_validator",
)
parser.add_argument(
"--log",
default="INFO",
help=("log level: DEBUG, INFO or INFO "
... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"[v\"",
"+",
"__version__",
"+",
"\"] \"",
"+",
"__doc__",
",",
"prog",
"=",
"\"w3c_validator\"",
",",
")",
"parser",
".",
"add_argument",
"(",
"\"--... | Parser the command line and run the validator. | [
"Parser",
"the",
"command",
"line",
"and",
"run",
"the",
"validator",
"."
] | python | train | 33.133333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.