text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def plot(self, *args, **kwargs):
"""Plot data onto these axes
Parameters
----------
args
a single instance of
- `~gwpy.segments.DataQualityFlag`
- `~gwpy.segments.Segment`
- `~gwpy.segments.SegmentList`
- `~gwp... | [
"def",
"plot",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"[",
"]",
"args",
"=",
"list",
"(",
"args",
")",
"while",
"args",
":",
"try",
":",
"plotter",
"=",
"self",
".",
"_plot_method",
"(",
"args",
"[",
"0",
... | 28.463415 | 21.219512 |
def ls_(path='/', profile=None, **kwargs):
'''
.. versionadded:: 2014.7.0
Return all keys and dirs inside a specific path. Returns an empty dict on
failure.
CLI Example:
.. code-block:: bash
salt myminion etcd.ls /path/to/dir/
salt myminion etcd.ls /path/to/dir/ profile=my_e... | [
"def",
"ls_",
"(",
"path",
"=",
"'/'",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"__utils__",
"[",
"'etcd_util.get_conn'",
"]",
"(",
"__opts__",
",",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"client",
".... | 27.277778 | 27.055556 |
def update_or_create(self, attributes, values=None, joining=None, touch=True):
"""
Create or update a related record matching the attributes, and fill it with values.
:param attributes: The attributes
:type attributes: dict
:param values: The values
:type values: dict
... | [
"def",
"update_or_create",
"(",
"self",
",",
"attributes",
",",
"values",
"=",
"None",
",",
"joining",
"=",
"None",
",",
"touch",
"=",
"True",
")",
":",
"if",
"values",
"is",
"None",
":",
"values",
"=",
"{",
"}",
"instance",
"=",
"self",
".",
"_query... | 24.88 | 22.4 |
def __gridconnections(self):
"""Level-2 parser for gridconnections.
pattern:
object 2 class gridconnections counts 97 93 99
"""
try:
tok = self.__consume()
except DXParserNoTokens:
return
if tok.equals('counts'):
shape = []
... | [
"def",
"__gridconnections",
"(",
"self",
")",
":",
"try",
":",
"tok",
"=",
"self",
".",
"__consume",
"(",
")",
"except",
"DXParserNoTokens",
":",
"return",
"if",
"tok",
".",
"equals",
"(",
"'counts'",
")",
":",
"shape",
"=",
"[",
"]",
"try",
":",
"wh... | 33.076923 | 16.961538 |
def pkginfo_to_metadata(egg_info_path, pkginfo_path):
"""
Convert .egg-info directory with PKG-INFO to the Metadata 2.1 format
"""
pkg_info = read_pkg_info(pkginfo_path)
pkg_info.replace_header('Metadata-Version', '2.1')
requires_path = os.path.join(egg_info_path, 'requires.txt')
if os.path.... | [
"def",
"pkginfo_to_metadata",
"(",
"egg_info_path",
",",
"pkginfo_path",
")",
":",
"pkg_info",
"=",
"read_pkg_info",
"(",
"pkginfo_path",
")",
"pkg_info",
".",
"replace_header",
"(",
"'Metadata-Version'",
",",
"'2.1'",
")",
"requires_path",
"=",
"os",
".",
"path",... | 39.857143 | 15.380952 |
def to_html(self):
"""Render a Text MessageElement as html
Args:
None
Returns:
Str the html representation of the Text MessageElement
Raises:
Errors are propagated
"""
if self.items is None:
return
else:
... | [
"def",
"to_html",
"(",
"self",
")",
":",
"if",
"self",
".",
"items",
"is",
"None",
":",
"return",
"else",
":",
"html",
"=",
"'<ol%s>\\n'",
"%",
"self",
".",
"html_attributes",
"(",
")",
"for",
"item",
"in",
"self",
".",
"items",
":",
"html",
"+=",
... | 24.55 | 19.95 |
def assemble_phi5_works_filepaths():
"""Reads PHI5 index and builds a list of absolute filepaths."""
plaintext_dir_rel = '~/cltk_data/latin/text/phi5/individual_works/'
plaintext_dir = os.path.expanduser(plaintext_dir_rel)
all_filepaths = []
for author_code in PHI5_WORKS_INDEX:
author_data =... | [
"def",
"assemble_phi5_works_filepaths",
"(",
")",
":",
"plaintext_dir_rel",
"=",
"'~/cltk_data/latin/text/phi5/individual_works/'",
"plaintext_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"plaintext_dir_rel",
")",
"all_filepaths",
"=",
"[",
"]",
"for",
"author_... | 46 | 13.916667 |
def real_time_statistics(self):
"""
Access the real_time_statistics
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics.WorkflowRealTimeStat... | [
"def",
"real_time_statistics",
"(",
"self",
")",
":",
"if",
"self",
".",
"_real_time_statistics",
"is",
"None",
":",
"self",
".",
"_real_time_statistics",
"=",
"WorkflowRealTimeStatisticsList",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
... | 46.5 | 23.071429 |
def create_silence(length):
"""Create a piece of silence."""
data = bytearray(length)
i = 0
while i < length:
data[i] = 128
i += 1
return data | [
"def",
"create_silence",
"(",
"length",
")",
":",
"data",
"=",
"bytearray",
"(",
"length",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"length",
":",
"data",
"[",
"i",
"]",
"=",
"128",
"i",
"+=",
"1",
"return",
"data"
] | 21.375 | 18.125 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'limit') and self.limit is not None:
_dict['limit'] = self.limit
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'limit'",
")",
"and",
"self",
".",
"limit",
"is",
"not",
"None",
":",
"_dict",
"[",
"'limit'",
"]",
"=",
"self",
".",
"limit",
"return",
"_dict"
] | 36.666667 | 14.166667 |
def sync_blockchain( working_dir, bt_opts, last_block, server_state, expected_snapshots={}, **virtualchain_args ):
"""
synchronize state with the blockchain.
Return True on success
Return False if we're supposed to stop indexing
Abort on error
"""
subdomain_index = server_state['subdoma... | [
"def",
"sync_blockchain",
"(",
"working_dir",
",",
"bt_opts",
",",
"last_block",
",",
"server_state",
",",
"expected_snapshots",
"=",
"{",
"}",
",",
"*",
"*",
"virtualchain_args",
")",
":",
"subdomain_index",
"=",
"server_state",
"[",
"'subdomains'",
"]",
"atlas... | 41.607143 | 28.25 |
def BE8(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''8-bit field, Big endian encoded'''
return UInt8(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) | [
"def",
"BE8",
"(",
"value",
",",
"min_value",
"=",
"None",
",",
"max_value",
"=",
"None",
",",
"fuzzable",
"=",
"True",
",",
"name",
"=",
"None",
",",
"full_range",
"=",
"False",
")",
":",
"return",
"UInt8",
"(",
"value",
",",
"min_value",
"=",
"min_... | 90 | 50 |
def flag_message(current):
"""
Flag inappropriate messages
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'message_key': key,
}
# response:
{
'
'status': 'Created',
'code': 201,
... | [
"def",
"flag_message",
"(",
"current",
")",
":",
"current",
".",
"output",
"=",
"{",
"'status'",
":",
"'Created'",
",",
"'code'",
":",
"201",
"}",
"FlaggedMessage",
".",
"objects",
".",
"get_or_create",
"(",
"user_id",
"=",
"current",
".",
"user_id",
",",
... | 23.227273 | 20.409091 |
def variance(self) -> Optional[float]: #, ddof: int = 0) -> float:
"""Statistical variance of all values entered into histogram.
This number is precise, because we keep the necessary data
separate from bin contents.
Returns
-------
float
"""
# TODO: Add... | [
"def",
"variance",
"(",
"self",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"#, ddof: int = 0) -> float:",
"# TODO: Add DOF",
"# http://stats.stackexchange.com/questions/6534/how-do-i-calculate-a-weighted-standard-deviation-in-excel",
"if",
"self",
".",
"_stats",
":",
"if",
... | 34.631579 | 24.526316 |
def save_csv(self):
""" Dump all results to CSV. """
# Sort results so we can start to see patterns right in the raw CSV.
self.results.sort_values(by=self.column_ids, inplace=True)
# Gotcha: integers seems to be promoted to float64 because of
# reindexation. See: https://pandas.p... | [
"def",
"save_csv",
"(",
"self",
")",
":",
"# Sort results so we can start to see patterns right in the raw CSV.",
"self",
".",
"results",
".",
"sort_values",
"(",
"by",
"=",
"self",
".",
"column_ids",
",",
"inplace",
"=",
"True",
")",
"# Gotcha: integers seems to be pro... | 54.333333 | 19 |
def check_anchor(self, url_data):
"""If URL is valid, parseable and has an anchor, check it.
A warning is logged and True is returned if the anchor is not found.
"""
log.debug(LOG_PLUGIN, "checking anchor %r in %s", url_data.anchor, self.anchors)
enc = lambda anchor: urlutil.url_... | [
"def",
"check_anchor",
"(",
"self",
",",
"url_data",
")",
":",
"log",
".",
"debug",
"(",
"LOG_PLUGIN",
",",
"\"checking anchor %r in %s\"",
",",
"url_data",
".",
"anchor",
",",
"self",
".",
"anchors",
")",
"enc",
"=",
"lambda",
"anchor",
":",
"urlutil",
".... | 50.823529 | 21.941176 |
def get_value_product_unique(self, pos):
"""
Return all products unique relationship with POS's Storage (only salable zones)
"""
qs = ProductUnique.objects.filter(
box__box_structure__zone__storage__in=pos.storage_stock.filter(storage_zones__salable=True),
product... | [
"def",
"get_value_product_unique",
"(",
"self",
",",
"pos",
")",
":",
"qs",
"=",
"ProductUnique",
".",
"objects",
".",
"filter",
"(",
"box__box_structure__zone__storage__in",
"=",
"pos",
".",
"storage_stock",
".",
"filter",
"(",
"storage_zones__salable",
"=",
"Tru... | 39 | 19.666667 |
def update_course(self, course, enterprise_customer, enterprise_context):
"""
Update course metadata of the given course and return updated course.
Arguments:
course (dict): Course Metadata returned by course catalog API
enterprise_customer (EnterpriseCustomer): enterpri... | [
"def",
"update_course",
"(",
"self",
",",
"course",
",",
"enterprise_customer",
",",
"enterprise_context",
")",
":",
"course",
"[",
"'course_runs'",
"]",
"=",
"self",
".",
"update_course_runs",
"(",
"course_runs",
"=",
"course",
".",
"get",
"(",
"'course_runs'",... | 46.259259 | 28.481481 |
def H13(self):
"Information measure of correlation 2."
# An imaginary result has been encountered once in the Matlab
# version. The reason is unclear.
return np.sqrt(1 - np.exp(-2 * (self.hxy2 - self.H9()))) | [
"def",
"H13",
"(",
"self",
")",
":",
"# An imaginary result has been encountered once in the Matlab",
"# version. The reason is unclear.",
"return",
"np",
".",
"sqrt",
"(",
"1",
"-",
"np",
".",
"exp",
"(",
"-",
"2",
"*",
"(",
"self",
".",
"hxy2",
"-",
"self",
... | 47.2 | 17.6 |
def _parse_metadata(response):
'''
Extracts out resource metadata information.
'''
if response is None or response.headers is None:
return None
metadata = _dict()
for key, value in response.headers.items():
if key.lower().startswith('x-ms-meta-'):
metadata[key[10:]]... | [
"def",
"_parse_metadata",
"(",
"response",
")",
":",
"if",
"response",
"is",
"None",
"or",
"response",
".",
"headers",
"is",
"None",
":",
"return",
"None",
"metadata",
"=",
"_dict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"response",
".",
"headers",
... | 24.642857 | 21.214286 |
def _init(self):
"""Create and grid the widgets."""
for label in self.ticklabels:
label.destroy()
self.label.place_forget()
self.ticks = []
self.ticklabels = []
if self._resolution > 0:
nb_steps = round((self.scale.cget('to') - self.scale.cget('fro... | [
"def",
"_init",
"(",
"self",
")",
":",
"for",
"label",
"in",
"self",
".",
"ticklabels",
":",
"label",
".",
"destroy",
"(",
")",
"self",
".",
"label",
".",
"place_forget",
"(",
")",
"self",
".",
"ticks",
"=",
"[",
"]",
"self",
".",
"ticklabels",
"="... | 47.875 | 19.3125 |
def vor_to_am(vor):
r"""
Given a Voronoi tessellation object from Scipy's ``spatial`` module,
converts to a sparse adjacency matrix network representation in COO format.
Parameters
----------
vor : Voronoi Tessellation object
This object is produced by ``scipy.spatial.Voronoi``
Ret... | [
"def",
"vor_to_am",
"(",
"vor",
")",
":",
"# Create adjacency matrix in lil format for quick matrix construction",
"N",
"=",
"vor",
".",
"vertices",
".",
"shape",
"[",
"0",
"]",
"rc",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"for",
"ij",
"in",
"vor",
".",
... | 33.285714 | 17.785714 |
def content():
"""Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 3.2.2
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message
"""
message = m.Message()
... | [
"def",
"content",
"(",
")",
":",
"message",
"=",
"m",
".",
"Message",
"(",
")",
"message",
".",
"add",
"(",
"m",
".",
"Paragraph",
"(",
"tr",
"(",
"'The InaSAFE options dialog is used to control various aspects of '",
"'the InaSAFE analysis and reporting environment. He... | 41.017391 | 22.663768 |
def _condition_as_sql(self, qn, connection):
'''
Return sql for condition.
'''
def escape(value):
if isinstance(value, bool):
value = str(int(value))
if isinstance(value, six.string_types):
# Escape params used with LIKE
... | [
"def",
"_condition_as_sql",
"(",
"self",
",",
"qn",
",",
"connection",
")",
":",
"def",
"escape",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"value",
"=",
"str",
"(",
"int",
"(",
"value",
")",
")",
"if",
"isins... | 34.409091 | 13.318182 |
def keys(self, element=None, mode=None):
r"""
This subclass works exactly like ``keys`` when no arguments are passed,
but optionally accepts an ``element`` and/or a ``mode``, which filters
the output to only the requested keys.
The default behavior is exactly equivalent to the n... | [
"def",
"keys",
"(",
"self",
",",
"element",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"is",
"None",
":",
"return",
"super",
"(",
")",
".",
"keys",
"(",
")",
"element",
"=",
"self",
".",
"_parse_element",
"(",
"element",
"=",
... | 35.057971 | 23.710145 |
def _filter_headers(self):
"""
Add headers designed for filtering messages based on objects.
Returns:
dict: Filter-related headers to be combined with the existing headers
"""
headers = {}
for user in self.usernames:
headers["fedora_messaging_user... | [
"def",
"_filter_headers",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"}",
"for",
"user",
"in",
"self",
".",
"usernames",
":",
"headers",
"[",
"\"fedora_messaging_user_{}\"",
".",
"format",
"(",
"user",
")",
"]",
"=",
"True",
"for",
"package",
"in",
"sel... | 42 | 18.947368 |
def enable_request_loader():
"""
Enable request loader
Optional user loader based on incomin request object. This is useful to
enable on top of default user loader if you want to authenticate API
requests via bearer token header.
:return:
"""
@login_manager.request_loader
def load_us... | [
"def",
"enable_request_loader",
"(",
")",
":",
"@",
"login_manager",
".",
"request_loader",
"def",
"load_user_from_request",
"(",
"request",
")",
":",
"user",
"=",
"None",
"auth",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'Authorization'",
")",
"if",
... | 37.269231 | 16.038462 |
def evaluate(obj, array):
"""Evaluate a ROOT histogram, function, graph, or spline over an array.
Parameters
----------
obj : TH[1|2|3], TF[1|2|3], TFormula, TGraph, TSpline, or string
A ROOT histogram, function, formula, graph, spline, or string. If a
string is specified, a TFormula is... | [
"def",
"evaluate",
"(",
"obj",
",",
"array",
")",
":",
"import",
"ROOT",
"array",
"=",
"np",
".",
"asarray",
"(",
"array",
",",
"dtype",
"=",
"np",
".",
"double",
")",
"if",
"isinstance",
"(",
"obj",
",",
"ROOT",
".",
"TH1",
")",
":",
"if",
"isin... | 39.03876 | 14.217054 |
def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a GET request to url with optional authentication
"""
res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return ... | [
"def",
"rest_get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"url",
",",
... | 48.428571 | 17.571429 |
def list_cache_nodes_full(opts=None, provider=None, base=None):
'''
Return a list of minion data from the cloud cache, rather from the cloud
providers themselves. This is the cloud cache version of list_nodes_full().
'''
if opts is None:
opts = __opts__
if opts.get('update_cachedir', Fal... | [
"def",
"list_cache_nodes_full",
"(",
"opts",
"=",
"None",
",",
"provider",
"=",
"None",
",",
"base",
"=",
"None",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"__opts__",
"if",
"opts",
".",
"get",
"(",
"'update_cachedir'",
",",
"False",
")",... | 41.194444 | 20.638889 |
def render_template(self, template_parameters, template_id):
"""RenderTemplate.
[Preview API]
:param :class:`<TemplateParameters> <azure.devops.v5_1.cix.models.TemplateParameters>` template_parameters:
:param str template_id:
:rtype: :class:`<Template> <azure.devops.v5_1.cix.mode... | [
"def",
"render_template",
"(",
"self",
",",
"template_parameters",
",",
"template_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"template_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'templateId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url... | 53.823529 | 22 |
def _cartesian(arraySizes, out=None):
"""
NAME:
cartesian
PURPOSE:
Generate a cartesian product of input arrays.
INPUT:
arraySizes - list of size of arrays
out - Array to place the cartesian product in.
OUTPUT:
2-D array of shape (product(arraySizes), len(ar... | [
"def",
"_cartesian",
"(",
"arraySizes",
",",
"out",
"=",
"None",
")",
":",
"arrays",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arraySizes",
")",
")",
":",
"arrays",
".",
"append",
"(",
"nu",
".",
"arange",
"(",
"0",
",",
"arrayS... | 31.617647 | 18.5 |
def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path,
verbose):
"""
Runs the program. Takes a list of postcodes or coordinates and
returns various information about them. If using the cli, make
sure to update the bikes database with t... | [
"def",
"run",
"(",
"locations",
",",
"random",
",",
"bikes",
",",
"crime",
",",
"nearby",
",",
"json",
",",
"update_bikes",
",",
"api_server",
",",
"cross_origin",
",",
"host",
",",
"port",
",",
"db_path",
",",
"verbose",
")",
":",
"log_levels",
"=",
"... | 39.925926 | 24.074074 |
def _toState(self, state, *args, **kwargs):
"""
Transition to the next state.
@param state: Name of the next state.
"""
try:
method = getattr(self, '_state_%s' % state)
except AttributeError:
raise ValueError("No such state %r" % state)
l... | [
"def",
"_toState",
"(",
"self",
",",
"state",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"'_state_%s'",
"%",
"state",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
... | 30.5 | 15.071429 |
def pre_save(sender, instance, raw, using, update_fields, **kwargs):
"""https://docs.djangoproject.com/es/1.10/ref/signals/#post-save"""
if raw:
# Return if loading Fixtures
return
try:
with transaction.atomic():
if not should_audit(instance):
return Fals... | [
"def",
"pre_save",
"(",
"sender",
",",
"instance",
",",
"raw",
",",
"using",
",",
"update_fields",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"raw",
":",
"# Return if loading Fixtures",
"return",
"try",
":",
"with",
"transaction",
".",
"atomic",
"(",
")",
... | 42.176471 | 20.455882 |
def _fetchSequence(ac, startIndex=None, endIndex=None):
"""Fetch sequences from NCBI using the eself interface.
An interbase interval may be optionally provided with startIndex and
endIndex. NCBI eself will return just the requested subsequence, which
might greatly reduce payload sizes (especially with... | [
"def",
"_fetchSequence",
"(",
"ac",
",",
"startIndex",
"=",
"None",
",",
"endIndex",
"=",
"None",
")",
":",
"urlFmt",
"=",
"(",
"\"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?\"",
"\"db=nucleotide&id={ac}&rettype=fasta&retmode=text\"",
")",
"if",
"startIndex",
... | 36.162162 | 21.675676 |
def drop_schema(self, schema, cascade=False):
"""Drop specified schema
"""
if schema in self.schemas:
sql = "DROP SCHEMA " + schema
if cascade:
sql = sql + " CASCADE"
self.execute(sql) | [
"def",
"drop_schema",
"(",
"self",
",",
"schema",
",",
"cascade",
"=",
"False",
")",
":",
"if",
"schema",
"in",
"self",
".",
"schemas",
":",
"sql",
"=",
"\"DROP SCHEMA \"",
"+",
"schema",
"if",
"cascade",
":",
"sql",
"=",
"sql",
"+",
"\" CASCADE\"",
"s... | 31.625 | 5.25 |
def change_sample(self, old_samp_name, new_samp_name, new_site_name=None,
new_er_data=None, new_pmag_data=None, replace_data=False):
"""
Find actual data objects for sample and site.
Then call Sample class change method to update sample name and data..
"""
s... | [
"def",
"change_sample",
"(",
"self",
",",
"old_samp_name",
",",
"new_samp_name",
",",
"new_site_name",
"=",
"None",
",",
"new_er_data",
"=",
"None",
",",
"new_pmag_data",
"=",
"None",
",",
"replace_data",
"=",
"False",
")",
":",
"sample",
"=",
"self",
".",
... | 50.75 | 21.6 |
def get(self, index: pd.Index, query: str='', omit_missing_columns: bool=False) -> pd.DataFrame:
"""For the rows in ``index`` get the columns from the simulation's population which this view is configured.
The result may be further filtered by the view's query.
Parameters
----------
... | [
"def",
"get",
"(",
"self",
",",
"index",
":",
"pd",
".",
"Index",
",",
"query",
":",
"str",
"=",
"''",
",",
"omit_missing_columns",
":",
"bool",
"=",
"False",
")",
"->",
"pd",
".",
"DataFrame",
":",
"pop",
"=",
"self",
".",
"manager",
".",
"get_pop... | 40.35 | 26.175 |
def main():
"""Simple test."""
from spyder.utils.qthelpers import qapplication
app = qapplication()
widget = NotebookClient(plugin=None, name='')
widget.show()
widget.set_url('http://google.com')
sys.exit(app.exec_()) | [
"def",
"main",
"(",
")",
":",
"from",
"spyder",
".",
"utils",
".",
"qthelpers",
"import",
"qapplication",
"app",
"=",
"qapplication",
"(",
")",
"widget",
"=",
"NotebookClient",
"(",
"plugin",
"=",
"None",
",",
"name",
"=",
"''",
")",
"widget",
".",
"sh... | 29.75 | 13 |
def dim_lower_extent(self, *args, **kwargs):
"""
Returns the lower extent of the dimensions in args.
.. code-block:: python
t_ex, bl_ex, ch_ex = cube.dim_lower_extent('ntime', 'nbl', 'nchan')
or
.. code-block:: python
t_ex, bl_ex, ch_ex, src_ex = cube... | [
"def",
"dim_lower_extent",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# The lower extent of any integral dimension is 0 by default",
"args",
"=",
"tuple",
"(",
"0",
"if",
"isinstance",
"(",
"a",
",",
"(",
"int",
",",
"np",
".",
"integ... | 30.842105 | 25.157895 |
def data_to_bytes(data, encoding):
"""\
Converts the provided data into bytes. If the data is already a byte
sequence, it will be left unchanged.
This function tries to use the provided `encoding` (if not ``None``)
or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback.
Returns th... | [
"def",
"data_to_bytes",
"(",
"data",
",",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"return",
"data",
",",
"len",
"(",
"data",
")",
",",
"encoding",
"or",
"consts",
".",
"DEFAULT_BYTE_ENCODING",
"data",
"=",
"str",
... | 35.972222 | 15.5 |
def ajax_recalculate_records(self):
"""Recalculate all AR records and dependencies
- samples
- templates
- profiles
- services
- dependecies
XXX: This function has grown too much and needs refactoring!
"""
out = {}
# ... | [
"def",
"ajax_recalculate_records",
"(",
"self",
")",
":",
"out",
"=",
"{",
"}",
"# The sorted records from the request",
"records",
"=",
"self",
".",
"get_records",
"(",
")",
"for",
"n",
",",
"record",
"in",
"enumerate",
"(",
"records",
")",
":",
"# Mapping of... | 45.155963 | 17.655963 |
def _get_stddevs(self, C, rup, shape, stddev_types):
"""
Return standard deviations as defined in p. 971.
"""
weight = self._compute_weight_std(C, rup.mag)
std_intra = weight * C["sd1"] * np.ones(shape)
std_inter = weight * C["sd2"] * np.ones(shape)
... | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"rup",
",",
"shape",
",",
"stddev_types",
")",
":",
"weight",
"=",
"self",
".",
"_compute_weight_std",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"std_intra",
"=",
"weight",
"*",
"C",
"[",
"\"sd1\"",
"]"... | 44 | 14.666667 |
def is_bifurcating(self, include_root=True):
"""
Returns False if there is a polytomy in the tree, including if the tree
is unrooted (basal polytomy), unless you use the include_root=False
argument.
"""
ctn1 = -1 + (2 * len(self))
ctn2 = -2 + (2 * len(self))
... | [
"def",
"is_bifurcating",
"(",
"self",
",",
"include_root",
"=",
"True",
")",
":",
"ctn1",
"=",
"-",
"1",
"+",
"(",
"2",
"*",
"len",
"(",
"self",
")",
")",
"ctn2",
"=",
"-",
"2",
"+",
"(",
"2",
"*",
"len",
"(",
"self",
")",
")",
"if",
"self",
... | 44.538462 | 18.384615 |
def OnPreferences(self, event):
"""Preferences event handler that launches preferences dialog"""
preferences = self.interfaces.get_preferences_from_user()
if preferences:
for key in preferences:
if type(config[key]) in (type(u""), type("")):
conf... | [
"def",
"OnPreferences",
"(",
"self",
",",
"event",
")",
":",
"preferences",
"=",
"self",
".",
"interfaces",
".",
"get_preferences_from_user",
"(",
")",
"if",
"preferences",
":",
"for",
"key",
"in",
"preferences",
":",
"if",
"type",
"(",
"config",
"[",
"key... | 38.071429 | 20.071429 |
def client_sends_binary(self, message, name=None, label=None):
"""Send raw binary `message`.
If client `name` is not given, uses the latest client. Optional message
`label` is shown on logs.
Examples:
| Client sends binary | Hello! |
| Client sends binary | ${some binar... | [
"def",
"client_sends_binary",
"(",
"self",
",",
"message",
",",
"name",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"client",
",",
"name",
"=",
"self",
".",
"_clients",
".",
"get_with_name",
"(",
"name",
")",
"client",
".",
"send",
"(",
"message"... | 37.692308 | 18.923077 |
def generate_orbital_path(self, factor=3., n_points=20, viewup=None, z_shift=None):
"""Genrates an orbital path around the data scene
Parameters
----------
facotr : float
A scaling factor when biulding the orbital extent
n_points : int
number of points o... | [
"def",
"generate_orbital_path",
"(",
"self",
",",
"factor",
"=",
"3.",
",",
"n_points",
"=",
"20",
",",
"viewup",
"=",
"None",
",",
"z_shift",
"=",
"None",
")",
":",
"if",
"viewup",
"is",
"None",
":",
"viewup",
"=",
"rcParams",
"[",
"'camera'",
"]",
... | 34.448276 | 18.103448 |
def list(self, teamId=None, type=None, sortBy=None, max=None,
**request_parameters):
"""List rooms.
By default, lists rooms to which the authenticated user belongs.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It ... | [
"def",
"list",
"(",
"self",
",",
"teamId",
"=",
"None",
",",
"type",
"=",
"None",
",",
"sortBy",
"=",
"None",
",",
"max",
"=",
"None",
",",
"*",
"*",
"request_parameters",
")",
":",
"check_type",
"(",
"teamId",
",",
"basestring",
")",
"check_type",
"... | 41.844828 | 24.517241 |
def _complete_original_tasks(
self,
setName):
"""*mark original tasks as completed if they are marked as complete in the index taskpaper document*
**Key Arguments:**
- ``setName`` -- the name of the sync tag set
"""
self.log.info('starting the ``_comp... | [
"def",
"_complete_original_tasks",
"(",
"self",
",",
"setName",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_complete_original_tasks`` method'",
")",
"if",
"self",
".",
"editorialRootPath",
":",
"taskpaperDocPath",
"=",
"self",
".",
"syncFolder"... | 36.169492 | 19.440678 |
def appliance_device_read_community(self):
"""
Gets the ApplianceDeviceReadCommunity API client.
Returns:
ApplianceDeviceReadCommunity:
"""
if not self.__appliance_device_read_community:
self.__appliance_device_read_community = ApplianceDeviceReadCommunit... | [
"def",
"appliance_device_read_community",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__appliance_device_read_community",
":",
"self",
".",
"__appliance_device_read_community",
"=",
"ApplianceDeviceReadCommunity",
"(",
"self",
".",
"__connection",
")",
"return",
"... | 38.5 | 17.1 |
def _update_param(self):
r"""Update parameters
This method updates the values of the algorthm parameters with the
methods provided
"""
# Update relaxation parameter.
if not isinstance(self._rho_update, type(None)):
self._rho = self._rho_update(self._rho)
... | [
"def",
"_update_param",
"(",
"self",
")",
":",
"# Update relaxation parameter.",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_rho_update",
",",
"type",
"(",
"None",
")",
")",
":",
"self",
".",
"_rho",
"=",
"self",
".",
"_rho_update",
"(",
"self",
".",
... | 32.263158 | 19 |
def frames(self, key=None, orig_order=False):
"""Returns a list of frames in this tag.
If KEY is None, returns all frames in the tag; otherwise returns all frames
whose frameid matches KEY.
If ORIG_ORDER is True, then the frames are returned in their original order.
Othe... | [
"def",
"frames",
"(",
"self",
",",
"key",
"=",
"None",
",",
"orig_order",
"=",
"False",
")",
":",
"if",
"key",
"is",
"not",
"None",
":",
"# If there are multiple frames, then they are already in original order.",
"key",
"=",
"self",
".",
"_normalize_key",
"(",
"... | 39.37931 | 15.551724 |
def _setup(self):
"""
Run setup tasks after initialization
"""
self._populate_local()
try:
self._populate_latest()
except Exception as e:
self.log.exception('Unable to retrieve latest %s version information', self.meta_name)
self._sort() | [
"def",
"_setup",
"(",
"self",
")",
":",
"self",
".",
"_populate_local",
"(",
")",
"try",
":",
"self",
".",
"_populate_latest",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"log",
".",
"exception",
"(",
"'Unable to retrieve latest %s version ... | 30.8 | 15.8 |
def gist_diff():
"""Diff this file with the gist on github"""
remote_file = wget(RAW_GIST)
proc = subprocess.Popen(('diff - %s'%MY_PATH).split(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout, stderr = proc.communicate(remote_file)
retu... | [
"def",
"gist_diff",
"(",
")",
":",
"remote_file",
"=",
"wget",
"(",
"RAW_GIST",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"(",
"'diff - %s'",
"%",
"MY_PATH",
")",
".",
"split",
"(",
")",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"st... | 40.25 | 13 |
def verb_chain_ends(self):
"""The end positions of ``verb_chains`` elements."""
if not self.is_tagged(VERB_CHAINS):
self.tag_verb_chains()
return self.ends(VERB_CHAINS) | [
"def",
"verb_chain_ends",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"VERB_CHAINS",
")",
":",
"self",
".",
"tag_verb_chains",
"(",
")",
"return",
"self",
".",
"ends",
"(",
"VERB_CHAINS",
")"
] | 40 | 5.2 |
def reducer_count(self, key, values):
""" count occurences for each (metro, POI) record """
total = sum(values)
metro, poi = key
# group data by metro areas for final output
yield metro, (total, poi) | [
"def",
"reducer_count",
"(",
"self",
",",
"key",
",",
"values",
")",
":",
"total",
"=",
"sum",
"(",
"values",
")",
"metro",
",",
"poi",
"=",
"key",
"# group data by metro areas for final output ",
"yield",
"metro",
",",
"(",
"total",
",",
"poi",
")"
] | 39.666667 | 9.166667 |
def frequencies(self, sides=None):
"""Return the frequency vector according to :attr:`sides`"""
# use the attribute sides except if a valid sides argument is provided
if sides is None:
sides = self.sides
if sides not in self._sides_choices:
raise errors.SpectrumC... | [
"def",
"frequencies",
"(",
"self",
",",
"sides",
"=",
"None",
")",
":",
"# use the attribute sides except if a valid sides argument is provided",
"if",
"sides",
"is",
"None",
":",
"sides",
"=",
"self",
".",
"sides",
"if",
"sides",
"not",
"in",
"self",
".",
"_sid... | 37.8 | 14.333333 |
def prob(self, pw):
"""
returns the probabiltiy of pw in the model.
P[pw] = n(pw)/n(__total__)
"""
return float(self._T.get(pw, 0)) / self._T[TOTALF_W] | [
"def",
"prob",
"(",
"self",
",",
"pw",
")",
":",
"return",
"float",
"(",
"self",
".",
"_T",
".",
"get",
"(",
"pw",
",",
"0",
")",
")",
"/",
"self",
".",
"_T",
"[",
"TOTALF_W",
"]"
] | 31 | 9.666667 |
def from_string(date_str):
"""
construction from the following string patterns
'%Y-%m-%d'
'%d.%m.%Y'
'%m/%d/%Y'
'%Y%m%d'
:param str date_str:
:return BusinessDate:
"""
if date_str.count('-'):
str_format = '%Y-%m-%d'
eli... | [
"def",
"from_string",
"(",
"date_str",
")",
":",
"if",
"date_str",
".",
"count",
"(",
"'-'",
")",
":",
"str_format",
"=",
"'%Y-%m-%d'",
"elif",
"date_str",
".",
"count",
"(",
"'.'",
")",
":",
"str_format",
"=",
"'%d.%m.%Y'",
"elif",
"date_str",
".",
"cou... | 30.677419 | 15.258065 |
def get_name(self):
"""
Return the name of the field
:rtype: string
"""
if self.name_idx_value == None:
self.name_idx_value = self.CM.get_string(self.name_idx)
return self.name_idx_value | [
"def",
"get_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"name_idx_value",
"==",
"None",
":",
"self",
".",
"name_idx_value",
"=",
"self",
".",
"CM",
".",
"get_string",
"(",
"self",
".",
"name_idx",
")",
"return",
"self",
".",
"name_idx_value"
] | 24.7 | 14.9 |
def redirect_to():
"""302/3XX Redirects to the given URL.
---
tags:
- Redirects
produces:
- text/html
get:
parameters:
- in: query
name: url
type: string
required: true
- in: query
name: status_code
type: int
pos... | [
"def",
"redirect_to",
"(",
")",
":",
"args_dict",
"=",
"request",
".",
"args",
".",
"items",
"(",
")",
"args",
"=",
"CaseInsensitiveDict",
"(",
"args_dict",
")",
"# We need to build the response manually and convert to UTF-8 to prevent",
"# werkzeug from \"fixing\" the URL.... | 24.236111 | 18.916667 |
def hash_vector(self, v, querying=False):
"""
Hashes the vector and returns the binary bucket key as string.
"""
if scipy.sparse.issparse(v):
# If vector is sparse, make sure we have the CSR representation
# of the projection matrix
if self.normals_csr... | [
"def",
"hash_vector",
"(",
"self",
",",
"v",
",",
"querying",
"=",
"False",
")",
":",
"if",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"v",
")",
":",
"# If vector is sparse, make sure we have the CSR representation",
"# of the projection matrix",
"if",
"self",
... | 43.16129 | 20.516129 |
def start(self, func=None):
"""Start the roaster control process.
This function will kick off the processing thread for the Hottop and
register any user-defined callback function. By default, it will not
begin collecting any reading information or saving it. In order to do
that ... | [
"def",
"start",
"(",
"self",
",",
"func",
"=",
"None",
")",
":",
"self",
".",
"_user_callback",
"=",
"func",
"if",
"not",
"self",
".",
"_simulate",
":",
"self",
".",
"_process",
"=",
"ControlProcess",
"(",
"self",
".",
"_conn",
",",
"self",
".",
"_co... | 43.904762 | 22.952381 |
def fo_pct_by_zone(self):
"""
Get the by team face-off win % by zone. Format is
:returns: dict ``{ 'home/away': { 'off/def/neut': % } }``
"""
bz = self.by_zone
return {
t: {
z: bz[t][z]['won']/(1.0*bz[t][z]['total']) if bz[t][z]['t... | [
"def",
"fo_pct_by_zone",
"(",
"self",
")",
":",
"bz",
"=",
"self",
".",
"by_zone",
"return",
"{",
"t",
":",
"{",
"z",
":",
"bz",
"[",
"t",
"]",
"[",
"z",
"]",
"[",
"'won'",
"]",
"/",
"(",
"1.0",
"*",
"bz",
"[",
"t",
"]",
"[",
"z",
"]",
"[... | 29.0625 | 18.5625 |
def parserunstats(self):
"""Parses the XML run statistics file (GenerateFASTQRunStatistics.xml). In some cases, the file is not
available. Equivalent data can be pulled from Basespace.Generate a text file name indexingQC.txt containing
the copied tables from the Indexing QC tab of the run on Ba... | [
"def",
"parserunstats",
"(",
"self",
")",
":",
"# metadata = GenObject()",
"# If the default file GenerateFASTQRunStatistics.xml is present, parse it",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"\"Gen... | 66.982143 | 29.142857 |
def notification_sm_changed(self, model, prop_name, info):
"""Remove references to non-existing state machines"""
for state_machine_id in list(self._expansion_state.keys()):
if state_machine_id not in self.model.state_machines:
del self._expansion_state[state_machine_id] | [
"def",
"notification_sm_changed",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"for",
"state_machine_id",
"in",
"list",
"(",
"self",
".",
"_expansion_state",
".",
"keys",
"(",
")",
")",
":",
"if",
"state_machine_id",
"not",
"in",
"se... | 62.2 | 17.8 |
def formatDuration(self, duration):
"""Format the duration.
This method could be overridden if really needed, as the duration format in gerrit
is an arbitrary string.
:param duration: duration in timedelta
"""
days = duration.days
hours, remainder = divmod(durati... | [
"def",
"formatDuration",
"(",
"self",
",",
"duration",
")",
":",
"days",
"=",
"duration",
".",
"days",
"hours",
",",
"remainder",
"=",
"divmod",
"(",
"duration",
".",
"seconds",
",",
"3600",
")",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"remainder"... | 42.3125 | 18.5625 |
def allocate(self):
"""Initializes libvirt resources."""
disk_path = self.provider_image
self._hypervisor = libvirt.open(
self.configuration.get('hypervisor', 'vbox:///session'))
self._domain = domain_create(self._hypervisor, self.identifier,
... | [
"def",
"allocate",
"(",
"self",
")",
":",
"disk_path",
"=",
"self",
".",
"provider_image",
"self",
".",
"_hypervisor",
"=",
"libvirt",
".",
"open",
"(",
"self",
".",
"configuration",
".",
"get",
"(",
"'hypervisor'",
",",
"'vbox:///session'",
")",
")",
"sel... | 39.777778 | 22 |
def replay_detection_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if the security context can use replay detection for messages protected by
:meth:`get_mic` and :meth:`wrap`. False if replay detection cannot be used.
"""
retu... | [
"def",
"replay_detection_negotiated",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_REPLAY_FLAG",
")",
"and",
"(",
"self",
".",
"established",
"or",
"(",
"self",
".",
"flags",
"&",
"C",
".",
"GSS_C_PROT_READY_FLAG",
")",... | 41.454545 | 21.636364 |
def get_policy_type(self, project, type_id):
"""GetPolicyType.
Retrieve a specific policy type by ID.
:param str project: Project ID or project name
:param str type_id: The policy ID.
:rtype: :class:`<PolicyType> <azure.devops.v5_0.policy.models.PolicyType>`
"""
r... | [
"def",
"get_policy_type",
"(",
"self",
",",
"project",
",",
"type_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'project'"... | 49.588235 | 16.058824 |
def cancel(self, mark_completed_as_cancelled=False):
"""
Cancel the future. If the future has not been started yet, it will never
start running. If the future is already running, it will run until the
worker function exists. The worker function can check if the future has
been cancelled using the :m... | [
"def",
"cancel",
"(",
"self",
",",
"mark_completed_as_cancelled",
"=",
"False",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"not",
"self",
".",
"_completed",
"or",
"mark_completed_as_cancelled",
":",
"self",
".",
"_cancelled",
"=",
"True",
"callbacks",
... | 42.631579 | 24.526316 |
def data_x_range(self):
"""Return a 2-tuple giving the minimum and maximum x-axis
data range.
"""
try:
lower = min([min(self._filter_none(s))
for type, s in self.annotated_data()
if type == 'x'])
upper = max([max(s... | [
"def",
"data_x_range",
"(",
"self",
")",
":",
"try",
":",
"lower",
"=",
"min",
"(",
"[",
"min",
"(",
"self",
".",
"_filter_none",
"(",
"s",
")",
")",
"for",
"type",
",",
"s",
"in",
"self",
".",
"annotated_data",
"(",
")",
"if",
"type",
"==",
"'x'... | 36.857143 | 12 |
def get_clamav_conf(filename):
"""Initialize clamav configuration."""
if os.path.isfile(filename):
return ClamavConfig(filename)
log.warn(LOG_PLUGIN, "No ClamAV config file found at %r.", filename) | [
"def",
"get_clamav_conf",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"return",
"ClamavConfig",
"(",
"filename",
")",
"log",
".",
"warn",
"(",
"LOG_PLUGIN",
",",
"\"No ClamAV config file found at %r.\"",
",",
... | 42.6 | 10.6 |
def processResponse(cls, soapdata, **kw):
"""called by deferred, returns pyobj representing reply.
Parameters and Key Words:
soapdata -- SOAP Data
replytype -- reply type of response
"""
if len(soapdata) == 0:
raise TypeError('Received empty response')
# ... | [
"def",
"processResponse",
"(",
"cls",
",",
"soapdata",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"soapdata",
")",
"==",
"0",
":",
"raise",
"TypeError",
"(",
"'Received empty response'",
")",
"# log.msg(\"_\" * 33, time.ctime(time.time()), ",
"# ... | 34.888889 | 14.722222 |
def groups_unarchive(self, room_id, **kwargs):
"""Unarchives a private group."""
return self.__call_api_post('groups.unarchive', roomId=room_id, kwargs=kwargs) | [
"def",
"groups_unarchive",
"(",
"self",
",",
"room_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'groups.unarchive'",
",",
"roomId",
"=",
"room_id",
",",
"kwargs",
"=",
"kwargs",
")"
] | 57.666667 | 17.333333 |
def execute(self, conn, app="", release_version="", pset_hash="", output_label="",
global_tag='', transaction = False):
"""
returns id for a given application
"""
sql = self.sql
binds = {}
setAnd=False
if not app == "":
sql += " A.APP_NAME=:app_name"
binds[... | [
"def",
"execute",
"(",
"self",
",",
"conn",
",",
"app",
"=",
"\"\"",
",",
"release_version",
"=",
"\"\"",
",",
"pset_hash",
"=",
"\"\"",
",",
"output_label",
"=",
"\"\"",
",",
"global_tag",
"=",
"''",
",",
"transaction",
"=",
"False",
")",
":",
"sql",
... | 36.447368 | 16.868421 |
def create_dvportgroup(portgroup_dict, portgroup_name, dvs,
service_instance=None):
'''
Creates a distributed virtual portgroup.
Note: The ``portgroup_name`` param will override any name already set
in ``portgroup_dict``.
portgroup_dict
Dictionary with the config val... | [
"def",
"create_dvportgroup",
"(",
"portgroup_dict",
",",
"portgroup_name",
",",
"dvs",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Creating portgroup\\'%s\\' in dvs \\'%s\\' '",
"'with dict = %s'",
",",
"portgroup_name",
",",
"dvs",
","... | 38.326087 | 22.413043 |
def _clean_algorithm(data):
"""Clean algorithm keys, handling items that can be specified as lists or single items.
"""
# convert single items to lists
for key in ["variantcaller", "jointcaller", "svcaller"]:
val = tz.get_in(["algorithm", key], data)
if val:
if not isinstance... | [
"def",
"_clean_algorithm",
"(",
"data",
")",
":",
"# convert single items to lists",
"for",
"key",
"in",
"[",
"\"variantcaller\"",
",",
"\"jointcaller\"",
",",
"\"svcaller\"",
"]",
":",
"val",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"algorithm\"",
",",
"key",
"]... | 47.75 | 17.875 |
def _set_clear_mpls_rsvp_statistics(self, v, load=False):
"""
Setter method for clear_mpls_rsvp_statistics, mapped from YANG variable /brocade_mpls_rpc/clear_mpls_rsvp_statistics (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_clear_mpls_rsvp_statistics is consider... | [
"def",
"_set_clear_mpls_rsvp_statistics",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v... | 81.954545 | 39 |
def source_model_info(nodes):
"""
Extract information about NRML/0.5 source models. Returns a table
with TRTs as rows and source classes as columns.
"""
c = collections.Counter()
for node in nodes:
for src_group in node:
trt = src_group['tectonicRegion']
for src i... | [
"def",
"source_model_info",
"(",
"nodes",
")",
":",
"c",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"node",
"in",
"nodes",
":",
"for",
"src_group",
"in",
"node",
":",
"trt",
"=",
"src_group",
"[",
"'tectonicRegion'",
"]",
"for",
"src",
"in",
... | 36.44 | 10.84 |
def add_ms1_quant_from_top3_mzidtsv(proteins, psms, headerfields, protcol):
"""Collects PSMs with the highes precursor quant values,
adds sum of the top 3 of these to a protein table"""
if not protcol:
protcol = mzidtsvdata.HEADER_MASTER_PROT
top_ms1_psms = generate_top_psms(psms, protcol)
f... | [
"def",
"add_ms1_quant_from_top3_mzidtsv",
"(",
"proteins",
",",
"psms",
",",
"headerfields",
",",
"protcol",
")",
":",
"if",
"not",
"protcol",
":",
"protcol",
"=",
"mzidtsvdata",
".",
"HEADER_MASTER_PROT",
"top_ms1_psms",
"=",
"generate_top_psms",
"(",
"psms",
","... | 50.846154 | 15.615385 |
def _get_ref_info_helper(cls, repo, ref_path):
"""Return: (str(sha), str(target_ref_path)) if available, the sha the file at
rela_path points to, or None. target_ref_path is the reference we
point to, or None"""
tokens = None
repodir = _git_dir(repo, ref_path)
try:
... | [
"def",
"_get_ref_info_helper",
"(",
"cls",
",",
"repo",
",",
"ref_path",
")",
":",
"tokens",
"=",
"None",
"repodir",
"=",
"_git_dir",
"(",
"repo",
",",
"ref_path",
")",
"try",
":",
"with",
"open",
"(",
"osp",
".",
"join",
"(",
"repodir",
",",
"ref_path... | 42.864865 | 18.405405 |
def run_maelstrom(infile, genome, outdir, pwmfile=None, plot=True, cluster=False,
score_table=None, count_table=None, methods=None, ncpus=None):
"""Run maelstrom on an input table.
Parameters
----------
infile : str
Filename of input table. Can be either a text-separated tab file o... | [
"def",
"run_maelstrom",
"(",
"infile",
",",
"genome",
",",
"outdir",
",",
"pwmfile",
"=",
"None",
",",
"plot",
"=",
"True",
",",
"cluster",
"=",
"False",
",",
"score_table",
"=",
"None",
",",
"count_table",
"=",
"None",
",",
"methods",
"=",
"None",
","... | 35.653631 | 19.821229 |
def GetService(self, service_name, version=None, server=None):
"""Creates a service client for the given service.
Args:
service_name: A string identifying which AdWords service to create a
service client for.
[optional]
version: A string identifying the AdWords version to connect to... | [
"def",
"GetService",
"(",
"self",
",",
"service_name",
",",
"version",
"=",
"None",
",",
"server",
"=",
"None",
")",
":",
"if",
"not",
"server",
":",
"server",
"=",
"_DEFAULT_ENDPOINT",
"server",
"=",
"server",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"no... | 35.64 | 24.82 |
def glob(cls, files=None):
'''
Glob a pattern or a list of pattern static storage relative(s).
'''
files = files or []
if isinstance(files, str):
files = os.path.normpath(files)
matches = lambda path: matches_patterns(path, [files])
return [pat... | [
"def",
"glob",
"(",
"cls",
",",
"files",
"=",
"None",
")",
":",
"files",
"=",
"files",
"or",
"[",
"]",
"if",
"isinstance",
"(",
"files",
",",
"str",
")",
":",
"files",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"files",
")",
"matches",
"=",
... | 43.9375 | 18.4375 |
def _determine_username(self, ip):
"""SSH in as root and determine the username."""
ssh = subprocess.Popen([
"ssh",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "StrictHostKeyChecking=no",
"root@%s" % ip],
stdin=subprocess.DEVNULL,
s... | [
"def",
"_determine_username",
"(",
"self",
",",
"ip",
")",
":",
"ssh",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"ssh\"",
",",
"\"-o\"",
",",
"\"UserKnownHostsFile=/dev/null\"",
",",
"\"-o\"",
",",
"\"StrictHostKeyChecking=no\"",
",",
"\"root@%s\"",
"%",
"ip"... | 34.809524 | 12.428571 |
def hacking_docstring_summary(physical_line, previous_logical, tokens):
r"""Check multi line docstring summary is separated with empty line.
OpenStack HACKING guide recommendation for docstring:
Docstring should start with a one-line summary, less than 80 characters.
Okay: def foo():\n a = '''\nnot... | [
"def",
"hacking_docstring_summary",
"(",
"physical_line",
",",
"previous_logical",
",",
"tokens",
")",
":",
"docstring",
"=",
"is_docstring",
"(",
"tokens",
",",
"previous_logical",
")",
"if",
"docstring",
":",
"if",
"'\\n'",
"not",
"in",
"docstring",
":",
"# no... | 44.086957 | 16.217391 |
def comment_lines(lines):
"""Comment out the given list of lines and return them. The hash mark will
be inserted before the first non-whitespace character on each line."""
ret = []
for line in lines:
ws_prefix, rest, ignore = RE_LINE_SPLITTER_COMMENT.match(line).groups()
ret.append(ws_p... | [
"def",
"comment_lines",
"(",
"lines",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"ws_prefix",
",",
"rest",
",",
"ignore",
"=",
"RE_LINE_SPLITTER_COMMENT",
".",
"match",
"(",
"line",
")",
".",
"groups",
"(",
")",
"ret",
".",
"a... | 44.5 | 14.875 |
def get_filebase(path, pattern):
"""Get the end of *path* of same length as *pattern*."""
# A pattern can include directories
tail_len = len(pattern.split(os.path.sep))
return os.path.join(*str(path).split(os.path.sep)[-tail_len:]) | [
"def",
"get_filebase",
"(",
"path",
",",
"pattern",
")",
":",
"# A pattern can include directories",
"tail_len",
"=",
"len",
"(",
"pattern",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
... | 48.6 | 8.2 |
def __get_global_options(cmd_line_options, conf_file_options=None):
""" Get all global options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns:... | [
"def",
"__get_global_options",
"(",
"cmd_line_options",
",",
"conf_file_options",
"=",
"None",
")",
":",
"options",
"=",
"{",
"}",
"for",
"option",
"in",
"DEFAULT_OPTIONS",
"[",
"'global'",
"]",
".",
"keys",
"(",
")",
":",
"options",
"[",
"option",
"]",
"=... | 33.238095 | 22.238095 |
def addTextOut(self, text):
"""add black text"""
self._currentColor = self._black
self.addText(text) | [
"def",
"addTextOut",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"_currentColor",
"=",
"self",
".",
"_black",
"self",
".",
"addText",
"(",
"text",
")"
] | 30.25 | 6.75 |
def upgrade(self):
"""Upgrade deployment."""
if not self.is_valid:
raise PolyaxonDeploymentConfigError(
'Deployment type `{}` not supported'.format(self.deployment_type))
if self.is_kubernetes:
self.upgrade_on_kubernetes()
elif self.is_docker_comp... | [
"def",
"upgrade",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_valid",
":",
"raise",
"PolyaxonDeploymentConfigError",
"(",
"'Deployment type `{}` not supported'",
".",
"format",
"(",
"self",
".",
"deployment_type",
")",
")",
"if",
"self",
".",
"is_kubern... | 34.857143 | 12.357143 |
def shutdown(self):
"""Shuts down the scheduler and immediately end all pending callbacks.
"""
# Drop all pending item from the executor. Without this, the executor
# will block until all pending items are complete, which is
# undesirable.
try:
while True:
... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"# Drop all pending item from the executor. Without this, the executor",
"# will block until all pending items are complete, which is",
"# undesirable.",
"try",
":",
"while",
"True",
":",
"self",
".",
"_executor",
".",
"_work_queue",
".... | 37 | 17.583333 |
def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '/**/' | [
"def",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"begin",
",",
"end",
")",
":",
"# Having // dummy comments makes the lines non-empty, so we will not get",
"# unnecessary blank line warnings later in the code.",
"for",
"i",
"in",
"range",
"(",
"begin",
",",
"end",
... | 48.333333 | 15.666667 |
def _from_nested_schema(self, obj, field):
"""Support nested field."""
if isinstance(field.nested, basestring):
nested = get_class(field.nested)
else:
nested = field.nested
name = nested.__name__
outer_name = obj.__class__.__name__
only = field.on... | [
"def",
"_from_nested_schema",
"(",
"self",
",",
"obj",
",",
"field",
")",
":",
"if",
"isinstance",
"(",
"field",
".",
"nested",
",",
"basestring",
")",
":",
"nested",
"=",
"get_class",
"(",
"field",
".",
"nested",
")",
"else",
":",
"nested",
"=",
"fiel... | 34.076923 | 19.326923 |
def delete(self, robj, rw=None, r=None, w=None, dw=None, pr=None, pw=None,
timeout=None):
"""
Delete an object.
"""
# We could detect quorum_controls here but HTTP ignores
# unknown flags/params.
params = {'rw': rw, 'r': r, 'w': w, 'dw': dw, 'pr': pr, 'pw':... | [
"def",
"delete",
"(",
"self",
",",
"robj",
",",
"rw",
"=",
"None",
",",
"r",
"=",
"None",
",",
"w",
"=",
"None",
",",
"dw",
"=",
"None",
",",
"pr",
"=",
"None",
",",
"pw",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"# We could detect q... | 41.318182 | 19.954545 |
def current_time_is_in_interval(start, end):
"""
Determine whether the current time is on the interval [start, end].
"""
interval_start = parse_lms_api_datetime(start or UNIX_MIN_DATE_STRING)
interval_end = parse_lms_api_datetime(end or UNIX_MAX_DATE_STRING)
return interval_start <= timezone.now... | [
"def",
"current_time_is_in_interval",
"(",
"start",
",",
"end",
")",
":",
"interval_start",
"=",
"parse_lms_api_datetime",
"(",
"start",
"or",
"UNIX_MIN_DATE_STRING",
")",
"interval_end",
"=",
"parse_lms_api_datetime",
"(",
"end",
"or",
"UNIX_MAX_DATE_STRING",
")",
"r... | 47.428571 | 16.857143 |
def rn_theory(af, b):
""" R(n) ratio expected from theory for given noise type
alpha = b + 2
"""
# From IEEE1139-2008
# alpha beta ADEV_mu MDEV_mu Rn_mu
# -2 -4 1 1 0 Random Walk FM
# -1 -3 0 0 0 Flicker FM
# ... | [
"def",
"rn_theory",
"(",
"af",
",",
"b",
")",
":",
"# From IEEE1139-2008",
"# alpha beta ADEV_mu MDEV_mu Rn_mu",
"# -2 -4 1 1 0 Random Walk FM",
"# -1 -3 0 0 0 Flicker FM",
"# 0 -2 -1 -1 0 White F... | 33.461538 | 17.346154 |
def data(self, index, role=Qt.DisplayRole):
"""return data depending on index, Qt::ItemDataRole and data type of the column.
Args:
index (QtCore.QModelIndex): Index to define column and row you want to return
role (Qt::ItemDataRole): Define which data you want to return.
... | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"None",
"def",
"convertValue",
"(",
"row",
",",
"col",
",",
"columnDtype",
")",
":",
"val... | 46.511628 | 25.174419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.