text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def experimentVaryingSynapseSampling(expParams,
sampleSizeDistalList,
sampleSizeProximalList):
"""
Test multi-column convergence with varying amount of proximal/distal sampling
:return:
"""
numRpts = 20
df = None
args = []
for sa... | [
"def",
"experimentVaryingSynapseSampling",
"(",
"expParams",
",",
"sampleSizeDistalList",
",",
"sampleSizeProximalList",
")",
":",
"numRpts",
"=",
"20",
"df",
"=",
"None",
"args",
"=",
"[",
"]",
"for",
"sampleSizeProximal",
"in",
"sampleSizeProximalList",
":",
"for"... | 31.212766 | 0.011897 |
def getchild(self, window_name, child_name='', role='', parent=''):
"""
Gets the list of object available in the window, which matches
component name or role name or both.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
... | [
"def",
"getchild",
"(",
"self",
",",
"window_name",
",",
"child_name",
"=",
"''",
",",
"role",
"=",
"''",
",",
"parent",
"=",
"''",
")",
":",
"matches",
"=",
"[",
"]",
"if",
"role",
":",
"role",
"=",
"re",
".",
"sub",
"(",
"' '",
",",
"'_'",
",... | 41.0625 | 0.002229 |
def getCmdParams(cmd, request, **fields):
"""Update or fill the fields parameters depending on command code. Both cmd and drAppId can be provided # noqa: E501
in string or int format."""
drCode = None
params = None
drAppId = None
# Fetch the parameters if cmd is found in dict
if isinstan... | [
"def",
"getCmdParams",
"(",
"cmd",
",",
"request",
",",
"*",
"*",
"fields",
")",
":",
"drCode",
"=",
"None",
"params",
"=",
"None",
"drAppId",
"=",
"None",
"# Fetch the parameters if cmd is found in dict",
"if",
"isinstance",
"(",
"cmd",
",",
"int",
")",
":"... | 41.107692 | 0.000365 |
def _prepare_fabric_fw_internal(self, tenant_id, fw_dict, is_fw_virt,
result):
"""Internal routine to prepare the fabric.
This creates an entry in FW DB and runs the SM.
"""
if not self.auto_nwk_create:
LOG.info("Auto network creation disa... | [
"def",
"_prepare_fabric_fw_internal",
"(",
"self",
",",
"tenant_id",
",",
"fw_dict",
",",
"is_fw_virt",
",",
"result",
")",
":",
"if",
"not",
"self",
".",
"auto_nwk_create",
":",
"LOG",
".",
"info",
"(",
"\"Auto network creation disabled\"",
")",
"return",
"Fals... | 46.410256 | 0.001623 |
def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120):
"""Fetch a JSON result via HTTP
"""
if not 'Content-Type' in headers:
headers['Content-Type'] = ['application/json']
body = yield cls().getBody(url, method, headers, data, socket, timeout)
... | [
"def",
"getJson",
"(",
"cls",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"headers",
"=",
"{",
"}",
",",
"data",
"=",
"None",
",",
"socket",
"=",
"None",
",",
"timeout",
"=",
"120",
")",
":",
"if",
"not",
"'Content-Type'",
"in",
"headers",
":",
... | 39.555556 | 0.010989 |
def prepareSiiImport(siiContainer, specfile, path, qcAttr, qcLargerBetter,
qcCutoff, rankAttr, rankLargerBetter):
"""Prepares the ``siiContainer`` for the import of peptide spectrum matching
results. Adds entries to ``siiContainer.container`` and to
``siiContainer.info``.
:param si... | [
"def",
"prepareSiiImport",
"(",
"siiContainer",
",",
"specfile",
",",
"path",
",",
"qcAttr",
",",
"qcLargerBetter",
",",
"qcCutoff",
",",
"rankAttr",
",",
"rankLargerBetter",
")",
":",
"if",
"specfile",
"not",
"in",
"siiContainer",
".",
"info",
":",
"siiContai... | 51.864865 | 0.002046 |
def _render(item: ConfigItem, indent: str = "") -> str:
"""
Render a single config item, with the provided indent
"""
optional = item.default_value != _NO_DEFAULT
if is_configurable(item.annotation):
rendered_annotation = f"{item.annotation} (configurable)"
else:
rendered_annota... | [
"def",
"_render",
"(",
"item",
":",
"ConfigItem",
",",
"indent",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"optional",
"=",
"item",
".",
"default_value",
"!=",
"_NO_DEFAULT",
"if",
"is_configurable",
"(",
"item",
".",
"annotation",
")",
":",
"rende... | 30.043478 | 0.001403 |
def from_networkx(cls, G, positions, nodes=None, **kwargs):
"""
Generate a HoloViews Graph from a networkx.Graph object and
networkx layout function or dictionary of node positions.
Any keyword arguments will be passed to the layout
function. By default it will extract all node a... | [
"def",
"from_networkx",
"(",
"cls",
",",
"G",
",",
"positions",
",",
"nodes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"positions",
",",
"dict",
")",
":",
"positions",
"=",
"positions",
"(",
"G",
",",
"*",
"*"... | 42.021739 | 0.002274 |
def verify(self, id):
"""Verify a custom domain
Args:
id (str): The id of the custom domain to delete
See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/post_verify
"""
url = self._url('%s/verify' % (id))
return self.client.post(url) | [
"def",
"verify",
"(",
"self",
",",
"id",
")",
":",
"url",
"=",
"self",
".",
"_url",
"(",
"'%s/verify'",
"%",
"(",
"id",
")",
")",
"return",
"self",
".",
"client",
".",
"post",
"(",
"url",
")"
] | 27 | 0.009772 |
def get_weichert_factor(beta, cmag, cyear, end_year):
'''
Gets the Weichert adjustment factor for each the magnitude bins
:param float beta:
Beta value of Gutenberg & Richter parameter (b * log(10.))
:param np.ndarray cmag:
Magnitude values of the completeness table
:param np.ndar... | [
"def",
"get_weichert_factor",
"(",
"beta",
",",
"cmag",
",",
"cyear",
",",
"end_year",
")",
":",
"if",
"len",
"(",
"cmag",
")",
">",
"1",
":",
"# cval corresponds to the mid-point of the completeness bins",
"# In the original code it requires that the magnitude bins be",
... | 34.6875 | 0.000876 |
def delete(self, item):
"""Deletes the specified item."""
uri = "/%s/%s" % (self.uri_base, utils.get_id(item))
return self._delete(uri) | [
"def",
"delete",
"(",
"self",
",",
"item",
")",
":",
"uri",
"=",
"\"/%s/%s\"",
"%",
"(",
"self",
".",
"uri_base",
",",
"utils",
".",
"get_id",
"(",
"item",
")",
")",
"return",
"self",
".",
"_delete",
"(",
"uri",
")"
] | 39 | 0.012579 |
def filter_geoquiet(sat, maxKp=None, filterTime=None, kpData=None, kp_inst=None):
"""Filters pysat.Instrument data for given time after Kp drops below gate.
Loads Kp data for the same timeframe covered by sat and sets sat.data to
NaN for times when Kp > maxKp and for filterTime after Kp drops below max... | [
"def",
"filter_geoquiet",
"(",
"sat",
",",
"maxKp",
"=",
"None",
",",
"filterTime",
"=",
"None",
",",
"kpData",
"=",
"None",
",",
"kp_inst",
"=",
"None",
")",
":",
"if",
"kp_inst",
"is",
"not",
"None",
":",
"kp_inst",
".",
"load",
"(",
"date",
"=",
... | 33.705882 | 0.008479 |
def mark_as_nsfw(self, unmark_nsfw=False):
"""Mark as Not Safe For Work.
Requires that the currently authenticated user is the author of the
submission, has the modposts oauth scope or has user/password
authentication as a mod of the subreddit.
:returns: The json response from ... | [
"def",
"mark_as_nsfw",
"(",
"self",
",",
"unmark_nsfw",
"=",
"False",
")",
":",
"def",
"mark_as_nsfw_helper",
"(",
"self",
")",
":",
"# pylint: disable=W0613",
"# It is necessary to have the 'self' argument as it's needed in",
"# restrict_access to determine what class the decora... | 43.24 | 0.00181 |
def is_treshold_reached(self, scraped_request):
"""Check if similar requests to the given requests have already been crawled X times. Where X is the
minimum treshold amount from the options.
Args:
scraped_request (:class:`nyawc.http.Request`): The request that possibly reached the ... | [
"def",
"is_treshold_reached",
"(",
"self",
",",
"scraped_request",
")",
":",
"for",
"route",
"in",
"self",
".",
"__routing_options",
".",
"routes",
":",
"if",
"re",
".",
"compile",
"(",
"route",
")",
".",
"match",
"(",
"scraped_request",
".",
"url",
")",
... | 39.55 | 0.008642 |
def heads(directory=None, verbose=False, resolve_dependencies=False):
"""Show current available heads in the script directory"""
if alembic_version >= (0, 7, 0):
config = current_app.extensions['migrate'].migrate.get_config(
directory)
command.heads(config, verbose=verbose,
... | [
"def",
"heads",
"(",
"directory",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"resolve_dependencies",
"=",
"False",
")",
":",
"if",
"alembic_version",
">=",
"(",
"0",
",",
"7",
",",
"0",
")",
":",
"config",
"=",
"current_app",
".",
"extensions",
"[... | 49.333333 | 0.002212 |
def stack_decoders(self, *layers):
"""
Stack decoding layers.
"""
self.stack(*layers)
self.decoding_layers.extend(layers) | [
"def",
"stack_decoders",
"(",
"self",
",",
"*",
"layers",
")",
":",
"self",
".",
"stack",
"(",
"*",
"layers",
")",
"self",
".",
"decoding_layers",
".",
"extend",
"(",
"layers",
")"
] | 26 | 0.012422 |
def get_git_hash(from_url):
"""
Get the git commit hash of HEAD from :from_url.
Args:
from_url: The file system url of our git repository.
Returns:
git commit hash of HEAD, or empty string.
"""
from benchbuild.utils.cmd import git
if from_url is None:
return ""
... | [
"def",
"get_git_hash",
"(",
"from_url",
")",
":",
"from",
"benchbuild",
".",
"utils",
".",
"cmd",
"import",
"git",
"if",
"from_url",
"is",
"None",
":",
"return",
"\"\"",
"if",
"not",
"path",
".",
"exists",
"(",
"from_url",
")",
":",
"return",
"\"\"",
"... | 22.894737 | 0.002208 |
def exhaustive_fragment_check( self,
ontology:pd.DataFrame,
iri_curie_fragment_predicate:str = 'iri',
cross_reference_iris:bool = False,
cross_reference_fragments:bool = False,
... | [
"def",
"exhaustive_fragment_check",
"(",
"self",
",",
"ontology",
":",
"pd",
".",
"DataFrame",
",",
"iri_curie_fragment_predicate",
":",
"str",
"=",
"'iri'",
",",
"cross_reference_iris",
":",
"bool",
"=",
"False",
",",
"cross_reference_fragments",
":",
"bool",
"="... | 53.744681 | 0.008554 |
def add(self, key, value):
"""Add CLI Arg to lists value.
Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
"""
if isinstance(value, list):
# TODO: support env vars in list w/masked values
... | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"# TODO: support env vars in list w/masked values",
"for",
"val",
"in",
"value",
":",
"self",
".",
"_add_arg_python",
"(",
"key",
",",
"... | 41.310345 | 0.001631 |
def explain(self, bindVars={}, allPlans = False) :
"""Returns an explanation of the query. Setting allPlans to True will result in ArangoDB returning all possible plans. False returns only the optimal plan"""
return self.database.explainAQLQuery(self.query, bindVars, allPlans) | [
"def",
"explain",
"(",
"self",
",",
"bindVars",
"=",
"{",
"}",
",",
"allPlans",
"=",
"False",
")",
":",
"return",
"self",
".",
"database",
".",
"explainAQLQuery",
"(",
"self",
".",
"query",
",",
"bindVars",
",",
"allPlans",
")"
] | 97 | 0.020478 |
def _handle_result_by_key_slice(self, key_slice):
"""
Handle processing when the result argument provided is a key slice.
"""
invalid_options = ('key', 'keys', 'startkey', 'endkey')
if any(x in invalid_options for x in self.options):
raise ResultException(102, invalid... | [
"def",
"_handle_result_by_key_slice",
"(",
"self",
",",
"key_slice",
")",
":",
"invalid_options",
"=",
"(",
"'key'",
",",
"'keys'",
",",
"'startkey'",
",",
"'endkey'",
")",
"if",
"any",
"(",
"x",
"in",
"invalid_options",
"for",
"x",
"in",
"self",
".",
"opt... | 37.428571 | 0.00186 |
def add_infos(self, *keyvals, **kwargs):
"""Adds the given info and returns a dict composed of just this added info."""
kv_pairs = []
for key, val in keyvals:
key = key.strip()
val = str(val).strip()
if ':' in key:
raise ValueError('info key "{}" must not contain a colon.'.format(k... | [
"def",
"add_infos",
"(",
"self",
",",
"*",
"keyvals",
",",
"*",
"*",
"kwargs",
")",
":",
"kv_pairs",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"keyvals",
":",
"key",
"=",
"key",
".",
"strip",
"(",
")",
"val",
"=",
"str",
"(",
"val",
")",
... | 34.695652 | 0.014634 |
def keyPressEvent(self, event):
"""Reimplement Qt method"""
if event == QKeySequence.Copy:
self.copy()
else:
QTableView.keyPressEvent(self, event) | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
"==",
"QKeySequence",
".",
"Copy",
":",
"self",
".",
"copy",
"(",
")",
"else",
":",
"QTableView",
".",
"keyPressEvent",
"(",
"self",
",",
"event",
")"
] | 32.333333 | 0.01005 |
def write(self, s: str) -> None:
"""Add str to internal bytes buffer and if echo is True, echo contents to inner stream"""
if not isinstance(s, str):
raise TypeError('write() argument must be str, not {}'.format(type(s)))
if not self.pause_storage:
self.buffer.byte_buf +... | [
"def",
"write",
"(",
"self",
",",
"s",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'write() argument must be str, not {}'",
".",
"format",
"(",
"type",
"(",
"s",
")",
")",
... | 47.444444 | 0.011494 |
def _create_simulated_annealing_expander(schedule):
'''
Creates an expander that has a random chance to choose a node that is worse
than the current (first) node, but that chance decreases with time.
'''
def _expander(fringe, iteration, viewer):
T = schedule(iteration)
current = frin... | [
"def",
"_create_simulated_annealing_expander",
"(",
"schedule",
")",
":",
"def",
"_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"T",
"=",
"schedule",
"(",
"iteration",
")",
"current",
"=",
"fringe",
"[",
"0",
"]",
"neighbors",
"=",
... | 33.041667 | 0.001225 |
def update_state(self):
"""
Update state with latest info from Wink API.
"""
response = self.api_interface.local_get_state(self, type_override="binary_switche")
return self._update_state_from_response(response) | [
"def",
"update_state",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"api_interface",
".",
"local_get_state",
"(",
"self",
",",
"type_override",
"=",
"\"binary_switche\"",
")",
"return",
"self",
".",
"_update_state_from_response",
"(",
"response",
")"
] | 41.666667 | 0.011765 |
def digest_secure_bootloader(args):
""" Calculate the digest of a bootloader image, in the same way the hardware
secure boot engine would do so. Can be used with a pre-loaded key to update a
secure bootloader. """
if args.iv is not None:
print("WARNING: --iv argument is for TESTING PURPOSES ONLY... | [
"def",
"digest_secure_bootloader",
"(",
"args",
")",
":",
"if",
"args",
".",
"iv",
"is",
"not",
"None",
":",
"print",
"(",
"\"WARNING: --iv argument is for TESTING PURPOSES ONLY\"",
")",
"iv",
"=",
"args",
".",
"iv",
".",
"read",
"(",
"128",
")",
"else",
":"... | 42.224138 | 0.001995 |
def PCM_encode(x,N_bits):
"""
Parameters
----------
x : signal samples to be PCM encoded
N_bits ; bit precision of PCM samples
Returns
-------
x_bits = encoded serial bit stream of 0/1 values. MSB first.
Mark Wickert, Mark 2015
"""
xq = np.int16(np.rint(x*2**(N_bits-1)))
... | [
"def",
"PCM_encode",
"(",
"x",
",",
"N_bits",
")",
":",
"xq",
"=",
"np",
".",
"int16",
"(",
"np",
".",
"rint",
"(",
"x",
"*",
"2",
"**",
"(",
"N_bits",
"-",
"1",
")",
")",
")",
"x_bits",
"=",
"np",
".",
"zeros",
"(",
"(",
"N_bits",
",",
"le... | 27.05 | 0.014286 |
def _maybe_validate_distributions(distributions, dtype_override, validate_args):
"""Checks that `distributions` satisfies all assumptions."""
assertions = []
if not _is_iterable(distributions) or not distributions:
raise ValueError('`distributions` must be a list of one or more '
'distri... | [
"def",
"_maybe_validate_distributions",
"(",
"distributions",
",",
"dtype_override",
",",
"validate_args",
")",
":",
"assertions",
"=",
"[",
"]",
"if",
"not",
"_is_iterable",
"(",
"distributions",
")",
"or",
"not",
"distributions",
":",
"raise",
"ValueError",
"(",... | 40.591837 | 0.008346 |
def make_full_ivar():
""" take the scatters and skylines and make final ivars """
# skylines come as an ivar
# don't use them for now, because I don't really trust them...
# skylines = np.load("%s/skylines.npz" %DATA_DIR)['arr_0']
ref_flux = np.load("%s/ref_flux_all.npz" %DATA_DIR)['arr_0']
re... | [
"def",
"make_full_ivar",
"(",
")",
":",
"# skylines come as an ivar",
"# don't use them for now, because I don't really trust them...",
"# skylines = np.load(\"%s/skylines.npz\" %DATA_DIR)['arr_0']",
"ref_flux",
"=",
"np",
".",
"load",
"(",
"\"%s/ref_flux_all.npz\"",
"%",
"DATA_DIR",... | 46.375 | 0.009683 |
def _call(self, x, out=None):
"""Extend ``x`` from the subspace."""
if out is None:
out = self.range.zero()
else:
out.set_zero()
out[self.index] = x
return out | [
"def",
"_call",
"(",
"self",
",",
"x",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"self",
".",
"range",
".",
"zero",
"(",
")",
"else",
":",
"out",
".",
"set_zero",
"(",
")",
"out",
"[",
"self",
".",
"index"... | 24 | 0.008929 |
def create_director(self, service_id, version_number,
name,
quorum=75,
_type=FastlyDirectorType.RANDOM,
retries=5,
shield=None):
"""Create a director for a particular service and version."""
body = self._formdata({
"name": name,
"quorum": quorum,
"type": _type,
"retries": retries,
"shield... | [
"def",
"create_director",
"(",
"self",
",",
"service_id",
",",
"version_number",
",",
"name",
",",
"quorum",
"=",
"75",
",",
"_type",
"=",
"FastlyDirectorType",
".",
"RANDOM",
",",
"retries",
"=",
"5",
",",
"shield",
"=",
"None",
")",
":",
"body",
"=",
... | 29.294118 | 0.048638 |
def save(self, commit=True):
"""
Override save method to also save the localised fields.
"""
# set the localised fields
for localized_field in self.instance.localized_fields:
setattr(self.instance, localized_field, self.cleaned_data[localized_field])
return s... | [
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"# set the localised fields",
"for",
"localized_field",
"in",
"self",
".",
"instance",
".",
"localized_fields",
":",
"setattr",
"(",
"self",
".",
"instance",
",",
"localized_field",
",",
"self",... | 38.888889 | 0.00838 |
def get(self, schema, query=None, **kwargs):
"""
get matching rows from the db matching filters set in query
schema -- Schema()
query -- Query()
return -- list -- a list of matching dicts
"""
ret = self._get_query(self._get, schema, query, **kwargs)
if n... | [
"def",
"get",
"(",
"self",
",",
"schema",
",",
"query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"self",
".",
"_get_query",
"(",
"self",
".",
"_get",
",",
"schema",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"re... | 28.666667 | 0.008451 |
def simulation_smoother(self,beta):
""" Koopman's simulation smoother - simulates from states given
model latent variables and observations
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
---... | [
"def",
"simulation_smoother",
"(",
"self",
",",
"beta",
")",
":",
"T",
",",
"Z",
",",
"R",
",",
"Q",
",",
"H",
"=",
"self",
".",
"_ss_matrices",
"(",
"beta",
")",
"# Generate e_t+ and n_t+",
"rnd_h",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",... | 33.780488 | 0.017544 |
def InspectZipFile(self, parser_mediator, zip_file):
"""Parses an OXML file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
zip_file (zipfile.ZipFile): the zip file containing OXML content. It is
... | [
"def",
"InspectZipFile",
"(",
"self",
",",
"parser_mediator",
",",
"zip_file",
")",
":",
"try",
":",
"xml_data",
"=",
"zip_file",
".",
"read",
"(",
"'_rels/.rels'",
")",
"property_files",
"=",
"self",
".",
"_ParseRelationshipsXMLFile",
"(",
"xml_data",
")",
"e... | 44.764045 | 0.001965 |
def create_get_property_request_content(option):
"""Creates an XML for requesting of getting a property value of remote WebDAV resource.
:param option: the property attributes as dictionary with following keys:
`namespace`: (optional) the namespace for XML property which will be ... | [
"def",
"create_get_property_request_content",
"(",
"option",
")",
":",
"root",
"=",
"etree",
".",
"Element",
"(",
"'propfind'",
",",
"xmlns",
"=",
"'DAV:'",
")",
"prop",
"=",
"etree",
".",
"SubElement",
"(",
"root",
",",
"'prop'",
")",
"etree",
".",
"SubEl... | 56.076923 | 0.008097 |
def select(self, key, where=None, start=None, stop=None, columns=None,
iterator=False, chunksize=None, auto_close=False, **kwargs):
"""
Retrieve pandas object stored in file, optionally based on where
criteria
Parameters
----------
key : object
whe... | [
"def",
"select",
"(",
"self",
",",
"key",
",",
"where",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"iterator",
"=",
"False",
",",
"chunksize",
"=",
"None",
",",
"auto_close",
"=",
"False",
",... | 37.977273 | 0.00175 |
def lease(self, ttl, lease_id=None):
"""
Create a new lease.
All keys attached to this lease will be expired and deleted if the
lease expires. A lease can be sent keep alive messages to refresh the
ttl.
:param ttl: Requested time to live
:param lease_id: Request... | [
"def",
"lease",
"(",
"self",
",",
"ttl",
",",
"lease_id",
"=",
"None",
")",
":",
"lease_grant_request",
"=",
"etcdrpc",
".",
"LeaseGrantRequest",
"(",
"TTL",
"=",
"ttl",
",",
"ID",
"=",
"lease_id",
")",
"lease_grant_response",
"=",
"self",
".",
"leasestub"... | 35.083333 | 0.002312 |
def fetchEntries(self):
"""GETs the corresponding chart data from Billboard.com, then parses
the data using BeautifulSoup.
"""
if not self.date:
# Fetch latest chart
url = 'http://www.billboard.com/charts/%s' % (self.name)
else:
url = 'http://w... | [
"def",
"fetchEntries",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"date",
":",
"# Fetch latest chart",
"url",
"=",
"'http://www.billboard.com/charts/%s'",
"%",
"(",
"self",
".",
"name",
")",
"else",
":",
"url",
"=",
"'http://www.billboard.com/charts/%s/%s'",... | 40.217949 | 0.002489 |
def calculateOptionPrice(self, reqId, contract, volatility, underPrice):
"""calculateOptionPrice(EClient self, TickerId reqId, Contract contract, double volatility, double underPrice)"""
return _swigibpy.EClient_calculateOptionPrice(self, reqId, contract, volatility, underPrice) | [
"def",
"calculateOptionPrice",
"(",
"self",
",",
"reqId",
",",
"contract",
",",
"volatility",
",",
"underPrice",
")",
":",
"return",
"_swigibpy",
".",
"EClient_calculateOptionPrice",
"(",
"self",
",",
"reqId",
",",
"contract",
",",
"volatility",
",",
"underPrice... | 97.666667 | 0.013559 |
def read_paraphrase_file(filename):
'''
Reads in a GermaNet wiktionary paraphrase file and returns its
contents as a list of dictionary structures.
Arguments:
- `filename`:
'''
with open(filename, 'rb') as input_file:
doc = etree.parse(input_file)
assert doc.getroot().tag == 'w... | [
"def",
"read_paraphrase_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"input_file",
":",
"doc",
"=",
"etree",
".",
"parse",
"(",
"input_file",
")",
"assert",
"doc",
".",
"getroot",
"(",
")",
".",
"tag",
"=="... | 40.131579 | 0.00064 |
def get_all_accounts(self):
"""iterates through trie to and yields non-blank leafs as accounts."""
for address_hash, rlpdata in self.secure_trie.trie.iter_branch():
if rlpdata != trie.BLANK_NODE:
yield rlp.decode(rlpdata, Account, db=self.db, addr=address_hash) | [
"def",
"get_all_accounts",
"(",
"self",
")",
":",
"for",
"address_hash",
",",
"rlpdata",
"in",
"self",
".",
"secure_trie",
".",
"trie",
".",
"iter_branch",
"(",
")",
":",
"if",
"rlpdata",
"!=",
"trie",
".",
"BLANK_NODE",
":",
"yield",
"rlp",
".",
"decode... | 60.2 | 0.009836 |
def check_user(user):
'''
Check user and assign process uid/gid.
'''
if salt.utils.platform.is_windows():
return True
if user == salt.utils.user.get_user():
return True
import pwd # after confirming not running Windows
try:
pwuser = pwd.getpwnam(user)
try:
... | [
"def",
"check_user",
"(",
"user",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"return",
"True",
"if",
"user",
"==",
"salt",
".",
"utils",
".",
"user",
".",
"get_user",
"(",
")",
":",
"return",
"True",
"i... | 34.319149 | 0.001808 |
def get_var_arr(self):
''' getter '''
if isinstance(self.__var_arr, np.ndarray):
return self.__var_arr
else:
raise TypeError() | [
"def",
"get_var_arr",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"__var_arr",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"self",
".",
"__var_arr",
"else",
":",
"raise",
"TypeError",
"(",
")"
] | 28.166667 | 0.011494 |
def delete(filepath):
"""
Delete the given file, directory or link.
It Should support undelete later on.
Args:
filepath (str): Absolute full path to a file. e.g. /path/to/file
"""
# Some files have ACLs, let's remove them recursively
remove_acl(filepath)
# Some files have immu... | [
"def",
"delete",
"(",
"filepath",
")",
":",
"# Some files have ACLs, let's remove them recursively",
"remove_acl",
"(",
"filepath",
")",
"# Some files have immutable attributes, let's remove them recursively",
"remove_immutable_attribute",
"(",
"filepath",
")",
"# Finally remove the ... | 29.4 | 0.001647 |
def interm_fluent_ordering(self) -> List[str]:
'''The list of intermediate-fluent names in canonical order.
Returns:
List[str]: A list of fluent names.
'''
interm_fluents = self.intermediate_fluents.values()
key = lambda pvar: (pvar.level, pvar.name)
return [... | [
"def",
"interm_fluent_ordering",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"interm_fluents",
"=",
"self",
".",
"intermediate_fluents",
".",
"values",
"(",
")",
"key",
"=",
"lambda",
"pvar",
":",
"(",
"pvar",
".",
"level",
",",
"pvar",
".",
... | 40.666667 | 0.008021 |
def generate(self, api):
"""Generates a file that lists each namespace."""
with self.output_to_relative_path('ex1.out'):
for namespace in api.namespaces.values():
self.emit(namespace.name) | [
"def",
"generate",
"(",
"self",
",",
"api",
")",
":",
"with",
"self",
".",
"output_to_relative_path",
"(",
"'ex1.out'",
")",
":",
"for",
"namespace",
"in",
"api",
".",
"namespaces",
".",
"values",
"(",
")",
":",
"self",
".",
"emit",
"(",
"namespace",
"... | 45.6 | 0.008621 |
def authenticate(realm, authid, details):
"""
application_name : name of your application
version : version of your application
required_components dictionary of components required for you application
and their version required
{
"component" : "1.1",
"component2" : "0... | [
"def",
"authenticate",
"(",
"realm",
",",
"authid",
",",
"details",
")",
":",
"global",
"_start",
"global",
"_waiting",
"import",
"json",
"ticket",
"=",
"json",
".",
"loads",
"(",
"details",
"[",
"'ticket'",
"]",
")",
"if",
"'application_name'",
"not",
"in... | 37.44898 | 0.001062 |
async def send(self, request: Request[HTTPRequestType], **config: Any) -> Response[HTTPRequestType, AsyncHTTPResponseType]:
"""Send the request using this HTTP sender.
"""
pass | [
"async",
"def",
"send",
"(",
"self",
",",
"request",
":",
"Request",
"[",
"HTTPRequestType",
"]",
",",
"*",
"*",
"config",
":",
"Any",
")",
"->",
"Response",
"[",
"HTTPRequestType",
",",
"AsyncHTTPResponseType",
"]",
":",
"pass"
] | 49.25 | 0.015 |
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
... | [
"def",
"image_list",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"nt_ks",
"=",
"self",
".",
"compute_conn",
"ret",
"=",
"{",
"}",
"for",
"image",
"in",
"nt_ks",
".",
"images",
".",
"list",
"(",
")",
":",
"links",
"=",
"{",
"}",
"for",
"link"... | 32.962963 | 0.002183 |
def dosdate(dosdate, dostime):
"""
`dosdate`: 2 bytes, little endian.
`dostime`: 2 bytes, little endian.
returns: datetime.datetime or datetime.datetime.min on error
"""
try:
t = ord(dosdate[1]) << 8
t |= ord(dosdate[0])
day = t & 0b0000000000011111
month = (t ... | [
"def",
"dosdate",
"(",
"dosdate",
",",
"dostime",
")",
":",
"try",
":",
"t",
"=",
"ord",
"(",
"dosdate",
"[",
"1",
"]",
")",
"<<",
"8",
"t",
"|=",
"ord",
"(",
"dosdate",
"[",
"0",
"]",
")",
"day",
"=",
"t",
"&",
"0b0000000000011111",
"month",
"... | 29.75 | 0.013569 |
def qual_name(self) -> QualName:
"""Return the receiver's qualified name."""
p, s, loc = self._key.partition(":")
return (loc, p) if s else (p, self.namespace) | [
"def",
"qual_name",
"(",
"self",
")",
"->",
"QualName",
":",
"p",
",",
"s",
",",
"loc",
"=",
"self",
".",
"_key",
".",
"partition",
"(",
"\":\"",
")",
"return",
"(",
"loc",
",",
"p",
")",
"if",
"s",
"else",
"(",
"p",
",",
"self",
".",
"namespac... | 45 | 0.010929 |
def data(self, data=None, ret_r=False):
'''response data'''
if data or ret_r:
self._data = data
return self
return self._data | [
"def",
"data",
"(",
"self",
",",
"data",
"=",
"None",
",",
"ret_r",
"=",
"False",
")",
":",
"if",
"data",
"or",
"ret_r",
":",
"self",
".",
"_data",
"=",
"data",
"return",
"self",
"return",
"self",
".",
"_data"
] | 28 | 0.011561 |
def _onLog(self, mqttc, obj, level, string):
"""
Called when the client has log information.
See [paho.mqtt.python#on_log](https://github.com/eclipse/paho.mqtt.python#on_log) for more information
# Parameters
mqttc (paho.mqtt.client.Client): The client instanc... | [
"def",
"_onLog",
"(",
"self",
",",
"mqttc",
",",
"obj",
",",
"level",
",",
"string",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"%d %s\"",
"%",
"(",
"level",
",",
"string",
")",
")"
] | 46.733333 | 0.015385 |
def setAllColor(self, color):
"""
Command: 0x06
sets all colors in the array
Data:
[Command][r][g][b]
"""
header = bytearray()
header.append(LightProtocolCommand.SetAllColor)
light = bytearray()
light.extend(color)
buff = header + light
return self.send(buff) | [
"def",
"setAllColor",
"(",
"self",
",",
"color",
")",
":",
"header",
"=",
"bytearray",
"(",
")",
"header",
".",
"append",
"(",
"LightProtocolCommand",
".",
"SetAllColor",
")",
"light",
"=",
"bytearray",
"(",
")",
"light",
".",
"extend",
"(",
"color",
")"... | 15.055556 | 0.048611 |
def view_meta_admonition(admonition_name, name=None):
"""List all found admonition from all the rst files found in directory.
view_meta_admonition is called by the 'meta' url: /__XXXXXXX__
where XXXXXXX represents and admonition name, like:
* todo
* warning
* danger
* ...
.. note:: th... | [
"def",
"view_meta_admonition",
"(",
"admonition_name",
",",
"name",
"=",
"None",
")",
":",
"print",
"(",
"\"meta admo: %s - %s\"",
"%",
"(",
"admonition_name",
",",
"name",
")",
")",
"admonition",
"=",
"None",
"if",
"admonition_name",
"==",
"'todo'",
":",
"adm... | 37.459016 | 0.000213 |
def _record(self, ext_loc, parent_dir_num):
# type: (int, int) -> bytes
'''
An internal method to generate a string representing this Path Table Record.
Parameters:
ext_loc - The extent location to place in this Path Table Record.
parent_dir_num - The parent directory ... | [
"def",
"_record",
"(",
"self",
",",
"ext_loc",
",",
"parent_dir_num",
")",
":",
"# type: (int, int) -> bytes",
"return",
"struct",
".",
"pack",
"(",
"self",
".",
"FMT",
",",
"self",
".",
"len_di",
",",
"self",
".",
"xattr_length",
",",
"ext_loc",
",",
"par... | 45.571429 | 0.009217 |
def load_calls(self, call_type='jsonrpc'):
"""Loads the KvasirAPI calls into API.call based on the call_type variable. Utilizes the `Calls` class to
establish an attribute-based access method. For instance a configuration with an instance called 'internal'
will create an API.call that can be use... | [
"def",
"load_calls",
"(",
"self",
",",
"call_type",
"=",
"'jsonrpc'",
")",
":",
"valid",
"=",
"False",
"if",
"call_type",
"==",
"'jsonrpc'",
":",
"#from jsonrpc import Hosts, Services, Accounts, Vulns, OS, NetBIOS, Evidence",
"import",
"jsonrpc",
"as",
"api_calls",
"sel... | 64.264706 | 0.009017 |
def calcChebyshev(coeffs, validDomain, freqs):
"""
Given a set of coefficients,
this method evaluates a Chebyshev approximation.
Used for CASA bandpass reading.
input coeffs and freqs are numpy arrays
"""
logger = logging.getLogger(__name__)
domain = (validDomain[1] - validDomain[0])[0... | [
"def",
"calcChebyshev",
"(",
"coeffs",
",",
"validDomain",
",",
"freqs",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"domain",
"=",
"(",
"validDomain",
"[",
"1",
"]",
"-",
"validDomain",
"[",
"0",
"]",
")",
"[",
"0",
"... | 39 | 0.014728 |
def infer_dtype_from_object(dtype):
"""
Get a numpy dtype.type-style object for a dtype object.
This methods also includes handling of the datetime64[ns] and
datetime64[ns, TZ] objects.
If no dtype can be found, we return ``object``.
Parameters
----------
dtype : dtype, type
T... | [
"def",
"infer_dtype_from_object",
"(",
"dtype",
")",
":",
"if",
"isinstance",
"(",
"dtype",
",",
"type",
")",
"and",
"issubclass",
"(",
"dtype",
",",
"np",
".",
"generic",
")",
":",
"# Type object from a dtype",
"return",
"dtype",
"elif",
"isinstance",
"(",
... | 29.064516 | 0.000537 |
def fixcode(**kwargs):
"""
auto pep8 format all python file in ``source code`` and ``tests`` dir.
"""
# repository direcotry
repo_dir = Path(__file__).parent.absolute()
# source code directory
source_dir = Path(repo_dir, package.__name__)
if source_dir.exists():
print("Source c... | [
"def",
"fixcode",
"(",
"*",
"*",
"kwargs",
")",
":",
"# repository direcotry",
"repo_dir",
"=",
"Path",
"(",
"__file__",
")",
".",
"parent",
".",
"absolute",
"(",
")",
"# source code directory",
"source_dir",
"=",
"Path",
"(",
"repo_dir",
",",
"package",
"."... | 30.148148 | 0.00119 |
def compute_discounts(self, precision=None):
'''
Returns the total amount of discounts of this group.
@param precision:int Total amount of discounts
@return: Decimal
'''
return sum([line.compute_discounts(precision) for line in self.__lines]) | [
"def",
"compute_discounts",
"(",
"self",
",",
"precision",
"=",
"None",
")",
":",
"return",
"sum",
"(",
"[",
"line",
".",
"compute_discounts",
"(",
"precision",
")",
"for",
"line",
"in",
"self",
".",
"__lines",
"]",
")"
] | 40.571429 | 0.010345 |
def reuse(context, block_list, **kwargs):
'''
Allow reuse of a block within a template.
{% reuse '_myblock' foo=bar %}
If passed a list of block names, will use the first that matches:
{% reuse list_of_block_names .... %}
'''
try:
block_context = context.render_context[BLOCK_CONTE... | [
"def",
"reuse",
"(",
"context",
",",
"block_list",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"block_context",
"=",
"context",
".",
"render_context",
"[",
"BLOCK_CONTEXT_KEY",
"]",
"except",
"KeyError",
":",
"block_context",
"=",
"BlockContext",
"(",
")"... | 24.296296 | 0.001466 |
def compute_search_efficiency_in_bins(
found, total, ndbins,
sim_to_bins_function=lambda sim: (sim.distance,)):
"""
Calculate search efficiency in the given ndbins.
The first dimension of ndbins must be bins over injected distance.
sim_to_bins_function must map an object to a tuple in... | [
"def",
"compute_search_efficiency_in_bins",
"(",
"found",
",",
"total",
",",
"ndbins",
",",
"sim_to_bins_function",
"=",
"lambda",
"sim",
":",
"(",
"sim",
".",
"distance",
",",
")",
")",
":",
"bins",
"=",
"bin_utils",
".",
"BinnedRatios",
"(",
"ndbins",
")",... | 38.076923 | 0.000985 |
def _process_data(self, dd, offsets, data):
# type: (Downloader, blobxfer.models.download.Descriptor,
# blobxfer.models.download.Offsets, bytes) -> None
"""Process downloaded data for disk
:param Downloader self: this
:param blobxfer.models.download.Descriptor dd: download... | [
"def",
"_process_data",
"(",
"self",
",",
"dd",
",",
"offsets",
",",
"data",
")",
":",
"# type: (Downloader, blobxfer.models.download.Descriptor,",
"# blobxfer.models.download.Offsets, bytes) -> None",
"# decrypt if necessary",
"if",
"dd",
".",
"entity",
".",
"is_encry... | 44.369565 | 0.001918 |
def _render_full_resource(self, instance, include, fields):
"""
Generate a representation of a full resource to match JSON API spec.
:param instance: The instance to serialize
:param include: Dictionary of relationships to include
:param fields: Dictionary of fields to filter
... | [
"def",
"_render_full_resource",
"(",
"self",
",",
"instance",
",",
"include",
",",
"fields",
")",
":",
"api_type",
"=",
"instance",
".",
"__jsonapi_type__",
"orm_desc_keys",
"=",
"instance",
".",
"__mapper__",
".",
"all_orm_descriptors",
".",
"keys",
"(",
")",
... | 41.058252 | 0.000462 |
def addvlan(self, vlanid, vlan_name):
"""
Function operates on the IMCDev object. Takes input of vlanid (1-4094), str of vlan_name,
auth and url to execute the create_dev_vlan method on the IMCDev object. Device must be
supported in the HPE IMC Platform VLAN Manager module.
:para... | [
"def",
"addvlan",
"(",
"self",
",",
"vlanid",
",",
"vlan_name",
")",
":",
"create_dev_vlan",
"(",
"vlanid",
",",
"vlan_name",
",",
"self",
".",
"auth",
",",
"self",
".",
"url",
",",
"devid",
"=",
"self",
".",
"devid",
")"
] | 50.8 | 0.015474 |
def connect(url):
"""Connect to UNIX or TCP socket.
url can be either tcp://<host>:port or ipc://<path>
"""
url = urlparse(url)
if url.scheme == 'tcp':
sock = socket()
netloc = tuple(url.netloc.rsplit(':', 1))
hostname = socket.gethostname()
elif url.scheme == 'ipc':... | [
"def",
"connect",
"(",
"url",
")",
":",
"url",
"=",
"urlparse",
"(",
"url",
")",
"if",
"url",
".",
"scheme",
"==",
"'tcp'",
":",
"sock",
"=",
"socket",
"(",
")",
"netloc",
"=",
"tuple",
"(",
"url",
".",
"netloc",
".",
"rsplit",
"(",
"':'",
",",
... | 27.210526 | 0.001869 |
def _create_table_setup(self):
"""
Return a list of SQL statements that creates a table reflecting the
structure of a DataFrame. The first entry will be a CREATE TABLE
statement while the rest will be CREATE INDEX statements.
"""
column_names_and_types = self._get_column... | [
"def",
"_create_table_setup",
"(",
"self",
")",
":",
"column_names_and_types",
"=",
"self",
".",
"_get_column_names_and_types",
"(",
"self",
".",
"_sql_type_name",
")",
"pat",
"=",
"re",
".",
"compile",
"(",
"r'\\s+'",
")",
"column_names",
"=",
"[",
"col_name",
... | 39.883721 | 0.001138 |
def multipart_uploadpart(self, multipart):
"""Upload a part.
:param multipart: A :class:`invenio_files_rest.models.MultipartObject`
instance.
:returns: A Flask response.
"""
content_length, part_number, stream, content_type, content_md5, tags =\
current_f... | [
"def",
"multipart_uploadpart",
"(",
"self",
",",
"multipart",
")",
":",
"content_length",
",",
"part_number",
",",
"stream",
",",
"content_type",
",",
"content_md5",
",",
"tags",
"=",
"current_files_rest",
".",
"multipart_partfactory",
"(",
")",
"if",
"content_len... | 32.621622 | 0.001609 |
def dragMoveEvent( self, event ):
"""
Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDragEvent>
"""
filt = self.dragDropFilter()
if not filt:
super(XTreeWidget, self).dragMoveEvent(... | [
"def",
"dragMoveEvent",
"(",
"self",
",",
"event",
")",
":",
"filt",
"=",
"self",
".",
"dragDropFilter",
"(",
")",
"if",
"not",
"filt",
":",
"super",
"(",
"XTreeWidget",
",",
"self",
")",
".",
"dragMoveEvent",
"(",
"event",
")",
"return",
"filt",
"(",
... | 28.538462 | 0.018277 |
def create_default_layout(config):
"""
Banana banana
"""
project_name = config.get('project_name')
project_version = config.get('project_version')
if not project_name or not project_version:
error('setup-issue',
'--project-name and --project-version must be specified')
... | [
"def",
"create_default_layout",
"(",
"config",
")",
":",
"project_name",
"=",
"config",
".",
"get",
"(",
"'project_name'",
")",
"project_version",
"=",
"config",
".",
"get",
"(",
"'project_version'",
")",
"if",
"not",
"project_name",
"or",
"not",
"project_versio... | 36.72549 | 0.00104 |
def get_content(api, rebuild_cache=False):
"""get content from server or cache"""
if hasattr(get_content, 'cache') and not rebuild_cache:
return get_content.cache
if not os.path.exists(CONTENT_JSON) or rebuild_cache:
import locale
content_endpoint = api.content.get
# pylint: ... | [
"def",
"get_content",
"(",
"api",
",",
"rebuild_cache",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"get_content",
",",
"'cache'",
")",
"and",
"not",
"rebuild_cache",
":",
"return",
"get_content",
".",
"cache",
"if",
"not",
"os",
".",
"path",
".",
"exi... | 35.384615 | 0.000705 |
def query(query, ts, **kwargs):
"""
Perform *query* on the testsuite *ts*.
Note: currently only 'select' queries are supported.
Args:
query (str): TSQL query string
ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over
kwargs: keyword arguments passed to the more speci... | [
"def",
"query",
"(",
"query",
",",
"ts",
",",
"*",
"*",
"kwargs",
")",
":",
"queryobj",
"=",
"_parse_query",
"(",
"query",
")",
"if",
"queryobj",
"[",
"'querytype'",
"]",
"in",
"(",
"'select'",
",",
"'retrieve'",
")",
":",
"return",
"_select",
"(",
"... | 34.033333 | 0.000952 |
def define_threshold(dat, s_freq, method, value, nbins=120):
"""Return the value of the threshold based on relative values.
Parameters
----------
dat : ndarray (dtype='float')
vector with the data after selection-transformation
s_freq : float
sampling frequency
method : str
... | [
"def",
"define_threshold",
"(",
"dat",
",",
"s_freq",
",",
"method",
",",
"value",
",",
"nbins",
"=",
"120",
")",
":",
"if",
"method",
"==",
"'mean'",
":",
"value",
"=",
"value",
"*",
"mean",
"(",
"dat",
")",
"elif",
"method",
"==",
"'median'",
":",
... | 29.076923 | 0.000853 |
def rebuild(args):
"""
%prog rebuild blocksfile blastfile
Rebuild anchors file from pre-built blocks file.
"""
p = OptionParser(rebuild.__doc__)
p.add_option("--header", default=False, action="store_true",
help="First line is header [default: %default]")
p.add_option("--wri... | [
"def",
"rebuild",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"rebuild",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--header\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"First line is head... | 30.34375 | 0.001996 |
def histogram2d(x, y, bins, range, weights=None):
"""
Compute a 2D histogram assuming equally spaced bins.
Parameters
----------
x, y : `~numpy.ndarray`
The position of the points to bin in the 2D histogram
bins : int or iterable
The number of bins in each dimension. If given as... | [
"def",
"histogram2d",
"(",
"x",
",",
"y",
",",
"bins",
",",
"range",
",",
"weights",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"bins",
",",
"numbers",
".",
"Integral",
")",
":",
"nx",
"=",
"ny",
"=",
"bins",
"else",
":",
"nx",
",",
"ny",
... | 28.459016 | 0.001114 |
def private_props(obj):
"""
Yield private properties of an object.
A private property is defined as one that has a single underscore
(:code:`_`) before its name
:param obj: Object
:type obj: object
:returns: iterator
"""
# Get private properties but NOT magic methods
props = ... | [
"def",
"private_props",
"(",
"obj",
")",
":",
"# Get private properties but NOT magic methods",
"props",
"=",
"[",
"item",
"for",
"item",
"in",
"dir",
"(",
"obj",
")",
"]",
"priv_props",
"=",
"[",
"_PRIVATE_PROP_REGEXP",
".",
"match",
"(",
"item",
")",
"for",
... | 32.315789 | 0.001582 |
def get_all(self, endpoint, params=None):
# pylint: disable=too-many-locals
"""
Get all items in the specified endpoint of alignak backend
If an error occurs, a BackendException is raised.
If the max_results parameter is not specified in parameters, it is set to
BACKEND... | [
"def",
"get_all",
"(",
"self",
",",
"endpoint",
",",
"params",
"=",
"None",
")",
":",
"# pylint: disable=too-many-locals",
"# Set max results at maximum value supported by the backend to limit requests number",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"'max_results'"... | 35.807339 | 0.002493 |
def _operator_handling(self, cursor):
"""Returns a string with the literal that are part of the operation."""
values = self._literal_handling(cursor)
retval = ''.join([str(val) for val in values])
return retval | [
"def",
"_operator_handling",
"(",
"self",
",",
"cursor",
")",
":",
"values",
"=",
"self",
".",
"_literal_handling",
"(",
"cursor",
")",
"retval",
"=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"val",
")",
"for",
"val",
"in",
"values",
"]",
")",
"retur... | 47.6 | 0.008264 |
def decode_network(objects):
"""Return root object from ref-containing obj table entries"""
def resolve_ref(obj, objects=objects):
if isinstance(obj, Ref):
# first entry is 1
return objects[obj.index - 1]
else:
return obj
# Reading the ObjTable backwards ... | [
"def",
"decode_network",
"(",
"objects",
")",
":",
"def",
"resolve_ref",
"(",
"obj",
",",
"objects",
"=",
"objects",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Ref",
")",
":",
"# first entry is 1",
"return",
"objects",
"[",
"obj",
".",
"index",
"-",... | 29.520833 | 0.000683 |
def get_jids(self):
"""Return JIDs for which this certificate is valid (except the domain
wildcards).
:Returtype: `list` of `JID`
"""
result = []
if ("XmppAddr" in self.alt_names or "DNS" in self.alt_names
or "SRVName" in self.... | [
"def",
"get_jids",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"if",
"(",
"\"XmppAddr\"",
"in",
"self",
".",
"alt_names",
"or",
"\"DNS\"",
"in",
"self",
".",
"alt_names",
"or",
"\"SRVName\"",
"in",
"self",
".",
"alt_names",
")",
":",
"addrs",
"=",
... | 42.969697 | 0.008276 |
def is_associated_file(self):
# type: () -> bool
'''
A method to determine whether this file is 'associated' with another file
on the ISO.
Parameters:
None.
Returns:
True if this file is associated with another file on the ISO, False
otherwise.... | [
"def",
"is_associated_file",
"(",
"self",
")",
":",
"# type: () -> bool",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'Directory Record not yet initialized'",
")",
"return",
"self",
".",
"file_flags",
... | 32.6875 | 0.009294 |
def get_dashboard(self, id, **kwargs): # noqa: E501
"""Get a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_dashboard(id, async_req=Tr... | [
"def",
"get_dashboard",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_dashboard_... | 40.285714 | 0.002309 |
def read_bitpacked(file_obj, header, width, debug_logging):
"""Read a bitpacked run of the rle/bitpack hybrid.
Supports width >8 (crossing bytes).
"""
num_groups = header >> 1
count = num_groups * 8
byte_count = (width * count) // 8
if debug_logging:
logger.debug("Reading a bit-pack... | [
"def",
"read_bitpacked",
"(",
"file_obj",
",",
"header",
",",
"width",
",",
"debug_logging",
")",
":",
"num_groups",
"=",
"header",
">>",
"1",
"count",
"=",
"num_groups",
"*",
"8",
"byte_count",
"=",
"(",
"width",
"*",
"count",
")",
"//",
"8",
"if",
"d... | 36.785714 | 0.001892 |
def _get_chain_parent_symbol(self, symbol, fullsymbol):
"""Gets the code element object for the parent of the specified
symbol in the fullsymbol chain."""
#We are only interested in the type of the variable immediately preceding our symbol
#in the chain so we can list its members.
... | [
"def",
"_get_chain_parent_symbol",
"(",
"self",
",",
"symbol",
",",
"fullsymbol",
")",
":",
"#We are only interested in the type of the variable immediately preceding our symbol",
"#in the chain so we can list its members.",
"chain",
"=",
"fullsymbol",
".",
"split",
"(",
"\"%\"",... | 46 | 0.012777 |
def _get_ntgpadnt(self, ver, add_ns):
"""Create a namedtuple object for each annotation"""
hdrs = self.gpad_columns[ver]
if add_ns:
hdrs = hdrs + ['NS']
return cx.namedtuple("ntgpadobj", hdrs) | [
"def",
"_get_ntgpadnt",
"(",
"self",
",",
"ver",
",",
"add_ns",
")",
":",
"hdrs",
"=",
"self",
".",
"gpad_columns",
"[",
"ver",
"]",
"if",
"add_ns",
":",
"hdrs",
"=",
"hdrs",
"+",
"[",
"'NS'",
"]",
"return",
"cx",
".",
"namedtuple",
"(",
"\"ntgpadobj... | 38.5 | 0.008475 |
def initialize():
"""
Method to parse and check configurations of FORD, get the project's
global documentation, and create the Markdown reader.
"""
try:
import multiprocessing
ncpus = '{0}'.format(multiprocessing.cpu_count())
except (ImportError, NotImplementedError):
nc... | [
"def",
"initialize",
"(",
")",
":",
"try",
":",
"import",
"multiprocessing",
"ncpus",
"=",
"'{0}'",
".",
"format",
"(",
"multiprocessing",
".",
"cpu_count",
"(",
")",
")",
"except",
"(",
"ImportError",
",",
"NotImplementedError",
")",
":",
"ncpus",
"=",
"'... | 51.866935 | 0.012967 |
def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert Average pooling.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionar... | [
"def",
"convert_avgpool",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting pooling ...'",
")",
"if",
"names",
"==",
"'short'",
":",
"tf_name",
"=",
"'P'",
"+",... | 28.984127 | 0.001589 |
def getSource(self, sourceKey, sourceTime=None):
"""
GetReturn a date/time tuple based on the giving source key
and the corresponding key found in self.re_sources.
The current time is used as the default and any specified
item found in self.re_sources is inserted into the value
... | [
"def",
"getSource",
"(",
"self",
",",
"sourceKey",
",",
"sourceTime",
"=",
"None",
")",
":",
"if",
"sourceKey",
"not",
"in",
"self",
".",
"re_sources",
":",
"return",
"None",
"if",
"sourceTime",
"is",
"None",
":",
"(",
"yr",
",",
"mth",
",",
"dy",
",... | 34.2 | 0.001896 |
def resolve_indices(self, index, start_val):
"""Get indices for the skeleton from the channels when loading in channel data."""
channels = self.vertices[index].meta['channels']
base_channel = start_val
rot_ind = -np.ones(3, dtype=int)
pos_ind = -np.ones(3, dtype=int)
fo... | [
"def",
"resolve_indices",
"(",
"self",
",",
"index",
",",
"start_val",
")",
":",
"channels",
"=",
"self",
".",
"vertices",
"[",
"index",
"]",
".",
"meta",
"[",
"'channels'",
"]",
"base_channel",
"=",
"start_val",
"rot_ind",
"=",
"-",
"np",
".",
"ones",
... | 44.636364 | 0.00997 |
def values(self):
"""
Returns the values for this axis.
:return [<variant>, ..]
"""
if self._values is None:
self._values = self.calculateValues()
return self._values | [
"def",
"values",
"(",
"self",
")",
":",
"if",
"self",
".",
"_values",
"is",
"None",
":",
"self",
".",
"_values",
"=",
"self",
".",
"calculateValues",
"(",
")",
"return",
"self",
".",
"_values"
] | 26.555556 | 0.012146 |
def get_nnsoap(obj, first_shell, alphas, betas, rcut=6, nmax=10, lmax=9, all_atomtypes=[]):
"""Takes cluster structure and nearest neighbour information of a datapoint,
Returns concatenated soap vectors for each nearest
neighbour (up to 3). Top, bridge, hollow fill the initial
zero soap vector from left... | [
"def",
"get_nnsoap",
"(",
"obj",
",",
"first_shell",
",",
"alphas",
",",
"betas",
",",
"rcut",
"=",
"6",
",",
"nmax",
"=",
"10",
",",
"lmax",
"=",
"9",
",",
"all_atomtypes",
"=",
"[",
"]",
")",
":",
"soap_vector",
"=",
"[",
"]",
"nnn",
"=",
"len"... | 43.038462 | 0.011364 |
def from_music_service(cls, music_service, content_dict):
"""Return an element instantiated from the information that a music
service has (alternative constructor)
Args:
music_service (MusicService): The music service that content_dict
originated from
con... | [
"def",
"from_music_service",
"(",
"cls",
",",
"music_service",
",",
"content_dict",
")",
":",
"# Form the item_id",
"quoted_id",
"=",
"quote_url",
"(",
"content_dict",
"[",
"'id'",
"]",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"# The hex prefix remains a mistery for... | 42.32 | 0.001848 |
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
cmd = '/usr/sbin/svcadm refresh {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling reload doesn't clear maintenanc... | [
"def",
"reload_",
"(",
"name",
")",
":",
"cmd",
"=",
"'/usr/sbin/svcadm refresh {0}'",
".",
"format",
"(",
"name",
")",
"if",
"not",
"__salt__",
"[",
"'cmd.retcode'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
":",
"# calling reload doesn't clear... | 25.8125 | 0.002336 |
def log_start_finish(msg, logger, level=logging.DEBUG):
"""
A context manager to log messages with "start: " and "finish: "
prefixes before and after a block.
Parameters
----------
msg : str
Will be prefixed with "start: " and "finish: ".
logger : logging.Logger
level : int, opt... | [
"def",
"log_start_finish",
"(",
"msg",
",",
"logger",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"logger",
".",
"log",
"(",
"level",
",",
"'start: '",
"+",
"msg",
")",
"yield",
"logger",
".",
"log",
"(",
"level",
",",
"'finish: '",
"+",
"m... | 27.294118 | 0.002083 |
def create_script_acl(self, id_vlan, network_type):
'''Generate the script acl
:param id_vlan: Vlan Id
:param network_type: v4 or v6
:raise InvalidValueError: Attrs invalids.
:raise XMLError: Networkapi failed to generate the XML response.
:raise VlanACLDuplicatedError:... | [
"def",
"create_script_acl",
"(",
"self",
",",
"id_vlan",
",",
"network_type",
")",
":",
"vlan_map",
"=",
"dict",
"(",
")",
"vlan_map",
"[",
"'id_vlan'",
"]",
"=",
"id_vlan",
"vlan_map",
"[",
"'network_type'",
"]",
"=",
"network_type",
"url",
"=",
"'vlan/crea... | 29.225 | 0.001656 |
def save(self, file=CONFIG_FILE):
"""
Save configuration to provided path as a yaml file
"""
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "w") as f:
yaml.dump(self._settings, f, Dumper=yaml.RoundTripDumper, width=float("inf")) | [
"def",
"save",
"(",
"self",
",",
"file",
"=",
"CONFIG_FILE",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"file",
")",
",",
"exist_ok",
"=",
"True",
")",
"with",
"open",
"(",
"file",
",",
"\"w\"",
")",
"as",
"f",
... | 41.857143 | 0.010033 |
def rpc_fix_code(self, source, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
source = get_source(source)
return fix_code(source, directory) | [
"def",
"rpc_fix_code",
"(",
"self",
",",
"source",
",",
"directory",
")",
":",
"source",
"=",
"get_source",
"(",
"source",
")",
"return",
"fix_code",
"(",
"source",
",",
"directory",
")"
] | 32.833333 | 0.009901 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.