text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def muc_request_voice(self):
"""
Request voice (participant role) in the room and wait for the request
to be sent.
The participant role allows occupants to send messages while the room
is in moderated mode.
There is no guarantee that the request will be granted. To dete... | [
"def",
"muc_request_voice",
"(",
"self",
")",
":",
"msg",
"=",
"aioxmpp",
".",
"Message",
"(",
"to",
"=",
"self",
".",
"_mucjid",
",",
"type_",
"=",
"aioxmpp",
".",
"MessageType",
".",
"NORMAL",
")",
"data",
"=",
"aioxmpp",
".",
"forms",
".",
"Data",
... | 28.195122 | 20.97561 |
def create(cls, ip_version, datacenter, bandwidth, vm=None, vlan=None,
ip=None, background=False):
""" Create a public ip and attach it if vm is given. """
return Iface.create(ip_version, datacenter, bandwidth, vlan, vm, ip,
background) | [
"def",
"create",
"(",
"cls",
",",
"ip_version",
",",
"datacenter",
",",
"bandwidth",
",",
"vm",
"=",
"None",
",",
"vlan",
"=",
"None",
",",
"ip",
"=",
"None",
",",
"background",
"=",
"False",
")",
":",
"return",
"Iface",
".",
"create",
"(",
"ip_versi... | 58.2 | 13.8 |
def _field_name_from_uri(self, uri):
"""helper, returns the name of an attribute (without namespace prefix)
"""
# TODO - should use graph API
uri = str(uri)
parts = uri.split('#')
if len(parts) == 1:
return uri.split('/')[-1] or uri
return parts[-1] | [
"def",
"_field_name_from_uri",
"(",
"self",
",",
"uri",
")",
":",
"# TODO - should use graph API",
"uri",
"=",
"str",
"(",
"uri",
")",
"parts",
"=",
"uri",
".",
"split",
"(",
"'#'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"return",
"uri",
... | 34.333333 | 7.555556 |
def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(vers... | [
"def",
"get_release_id",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"version",
":",
"str",
")",
"->",
"bytes",
":",
"validate_package_name",
"(",
"package_name",
")",
"validate_package_version",
"(",
"version",
")",
"self",
".",
"_validate_set_registry",
... | 46.888889 | 14 |
def percentile(arr, percent):
"""
Calculate the given percentile of arr.
"""
arr = sorted(arr)
index = (len(arr) - 1) * percent
floor = math.floor(index)
ceil = math.ceil(index)
if floor == ceil:
return arr[int(index)]
low_value = arr[int(floor)] * (ceil - index)
high_val... | [
"def",
"percentile",
"(",
"arr",
",",
"percent",
")",
":",
"arr",
"=",
"sorted",
"(",
"arr",
")",
"index",
"=",
"(",
"len",
"(",
"arr",
")",
"-",
"1",
")",
"*",
"percent",
"floor",
"=",
"math",
".",
"floor",
"(",
"index",
")",
"ceil",
"=",
"mat... | 29.153846 | 8.692308 |
def parse_genes(transcripts):
"""Parse transcript information and get the gene information from there.
Use hgnc_id as identifier for genes and ensembl transcript id to identify transcripts
Args:
transcripts(iterable(dict))
Returns:
genes (list(dict)): A list with dictionaries th... | [
"def",
"parse_genes",
"(",
"transcripts",
")",
":",
"# Dictionary to group the transcripts by hgnc_id",
"genes_to_transcripts",
"=",
"{",
"}",
"# List with all genes and there transcripts",
"genes",
"=",
"[",
"]",
"hgvs_identifier",
"=",
"None",
"canonical_transcript",
"=",
... | 38.767677 | 19 |
def _intermediary_to_dot(tables, relationships):
""" Returns the dot source representing the database in a string. """
t = '\n'.join(t.to_dot() for t in tables)
r = '\n'.join(r.to_dot() for r in relationships)
return '{}\n{}\n{}\n}}'.format(GRAPH_BEGINNING, t, r) | [
"def",
"_intermediary_to_dot",
"(",
"tables",
",",
"relationships",
")",
":",
"t",
"=",
"'\\n'",
".",
"join",
"(",
"t",
".",
"to_dot",
"(",
")",
"for",
"t",
"in",
"tables",
")",
"r",
"=",
"'\\n'",
".",
"join",
"(",
"r",
".",
"to_dot",
"(",
")",
"... | 55 | 8.4 |
def searchTriples(expnums,ccd):
"""Given a list of exposure numbers, find all the KBOs in that set of exposures"""
import MOPfits,os
import MOPdbaccess
if len(expnums)!=3:
return(-1)
### Some program Constants
proc_file = open("proc-these-files","w")
proc_file.write("# Files... | [
"def",
"searchTriples",
"(",
"expnums",
",",
"ccd",
")",
":",
"import",
"MOPfits",
",",
"os",
"import",
"MOPdbaccess",
"if",
"len",
"(",
"expnums",
")",
"!=",
"3",
":",
"return",
"(",
"-",
"1",
")",
"### Some program Constants",
"proc_file",
"=",
"open",
... | 24.611111 | 21.555556 |
def as_dict(self):
"""
Json-serializable dict representation.
"""
d = {"vasp_version": self.vasp_version,
"has_vasp_completed": True,
"nsites": len(self.final_structure)}
comp = self.final_structure.composition
d["unit_cell_formula"] = comp.as_di... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"\"vasp_version\"",
":",
"self",
".",
"vasp_version",
",",
"\"has_vasp_completed\"",
":",
"True",
",",
"\"nsites\"",
":",
"len",
"(",
"self",
".",
"final_structure",
")",
"}",
"comp",
"=",
"self",
"... | 43.016393 | 16.229508 |
def handle_property(self, obj):
"""Handle a property event.
This function will set an attribute on an object if the event requires
it.
:param obj: A :py:class:`~turberfield.dialogue.model.Model.Property`
object.
:return: The supplied object.
"""
if ... | [
"def",
"handle_property",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"object",
"is",
"not",
"None",
":",
"try",
":",
"setattr",
"(",
"obj",
".",
"object",
",",
"obj",
".",
"attr",
",",
"obj",
".",
"val",
")",
"except",
"AttributeError",
"... | 34.407407 | 19.814815 |
def revoke(self):
"""Revoke the current tokens then empty all stored tokens
This returns nothing since the endpoint return HTTP/200
whatever the result is...
Currently not working with JWT, left here for compatibility.
"""
if not self.refresh_token and not self.ac... | [
"def",
"revoke",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"refresh_token",
"and",
"not",
"self",
".",
"access_token",
":",
"raise",
"AttributeError",
"(",
"'No access/refresh token are defined.'",
")",
"if",
"self",
".",
"refresh_token",
":",
"data",
"... | 34.333333 | 18.851852 |
def routeDefault(self, request, year=None):
"""Route a request to the default calendar view."""
eventsView = request.GET.get('view', self.default_view)
if eventsView in ("L", "list"):
return self.serveUpcoming(request)
elif eventsView in ("W", "weekly"):
return se... | [
"def",
"routeDefault",
"(",
"self",
",",
"request",
",",
"year",
"=",
"None",
")",
":",
"eventsView",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'view'",
",",
"self",
".",
"default_view",
")",
"if",
"eventsView",
"in",
"(",
"\"L\"",
",",
"\"list\"",... | 44.777778 | 8.888889 |
def ols_covariance(self):
""" Creates OLS estimate of the covariance matrix
Returns
----------
The OLS estimate of the covariance matrix
"""
Y = np.array([reg[self.lags:reg.shape[0]] for reg in self.data])
return (1.0/(Y[0].shape[0]))*np.dot(sel... | [
"def",
"ols_covariance",
"(",
"self",
")",
":",
"Y",
"=",
"np",
".",
"array",
"(",
"[",
"reg",
"[",
"self",
".",
"lags",
":",
"reg",
".",
"shape",
"[",
"0",
"]",
"]",
"for",
"reg",
"in",
"self",
".",
"data",
"]",
")",
"return",
"(",
"1.0",
"/... | 35.8 | 24.5 |
def summary_table(pairs, key_header, descr_header="Description", width=78):
"""
List of one-liner strings containing a reStructuredText summary table
for the given pairs ``(name, object)``.
"""
from .lazy_text import rst_table, small_doc
max_width = width - max(len(k) for k, v in pairs)
table = [(k, small... | [
"def",
"summary_table",
"(",
"pairs",
",",
"key_header",
",",
"descr_header",
"=",
"\"Description\"",
",",
"width",
"=",
"78",
")",
":",
"from",
".",
"lazy_text",
"import",
"rst_table",
",",
"small_doc",
"max_width",
"=",
"width",
"-",
"max",
"(",
"len",
"... | 46 | 13.777778 |
def process_mutect_vcf(job, mutect_vcf, work_dir, univ_options):
"""
Process the MuTect vcf for accepted calls.
:param toil.fileStore.FileID mutect_vcf: fsID for a MuTect generated chromosome vcf
:param str work_dir: Working directory
:param dict univ_options: Dict of universal options used by almo... | [
"def",
"process_mutect_vcf",
"(",
"job",
",",
"mutect_vcf",
",",
"work_dir",
",",
"univ_options",
")",
":",
"mutect_vcf",
"=",
"job",
".",
"fileStore",
".",
"readGlobalFile",
"(",
"mutect_vcf",
")",
"with",
"open",
"(",
"mutect_vcf",
",",
"'r'",
")",
"as",
... | 38.363636 | 17.363636 |
def set_error(self, error_shortmsg: str, error_longmsg: str):
""" Set the stage to error and add a message """
LOG.error(f"Update session: error in stage {self._stage.name}: "
f"{error_shortmsg}: {error_longmsg}")
self._error = Value(error_shortmsg, error_longmsg)
self.... | [
"def",
"set_error",
"(",
"self",
",",
"error_shortmsg",
":",
"str",
",",
"error_longmsg",
":",
"str",
")",
":",
"LOG",
".",
"error",
"(",
"f\"Update session: error in stage {self._stage.name}: \"",
"f\"{error_shortmsg}: {error_longmsg}\"",
")",
"self",
".",
"_error",
... | 56.333333 | 15 |
def LogoPlot(sites, datatype, data, plotfile, nperline,
numberevery=10, allowunsorted=False, ydatamax=1.01,
overlay=None, fix_limits={}, fixlongname=False,
overlay_cmap=None, ylimits=None, relativestackheight=1,
custom_cmap='jet', map_metric='kd', noseparator=False,
underlay=Fals... | [
"def",
"LogoPlot",
"(",
"sites",
",",
"datatype",
",",
"data",
",",
"plotfile",
",",
"nperline",
",",
"numberevery",
"=",
"10",
",",
"allowunsorted",
"=",
"False",
",",
"ydatamax",
"=",
"1.01",
",",
"overlay",
"=",
"None",
",",
"fix_limits",
"=",
"{",
... | 53.580737 | 29.8017 |
def locked_put(self, credentials):
"""Write a Credentials to the Django datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity, _ = self.model_class.objects.get_or_create(
**{self.key_name: self.key_value})
setattr(entity, self.p... | [
"def",
"locked_put",
"(",
"self",
",",
"credentials",
")",
":",
"entity",
",",
"_",
"=",
"self",
".",
"model_class",
".",
"objects",
".",
"get_or_create",
"(",
"*",
"*",
"{",
"self",
".",
"key_name",
":",
"self",
".",
"key_value",
"}",
")",
"setattr",
... | 32.545455 | 17.818182 |
def _serialize_scalar_from_string_representation_factory(type_name, types, str_func=str):
"""Builds functions that leverage Python ``str()`` or similar functionality.
Args:
type_name (str): The name of the Ion type.
types (Union[Sequence[type],type]): The Python types to validate for.
s... | [
"def",
"_serialize_scalar_from_string_representation_factory",
"(",
"type_name",
",",
"types",
",",
"str_func",
"=",
"str",
")",
":",
"def",
"serialize",
"(",
"ion_event",
")",
":",
"value",
"=",
"ion_event",
".",
"value",
"validate_scalar_value",
"(",
"value",
",... | 42.470588 | 23.470588 |
def url(self):
""":class:`str`: The URL to the Tibia.com page of the house."""
return self.get_url(self.id, self.world) if self.id and self.world else None | [
"def",
"url",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_url",
"(",
"self",
".",
"id",
",",
"self",
".",
"world",
")",
"if",
"self",
".",
"id",
"and",
"self",
".",
"world",
"else",
"None"
] | 56.333333 | 23.333333 |
def smart_search_pool(self):
""" Perform a smart pool search.
The "smart" search function tries extract a query from
a text string. This query is then passed to the search_pool
function, which performs the search.
"""
search_options = {}
if 'query_i... | [
"def",
"smart_search_pool",
"(",
"self",
")",
":",
"search_options",
"=",
"{",
"}",
"if",
"'query_id'",
"in",
"request",
".",
"json",
":",
"search_options",
"[",
"'query_id'",
"]",
"=",
"request",
".",
"json",
"[",
"'query_id'",
"]",
"if",
"'max_result'",
... | 38.71875 | 22.6875 |
def start(self):
"""Start discovering and listing to connections."""
if self._state == CLOSED:
raise NSQException('producer already closed')
if self.is_running:
self.logger.warn('producer already started')
return
self.logger.debug('starting producer.... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"CLOSED",
":",
"raise",
"NSQException",
"(",
"'producer already closed'",
")",
"if",
"self",
".",
"is_running",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"'producer already started... | 32.6 | 17.6 |
def get_hfs_accounts(netid):
"""
Return a restclients.models.hfs.HfsAccounts object on the given uwnetid
"""
url = ACCOUNTS_URL.format(uwnetid=netid)
response = get_resource(url)
return _object_from_json(response) | [
"def",
"get_hfs_accounts",
"(",
"netid",
")",
":",
"url",
"=",
"ACCOUNTS_URL",
".",
"format",
"(",
"uwnetid",
"=",
"netid",
")",
"response",
"=",
"get_resource",
"(",
"url",
")",
"return",
"_object_from_json",
"(",
"response",
")"
] | 33 | 8.714286 |
def evaluate(dataset):
"""Evaluate model on Dataset for a number of steps."""
with tf.Graph().as_default():
# Get images and labels from the dataset.
images, labels = image_processing.inputs(dataset)
# Number of classes in the Dataset label set plus 1.
# Label 0 is reserved for an (unused) backgrou... | [
"def",
"evaluate",
"(",
"dataset",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"# Get images and labels from the dataset.",
"images",
",",
"labels",
"=",
"image_processing",
".",
"inputs",
"(",
"dataset",
")",
"# Number of... | 38.111111 | 20.277778 |
def coerce_to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
"""
Coerce value to bytes
>>> a = coerce_to_bytes('hello')
>>> assert isinstance(a, bytes)
>>> a = coerce_to_bytes(b'hello')
>>> assert isinstance(a, bytes)
>>> a = coerce_to_bytes(None)
>>> assert a is None
... | [
"def",
"coerce_to_bytes",
"(",
"x",
",",
"charset",
"=",
"sys",
".",
"getdefaultencoding",
"(",
")",
",",
"errors",
"=",
"'strict'",
")",
":",
"PY2",
"=",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
"if",
"PY2",
":",
"# pragma: nocover",
"if"... | 30.909091 | 12.545455 |
def intersect_with(self, polygon):
"""
Calculates the intersection between the polygons in this surface
and other polygon, in the z=0 projection.
This method rely on the ``shapely.Polygon.intersects()`` method.
The way this method is used is intersecting this polyg... | [
"def",
"intersect_with",
"(",
"self",
",",
"polygon",
")",
":",
"intersections",
"=",
"{",
"}",
"for",
"i",
",",
"poly",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"polygon",
".",
"get_shapely",
"(",
")",
".",
"intersects",
"(",
"poly",
".",
"ge... | 45.130435 | 20.086957 |
def resample(self,N,**kwargs):
"""Random resampling of the doublegauss distribution
"""
lovals = self.mu - np.absolute(rand.normal(size=N)*self.siglo)
hivals = self.mu + np.absolute(rand.normal(size=N)*self.sighi)
u = rand.random(size=N)
hi = (u < float(self.sighi)/(self... | [
"def",
"resample",
"(",
"self",
",",
"N",
",",
"*",
"*",
"kwargs",
")",
":",
"lovals",
"=",
"self",
".",
"mu",
"-",
"np",
".",
"absolute",
"(",
"rand",
".",
"normal",
"(",
"size",
"=",
"N",
")",
"*",
"self",
".",
"siglo",
")",
"hivals",
"=",
... | 35.714286 | 18.642857 |
def list_nodes_full(call=None):
'''
Return a list of the instances that are on the provider.
CLI Examples:
.. code-block:: bash
salt-cloud -F my-qingcloud
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --... | [
"def",
"list_nodes_full",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_full function must be called with -f or --function.'",
")",
"zone",
"=",
"_get_specified_zone",
"(",
")",
"params",
... | 24.173913 | 23.652174 |
def levinson_durbin(acdata, order=None):
"""
Solve the Yule-Walker linear system of equations.
They're given by:
.. math::
R . a = r
where :math:`R` is a simmetric Toeplitz matrix where each element are lags
from the given autocorrelation list. :math:`R` and :math:`r` are defined
(Python indexing ... | [
"def",
"levinson_durbin",
"(",
"acdata",
",",
"order",
"=",
"None",
")",
":",
"if",
"order",
"is",
"None",
":",
"order",
"=",
"len",
"(",
"acdata",
")",
"-",
"1",
"elif",
"order",
">=",
"len",
"(",
"acdata",
")",
":",
"acdata",
"=",
"Stream",
"(",
... | 26.235294 | 24.423529 |
def execute_go_cmd(self, cmd, gopath=None, args=None, env=None,
workunit_factory=None, workunit_name=None, workunit_labels=None, **kwargs):
"""Runs a Go command that is optionally targeted to a Go workspace.
If a `workunit_factory` is supplied the command will run in a work unit context.
... | [
"def",
"execute_go_cmd",
"(",
"self",
",",
"cmd",
",",
"gopath",
"=",
"None",
",",
"args",
"=",
"None",
",",
"env",
"=",
"None",
",",
"workunit_factory",
"=",
"None",
",",
"workunit_name",
"=",
"None",
",",
"workunit_labels",
"=",
"None",
",",
"*",
"*"... | 57.363636 | 25.969697 |
def hash(self):
"""Generate a hash value."""
h = hash_pandas_object(self, index=True)
return hashlib.md5(h.values.tobytes()).hexdigest() | [
"def",
"hash",
"(",
"self",
")",
":",
"h",
"=",
"hash_pandas_object",
"(",
"self",
",",
"index",
"=",
"True",
")",
"return",
"hashlib",
".",
"md5",
"(",
"h",
".",
"values",
".",
"tobytes",
"(",
")",
")",
".",
"hexdigest",
"(",
")"
] | 39.25 | 12.75 |
def get_person_from_legacy_format(profile_record):
"""
Given a whole profile, convert it into
zone-file format. In the full profile JSON,
this method operates on the 'data_record' object.
@profile is a dict that contains the legacy profile data
Return a dict with the zone-file formatting.
... | [
"def",
"get_person_from_legacy_format",
"(",
"profile_record",
")",
":",
"if",
"not",
"is_profile_in_legacy_format",
"(",
"profile_record",
")",
":",
"raise",
"ValueError",
"(",
"\"Not a legacy profile\"",
")",
"profile",
"=",
"profile_record",
"try",
":",
"profile",
... | 31.428571 | 19.904762 |
def connect_to_database(host=None, port=None, connect=False, **kwargs):
"""
Explicitly begins a database connection for the application
(if this function is not called, a connection is created when
it is first needed). Takes arguments identical to
pymongo.MongoClient.__init__
@param host: ... | [
"def",
"connect_to_database",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"connect",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"CONNECTION",
".",
"connect",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"conne... | 46.076923 | 18.076923 |
def write_csv_header(mol, csv_writer):
"""
Write the csv header
"""
# create line list where line elements for writing will be stored
line = []
# ID
line.append('id')
# status
line.append('status')
# query labels
queryList = mol.properties.keys()
for queryLabel in queryList... | [
"def",
"write_csv_header",
"(",
"mol",
",",
"csv_writer",
")",
":",
"# create line list where line elements for writing will be stored",
"line",
"=",
"[",
"]",
"# ID",
"line",
".",
"append",
"(",
"'id'",
")",
"# status",
"line",
".",
"append",
"(",
"'status'",
")"... | 18.142857 | 21.333333 |
def load_accounts(extra_path=None, load_user=True):
"""Load the yaml account files
:param load_user:
:return: An `AttrDict`
"""
from os.path import getmtime
try:
accts_file = find_config_file(ACCOUNTS_FILE, extra_path=extra_path, load_user=load_user)
except ConfigurationError:
... | [
"def",
"load_accounts",
"(",
"extra_path",
"=",
"None",
",",
"load_user",
"=",
"True",
")",
":",
"from",
"os",
".",
"path",
"import",
"getmtime",
"try",
":",
"accts_file",
"=",
"find_config_file",
"(",
"ACCOUNTS_FILE",
",",
"extra_path",
"=",
"extra_path",
"... | 24.884615 | 22.461538 |
def delete_message(queue, region, receipthandle, opts=None, user=None):
'''
Delete one or more messages from a queue in a region
queue
The name of the queue to delete messages from
region
Region where SQS queues exists
receipthandle
The ReceiptHandle of the message to dele... | [
"def",
"delete_message",
"(",
"queue",
",",
"region",
",",
"receipthandle",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"queues",
"=",
"list_queues",
"(",
"region",
",",
"opts",
",",
"user",
")",
"url_map",
"=",
"_parse_queue_list",
"("... | 26.973684 | 26.447368 |
def dailysummary(start_date=None, end_date=None, return_format=None):
"""Returns daily summary totals of targets, attacks and sources. Limit to
30 days at a time. (Query 2002-01-01 to present)
In the return data:
Sources: Distinct source IP addresses the packets originate from.
Targets: Distinct t... | [
"def",
"dailysummary",
"(",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'dailysummary'",
"if",
"not",
"start_date",
":",
"# default today",
"start_date",
"=",
"datetime",
".",
"datetime",
... | 33.931034 | 20.068966 |
def plugin_info(self):
"""
Property for accessing :class:`PluginInfoManager` instance, which is used to manage pipeline configurations.
:rtype: yagocd.resources.plugin_info.PluginInfoManager
"""
if self._plugin_info_manager is None:
self._plugin_info_manager = Plugin... | [
"def",
"plugin_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"_plugin_info_manager",
"is",
"None",
":",
"self",
".",
"_plugin_info_manager",
"=",
"PluginInfoManager",
"(",
"session",
"=",
"self",
".",
"_session",
")",
"return",
"self",
".",
"_plugin_info_ma... | 43 | 22.333333 |
def read_string(self, len):
"""Reads a string of a given length from the packet"""
format = '!' + str(len) + 's'
length = struct.calcsize(format)
info = struct.unpack(format,
self.data[self.offset:self.offset + length])
self.offset += length
return info[0] | [
"def",
"read_string",
"(",
"self",
",",
"len",
")",
":",
"format",
"=",
"'!'",
"+",
"str",
"(",
"len",
")",
"+",
"'s'",
"length",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"info",
"=",
"struct",
".",
"unpack",
"(",
"format",
",",
"self",
... | 39.125 | 8.625 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'tooling') and self.tooling is not None:
_dict['tooling'] = self.tooling._to_dict()
if hasattr(self, 'disambiguation') and self.disambiguation is not None:
_dic... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'tooling'",
")",
"and",
"self",
".",
"tooling",
"is",
"not",
"None",
":",
"_dict",
"[",
"'tooling'",
"]",
"=",
"self",
".",
"tooling",
".",
"_to_d... | 47.416667 | 22.666667 |
def get_associated_profiles(self):
"""
Gets the URIs of profiles which are using an Ethernet network.
Args:
id_or_uri: Can be either the logical interconnect group id or the logical interconnect group uri
Returns:
list: URIs of the associated profiles.
... | [
"def",
"get_associated_profiles",
"(",
"self",
")",
":",
"uri",
"=",
"\"{}/associatedProfiles\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"'uri'",
"]",
")",
"return",
"self",
".",
"_helper",
".",
"do_get",
"(",
"uri",
")"
] | 31.846154 | 23.692308 |
def downloadSessionImages(server, filename=None, height=150, width=150,
opacity=100, saturation=100): # pragma: no cover
""" Helper to download a bif image or thumb.url from plex.server.sessions.
Parameters:
filename (str): default to None,
height (int): Heig... | [
"def",
"downloadSessionImages",
"(",
"server",
",",
"filename",
"=",
"None",
",",
"height",
"=",
"150",
",",
"width",
"=",
"150",
",",
"opacity",
"=",
"100",
",",
"saturation",
"=",
"100",
")",
":",
"# pragma: no cover",
"info",
"=",
"{",
"}",
"for",
"... | 45.83871 | 22.516129 |
def convert_flux(wavelengths, fluxes, out_flux_unit, **kwargs):
"""Perform conversion for :ref:`supported flux units <synphot-flux-units>`.
Parameters
----------
wavelengths : array-like or `~astropy.units.quantity.Quantity`
Wavelength values. If not a Quantity, assumed to be in
Angstro... | [
"def",
"convert_flux",
"(",
"wavelengths",
",",
"fluxes",
",",
"out_flux_unit",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"fluxes",
",",
"u",
".",
"Quantity",
")",
":",
"fluxes",
"=",
"fluxes",
"*",
"PHOTLAM",
"out_flux_unit",
"=... | 31.542169 | 19.301205 |
def parse_search_url(url):
"""Parses a search URL."""
config = {}
url = urlparse.urlparse(url)
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
if url.scheme in SEARCH_SCHEMES:
config["ENGINE"] = SEARCH_SCHEMES[url.scheme]
if url.scheme in USES_URL:
... | [
"def",
"parse_search_url",
"(",
"url",
")",
":",
"config",
"=",
"{",
"}",
"url",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"# Remove query strings.",
"path",
"=",
"url",
".",
"path",
"[",
"1",
":",
"]",
"path",
"=",
"path",
".",
"split",
"("... | 21.731707 | 21.829268 |
def from_ic50(ic50, max_ic50=50000.0):
"""
Convert ic50s to regression targets in the range [0.0, 1.0].
Parameters
----------
ic50 : numpy.array of float
Returns
-------
numpy.array of float
"""
x = 1.0 - (numpy.log(ic50) / numpy.log(max_ic50))
return numpy.minimum(
... | [
"def",
"from_ic50",
"(",
"ic50",
",",
"max_ic50",
"=",
"50000.0",
")",
":",
"x",
"=",
"1.0",
"-",
"(",
"numpy",
".",
"log",
"(",
"ic50",
")",
"/",
"numpy",
".",
"log",
"(",
"max_ic50",
")",
")",
"return",
"numpy",
".",
"minimum",
"(",
"1.0",
",",... | 20.294118 | 20.176471 |
def get_help_width():
"""Returns the integer width of help lines that is used in TextWrap."""
if not sys.stdout.isatty() or termios is None or fcntl is None:
return _DEFAULT_HELP_WIDTH
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
# Emacs mo... | [
"def",
"get_help_width",
"(",
")",
":",
"if",
"not",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
"or",
"termios",
"is",
"None",
"or",
"fcntl",
"is",
"None",
":",
"return",
"_DEFAULT_HELP_WIDTH",
"try",
":",
"data",
"=",
"fcntl",
".",
"ioctl",
"(",
... | 40.25 | 17.1875 |
def declare_vars(self, d):
"""Declare the variables defined in the dictionary d."""
for k, v in d.items():
self.declare_var(k, v) | [
"def",
"declare_vars",
"(",
"self",
",",
"d",
")",
":",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"self",
".",
"declare_var",
"(",
"k",
",",
"v",
")"
] | 38.5 | 7.5 |
def read_bits(self, num):
"""Read ``num`` number of bits from the stream
:num: number of bits to read
:returns: a list of ``num`` bits, or an empty list if EOF has been reached
"""
if num > len(self._bits):
needed = num - len(self._bits)
num_bytes = int(m... | [
"def",
"read_bits",
"(",
"self",
",",
"num",
")",
":",
"if",
"num",
">",
"len",
"(",
"self",
".",
"_bits",
")",
":",
"needed",
"=",
"num",
"-",
"len",
"(",
"self",
".",
"_bits",
")",
"num_bytes",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"need... | 31.894737 | 17.315789 |
def expand_brackets(s):
"""Remove whitespace and expand all brackets."""
s = ''.join(s.split())
while True:
start = s.find('(')
if start == -1:
break
count = 1 # Number of hanging open brackets
p = start + 1
while p < len(s):
if s[p] == '(':
... | [
"def",
"expand_brackets",
"(",
"s",
")",
":",
"s",
"=",
"''",
".",
"join",
"(",
"s",
".",
"split",
"(",
")",
")",
"while",
"True",
":",
"start",
"=",
"s",
".",
"find",
"(",
"'('",
")",
"if",
"start",
"==",
"-",
"1",
":",
"break",
"count",
"="... | 33.366667 | 18.366667 |
def source_uris(self):
"""The fully-qualified URIs that point to your data in Google Cloud Storage.
Each URI can contain one '*' wildcard character and it must come after the 'bucket' name."""
return [x.path for x in luigi.task.flatten(self.input())] | [
"def",
"source_uris",
"(",
"self",
")",
":",
"return",
"[",
"x",
".",
"path",
"for",
"x",
"in",
"luigi",
".",
"task",
".",
"flatten",
"(",
"self",
".",
"input",
"(",
")",
")",
"]"
] | 54.2 | 16.6 |
def __IsInitialized(self):
""" Returns true if IAM user initialization has completed. """
is_initialized = False
iam_id = self.GetAccessKeyId()
if iam_id:
if core.CirrusAccessIdMetadata(self.s3, iam_id).IsInitialized():
is_initialized = True
return is_initialized | [
"def",
"__IsInitialized",
"(",
"self",
")",
":",
"is_initialized",
"=",
"False",
"iam_id",
"=",
"self",
".",
"GetAccessKeyId",
"(",
")",
"if",
"iam_id",
":",
"if",
"core",
".",
"CirrusAccessIdMetadata",
"(",
"self",
".",
"s3",
",",
"iam_id",
")",
".",
"I... | 37.25 | 13.75 |
def delete(id):
"""Delete a post.
Ensures that the post exists and that the logged in user is the
author of the post.
"""
post = get_post(id)
db.session.delete(post)
db.session.commit()
return redirect(url_for("blog.index")) | [
"def",
"delete",
"(",
"id",
")",
":",
"post",
"=",
"get_post",
"(",
"id",
")",
"db",
".",
"session",
".",
"delete",
"(",
"post",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"\"blog.index\"",
")",
"... | 24.8 | 15.8 |
def read(cls, proto):
""" capnp deserialization method for the anomaly likelihood object
:param proto: (Object) capnp proto object specified in
nupic.regions.anomaly_likelihood.capnp
:returns: (Object) the deserialized AnomalyLikelihood object
"""
# pylint: disable=W0212
... | [
"def",
"read",
"(",
"cls",
",",
"proto",
")",
":",
"# pylint: disable=W0212",
"anomalyLikelihood",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"anomalyLikelihood",
".",
"_iteration",
"=",
"proto",
".",
"iteration",
"anomalyLikelihood",
".",
"_historicalScores"... | 51.363636 | 28.295455 |
def build_specfile_sections(spec):
""" Builds the sections of a rpm specfile.
"""
str = ""
mandatory_sections = {
'DESCRIPTION' : '\n%%description\n%s\n\n', }
str = str + SimpleTagCompiler(mandatory_sections).compile( spec )
optional_sections = {
'DESCRIPTION_' : '%%de... | [
"def",
"build_specfile_sections",
"(",
"spec",
")",
":",
"str",
"=",
"\"\"",
"mandatory_sections",
"=",
"{",
"'DESCRIPTION'",
":",
"'\\n%%description\\n%s\\n\\n'",
",",
"}",
"str",
"=",
"str",
"+",
"SimpleTagCompiler",
"(",
"mandatory_sections",
")",
".",
"compile... | 39.837209 | 25.906977 |
def fetch(elastic, backend, limit=None, search_after_value=None, scroll=True):
""" Fetch the items from raw or enriched index """
logging.debug("Creating a elastic items generator.")
elastic_scroll_id = None
search_after = search_after_value
while True:
if scroll:
rjson = get_... | [
"def",
"fetch",
"(",
"elastic",
",",
"backend",
",",
"limit",
"=",
"None",
",",
"search_after_value",
"=",
"None",
",",
"scroll",
"=",
"True",
")",
":",
"logging",
".",
"debug",
"(",
"\"Creating a elastic items generator.\"",
")",
"elastic_scroll_id",
"=",
"No... | 31.088235 | 19.970588 |
def _systemctl_cmd(action, name=None, systemd_scope=False, no_block=False,
root=None):
'''
Build a systemctl command line. Treat unit names without one
of the valid suffixes as a service.
'''
ret = []
if systemd_scope \
and salt.utils.systemd.has_scope(__context__)... | [
"def",
"_systemctl_cmd",
"(",
"action",
",",
"name",
"=",
"None",
",",
"systemd_scope",
"=",
"False",
",",
"no_block",
"=",
"False",
",",
"root",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"systemd_scope",
"and",
"salt",
".",
"utils",
".",
"s... | 32.708333 | 16.875 |
def logger(function):
"""Decorate passed in function and log message to module logger."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrap function."""
sep = kwargs.get('sep', ' ')
end = kwargs.get('end', '') # do not add newline by default
out = sep.join([re... | [
"def",
"logger",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrap function.\"\"\"",
"sep",
"=",
"kwargs",
".",
"get",
"(",
"'sep'",
",",
... | 36.75 | 10.666667 |
def _find_types(pkgs):
'''Form a package names list, find prefixes of packages types.'''
return sorted({pkg.split(':', 1)[0] for pkg in pkgs
if len(pkg.split(':', 1)) == 2}) | [
"def",
"_find_types",
"(",
"pkgs",
")",
":",
"return",
"sorted",
"(",
"{",
"pkg",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
"for",
"pkg",
"in",
"pkgs",
"if",
"len",
"(",
"pkg",
".",
"split",
"(",
"':'",
",",
"1",
")",
")",
"==",... | 49.25 | 18.25 |
def push(self, obj):
"""Prepend an element to the beginnging of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list.
"""
if isinstance(obj, str):
... | [
"def",
"push",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
"KQMLToken",
"(",
"obj",
")",
"self",
".",
"data",
".",
"insert",
"(",
"0",
",",
"obj",
")"
] | 30.416667 | 14 |
def find_connection_file(filename, profile=None):
"""find a connection file, and return its absolute path.
The current working directory and the profile's security
directory will be searched for the file if it is not given by
absolute path.
If profile is unspecified, then the current runni... | [
"def",
"find_connection_file",
"(",
"filename",
",",
"profile",
"=",
"None",
")",
":",
"from",
"IPython",
".",
"core",
".",
"application",
"import",
"BaseIPythonApplication",
"as",
"IPApp",
"try",
":",
"# quick check for absolute path, before going through logic",
"retu... | 34.558824 | 22.191176 |
def create_masked_lm_predictions(tokens, masked_lm_prob,
max_predictions_per_seq, vocab_words, rng):
"""Creates the predictions for the masked LM objective."""
cand_indexes = []
for (i, token) in enumerate(tokens):
if token in ['[CLS]', '[SEP]']:
continu... | [
"def",
"create_masked_lm_predictions",
"(",
"tokens",
",",
"masked_lm_prob",
",",
"max_predictions_per_seq",
",",
"vocab_words",
",",
"rng",
")",
":",
"cand_indexes",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"token",
")",
"in",
"enumerate",
"(",
"tokens",
")",
"... | 31.5 | 19.269231 |
def load(self, schema_file: Union[str, TextIO], schema_location: Optional[str]=None) -> ShExJ.Schema:
""" Load a ShEx Schema from schema_location
:param schema_file: name or file-like object to deserialize
:param schema_location: URL or file name of schema. Used to create the base_location
... | [
"def",
"load",
"(",
"self",
",",
"schema_file",
":",
"Union",
"[",
"str",
",",
"TextIO",
"]",
",",
"schema_location",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"ShExJ",
".",
"Schema",
":",
"if",
"isinstance",
"(",
"schema_file",
",",
... | 43.85 | 20.55 |
def flag_is_related(self, flag):
'''
Checks for relationship between a flag and this block.
Returns:
True if the flag is related to this block.
'''
same_worksheet = flag.worksheet == self.worksheet
if isinstance(flag.location, (tuple, list)):
retu... | [
"def",
"flag_is_related",
"(",
"self",
",",
"flag",
")",
":",
"same_worksheet",
"=",
"flag",
".",
"worksheet",
"==",
"self",
".",
"worksheet",
"if",
"isinstance",
"(",
"flag",
".",
"location",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"(... | 40 | 24.142857 |
def mixin(self):
"""
Add your own custom functions to the Underscore object, ensuring that
they're correctly added to the OOP wrapper as well.
"""
methods = self.obj
for i, k in enumerate(methods):
setattr(underscore, k, methods[k])
self.makeStatic()
... | [
"def",
"mixin",
"(",
"self",
")",
":",
"methods",
"=",
"self",
".",
"obj",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"methods",
")",
":",
"setattr",
"(",
"underscore",
",",
"k",
",",
"methods",
"[",
"k",
"]",
")",
"self",
".",
"makeStatic",
"... | 31.363636 | 14.636364 |
def _check_rot_sym(self, axis):
"""
Determines the rotational symmetry about supplied axis. Used only for
symmetric top molecules which has possible rotational symmetry
operations > 2.
"""
min_set = self._get_smallest_set_not_on_axis(axis)
max_sym = len(min_set)
... | [
"def",
"_check_rot_sym",
"(",
"self",
",",
"axis",
")",
":",
"min_set",
"=",
"self",
".",
"_get_smallest_set_not_on_axis",
"(",
"axis",
")",
"max_sym",
"=",
"len",
"(",
"min_set",
")",
"for",
"i",
"in",
"range",
"(",
"max_sym",
",",
"0",
",",
"-",
"1",... | 37.166667 | 13.5 |
def create(self, name, *args, **kwargs):
"""
Need to wrap the default call to handle exceptions.
"""
try:
return super(ImageMemberManager, self).create(name, *args, **kwargs)
except Exception as e:
if e.http_status == 403:
raise exc.Unshara... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"super",
"(",
"ImageMemberManager",
",",
"self",
")",
".",
"create",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"... | 35.818182 | 16.363636 |
def shards(self, add_shard=False):
"""Get a list of shards belonging to this instance.
:param bool add_shard: A boolean indicating whether to add a new shard to the specified
instance.
"""
url = self._service_url + 'shards/'
if add_shard:
response = reque... | [
"def",
"shards",
"(",
"self",
",",
"add_shard",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"_service_url",
"+",
"'shards/'",
"if",
"add_shard",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"*",
"*",
"self",
".",
"_instances",
... | 38 | 23.538462 |
def close(self):
"""Close the socket"""
if self.is_open():
fd = self._fd
self._fd = -1
if self.uses_nanoconfig:
wrapper.nc_close(fd)
else:
_nn_check_positive_rtn(wrapper.nn_close(fd)) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_open",
"(",
")",
":",
"fd",
"=",
"self",
".",
"_fd",
"self",
".",
"_fd",
"=",
"-",
"1",
"if",
"self",
".",
"uses_nanoconfig",
":",
"wrapper",
".",
"nc_close",
"(",
"fd",
")",
"else",
... | 30.111111 | 13.222222 |
def copy(self, **replacements):
"""Returns a clone of this M2Coordinate with the given replacements kwargs overlaid."""
cls = type(self)
kwargs = {'org': self.org, 'name': self.name, 'ext': self.ext, 'classifier': self.classifier, 'rev': self.rev}
for key, val in replacements.items():
kwargs[key] ... | [
"def",
"copy",
"(",
"self",
",",
"*",
"*",
"replacements",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"kwargs",
"=",
"{",
"'org'",
":",
"self",
".",
"org",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'ext'",
":",
"self",
".",
"ext",
","... | 49.142857 | 19.571429 |
def create_token(cls, obj_id, data, expires_at=None):
"""Create the secret link token."""
if expires_at:
s = TimedSecretLinkSerializer(expires_at=expires_at)
else:
s = SecretLinkSerializer()
return s.create_token(obj_id, data) | [
"def",
"create_token",
"(",
"cls",
",",
"obj_id",
",",
"data",
",",
"expires_at",
"=",
"None",
")",
":",
"if",
"expires_at",
":",
"s",
"=",
"TimedSecretLinkSerializer",
"(",
"expires_at",
"=",
"expires_at",
")",
"else",
":",
"s",
"=",
"SecretLinkSerializer",... | 34.5 | 15.875 |
def rel_links(cls, page):
"""return rel= links that should be scraped, skipping obviously data links."""
for match in cls.REL_RE.finditer(page):
href, rel = match.group(0), match.group(1)
if rel not in cls.REL_TYPES:
continue
href_match = cls.HREF_RE.search(href)
if href_match:
... | [
"def",
"rel_links",
"(",
"cls",
",",
"page",
")",
":",
"for",
"match",
"in",
"cls",
".",
"REL_RE",
".",
"finditer",
"(",
"page",
")",
":",
"href",
",",
"rel",
"=",
"match",
".",
"group",
"(",
"0",
")",
",",
"match",
".",
"group",
"(",
"1",
")",... | 39.461538 | 13.615385 |
def camelcase_search_options(self, options):
"""change all underscored variants back to what the API is expecting"""
new_options = {}
for key in options:
value = options[key]
new_key = SEARCH_OPTIONS_DICT.get(key, key)
if new_key == 'sort':
val... | [
"def",
"camelcase_search_options",
"(",
"self",
",",
"options",
")",
":",
"new_options",
"=",
"{",
"}",
"for",
"key",
"in",
"options",
":",
"value",
"=",
"options",
"[",
"key",
"]",
"new_key",
"=",
"SEARCH_OPTIONS_DICT",
".",
"get",
"(",
"key",
",",
"key... | 44.071429 | 9.571429 |
def box(text, width=100, height=3, corner="+", horizontal="-", vertical="|"):
"""Return a ascii box, with your text center-aligned.
Usage Example::
>>> StringTemplate.box("Hello world!", 20, 5)
+------------------+
| |
| ... | [
"def",
"box",
"(",
"text",
",",
"width",
"=",
"100",
",",
"height",
"=",
"3",
",",
"corner",
"=",
"\"+\"",
",",
"horizontal",
"=",
"\"-\"",
",",
"vertical",
"=",
"\"|\"",
")",
":",
"if",
"width",
"<=",
"len",
"(",
"text",
")",
"-",
"4",
":",
"p... | 38.3 | 18.233333 |
def get_display(unicode_or_str, encoding='utf-8', upper_is_rtl=False,
base_dir=None, debug=False):
"""Accepts unicode or string. In case it's a string, `encoding`
is needed as it works on unicode ones (default:"utf-8").
Set `upper_is_rtl` to True to treat upper case chars as strong 'R'
... | [
"def",
"get_display",
"(",
"unicode_or_str",
",",
"encoding",
"=",
"'utf-8'",
",",
"upper_is_rtl",
"=",
"False",
",",
"base_dir",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"storage",
"=",
"get_empty_storage",
"(",
")",
"# utf-8 ? we need unicode",
"if... | 30.62 | 20.26 |
def _update_subplot(self, subplot, spec):
"""
Updates existing subplots when the subplot has been assigned
to plot an element that is not an exact match to the object
it was initially assigned.
"""
# See if the precise spec has already been assigned a cyclic
# in... | [
"def",
"_update_subplot",
"(",
"self",
",",
"subplot",
",",
"spec",
")",
":",
"# See if the precise spec has already been assigned a cyclic",
"# index otherwise generate a new one",
"if",
"spec",
"in",
"self",
".",
"cyclic_index_lookup",
":",
"cyclic_index",
"=",
"self",
... | 41.318182 | 14.954545 |
def get_choice(cls, value):
"""
Return the underlying :class:`ChoiceItem` for a given value.
"""
attribute_for_value = cls.attributes[value]
return cls._fields[attribute_for_value] | [
"def",
"get_choice",
"(",
"cls",
",",
"value",
")",
":",
"attribute_for_value",
"=",
"cls",
".",
"attributes",
"[",
"value",
"]",
"return",
"cls",
".",
"_fields",
"[",
"attribute_for_value",
"]"
] | 35.833333 | 9.833333 |
def _format_fields(self, fields, title_width=12):
"""Formats a list of fields for display.
Parameters
----------
fields : list
A list of 2-tuples: (field_title, field_content)
title_width : int
How many characters to pad titles to. Default 12.
"""
... | [
"def",
"_format_fields",
"(",
"self",
",",
"fields",
",",
"title_width",
"=",
"12",
")",
":",
"out",
"=",
"[",
"]",
"header",
"=",
"self",
".",
"__head",
"for",
"title",
",",
"content",
"in",
"fields",
":",
"if",
"len",
"(",
"content",
".",
"splitlin... | 33.157895 | 14.473684 |
def validate_key(self, activation_key):
"""
Verify that the activation key is valid and within the
permitted activation time window, returning the username if
valid or ``None`` if not.
"""
try:
username = signing.loads(
activation_key,
... | [
"def",
"validate_key",
"(",
"self",
",",
"activation_key",
")",
":",
"try",
":",
"username",
"=",
"signing",
".",
"loads",
"(",
"activation_key",
",",
"salt",
"=",
"self",
".",
"key_salt",
",",
"max_age",
"=",
"conf",
".",
"get",
"(",
"'ACCOUNT_ACTIVATION_... | 33.388889 | 15.166667 |
def run(self, *args):
"""Remove unique identities or identities from the registry.
By default, it removes the unique identity identified by <identifier>.
To remove an identity, set <identity> parameter.
"""
params = self.parser.parse_args(args)
identifier = params.ident... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"identifier",
"=",
"params",
".",
"identifier",
"identity",
"=",
"params",
".",
"identity",
"code",
"=",
"self",
".",
"r... | 29.857143 | 19.642857 |
def custom_prefix_lax(instance):
"""Ensure custom content follows lenient naming style conventions
for forward-compatibility.
"""
for error in chain(custom_object_prefix_lax(instance),
custom_property_prefix_lax(instance),
custom_observable_object_prefix_lax... | [
"def",
"custom_prefix_lax",
"(",
"instance",
")",
":",
"for",
"error",
"in",
"chain",
"(",
"custom_object_prefix_lax",
"(",
"instance",
")",
",",
"custom_property_prefix_lax",
"(",
"instance",
")",
",",
"custom_observable_object_prefix_lax",
"(",
"instance",
")",
",... | 48.6 | 16.8 |
def reboot(vm_):
'''
Reboot a domain via ACPI request
CLI Example:
.. code-block:: bash
salt '*' virt.reboot <vm name>
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if vm_uuid is False:
return False
try:
... | [
"def",
"reboot",
"(",
"vm_",
")",
":",
"with",
"_get_xapi_session",
"(",
")",
"as",
"xapi",
":",
"vm_uuid",
"=",
"_get_label_uuid",
"(",
"xapi",
",",
"'VM'",
",",
"vm_",
")",
"if",
"vm_uuid",
"is",
"False",
":",
"return",
"False",
"try",
":",
"xapi",
... | 21.473684 | 19.684211 |
def get_barcode_umis(read, cell_barcode=False):
''' extract the umi +/- cell barcode from the read name where the barcodes
were extracted using umis'''
umi, cell = None, None
try:
read_name_elements = read.qname.split(":")
for element in read_name_elements:
if element.starts... | [
"def",
"get_barcode_umis",
"(",
"read",
",",
"cell_barcode",
"=",
"False",
")",
":",
"umi",
",",
"cell",
"=",
"None",
",",
"None",
"try",
":",
"read_name_elements",
"=",
"read",
".",
"qname",
".",
"split",
"(",
"\":\"",
")",
"for",
"element",
"in",
"re... | 32.619048 | 20.238095 |
def request_cert(domain, master, ticket, port):
'''
Request CA cert from master icinga2 node.
Returns::
icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \
/etc/icing... | [
"def",
"request_cert",
"(",
"domain",
",",
"master",
",",
"ticket",
",",
"port",
")",
":",
"result",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"[",
"\"icinga2\"",
",",
"\"pki\"",
",",
"\"request\"",
",",
"\"--host\"",
",",
"master",
",",
"\"--port\"... | 50.666667 | 50.222222 |
def _state_stopped(self):
"""
The service is not running.
This is the initial state, and the state after L{stopService} was
called. To get out of this state, call L{startService}. If there is a
current connection, we disconnect.
"""
if self._reconnectDelayedCall:... | [
"def",
"_state_stopped",
"(",
"self",
")",
":",
"if",
"self",
".",
"_reconnectDelayedCall",
":",
"self",
".",
"_reconnectDelayedCall",
".",
"cancel",
"(",
")",
"self",
".",
"_reconnectDelayedCall",
"=",
"None",
"self",
".",
"loseConnection",
"(",
")"
] | 36.083333 | 13.083333 |
def cmd(send, msg, args):
"""Gets a definition from urban dictionary.
Syntax: {command} <[#<num>] <term>|--blacklist (word)|--unblacklist (word)>
"""
key = args['config']['api']['bitlykey']
parser = arguments.ArgParser(args['config'])
parser.add_argument('--blacklist')
parser.add_argument(... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"key",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'bitlykey'",
"]",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
... | 31.96875 | 16.90625 |
def _snapshot_to_data(snapshot):
'''
Returns snapshot data from a D-Bus response.
A snapshot D-Bus response is a dbus.Struct containing the
information related to a snapshot:
[id, type, pre_snapshot, timestamp, user, description,
cleanup_algorithm, userdata]
id: dbus.UInt32
type: dbu... | [
"def",
"_snapshot_to_data",
"(",
"snapshot",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"'id'",
"]",
"=",
"snapshot",
"[",
"0",
"]",
"data",
"[",
"'type'",
"]",
"=",
"[",
"'single'",
",",
"'pre'",
",",
"'post'",
"]",
"[",
"snapshot",
"[",
"1",
... | 24.975 | 18.675 |
def do_POST(self, ):
"""Handle POST requests
When the user is redirected, this handler will respond with a website
which will send a post request with the url fragment as parameters.
This will get the parameters and store the original redirection
url and fragments in :data:`Logi... | [
"def",
"do_POST",
"(",
"self",
",",
")",
":",
"log",
".",
"debug",
"(",
"'POST'",
")",
"self",
".",
"_set_headers",
"(",
")",
"# convert the parameters back to the original fragment",
"# because we need to send the original uri to set_token",
"# url fragments will not show up... | 42.818182 | 21.363636 |
def loaders(*specifiers):
"""
Generates loaders in the specified order.
Arguments can be `.Locality` instances, producing the loader(s) available
for that locality, `str` instances (used as file path templates) or
`callable`s. These can be mixed:
.. code-block:: python
# define a load... | [
"def",
"loaders",
"(",
"*",
"specifiers",
")",
":",
"for",
"specifier",
"in",
"specifiers",
":",
"if",
"isinstance",
"(",
"specifier",
",",
"Locality",
")",
":",
"# localities can carry multiple loaders, flatten this",
"yield",
"from",
"_LOADERS",
"[",
"specifier",
... | 37.806452 | 20.387097 |
def send_message(self, to_number, message, from_number=None):
""" Send a message to the specified number and return a response dictionary.
The numbers must be specified in international format starting with a '+'.
Returns a dictionary that contains a 'MessageId' key with the sent messag... | [
"def",
"send_message",
"(",
"self",
",",
"to_number",
",",
"message",
",",
"from_number",
"=",
"None",
")",
":",
"values",
"=",
"{",
"'Message'",
":",
"message",
"}",
"if",
"from_number",
"is",
"not",
"None",
":",
"values",
"[",
"'From'",
"]",
"=",
"fr... | 44.130435 | 18.782609 |
def Nu_vertical_cylinder_McAdams_Weiss_Saunders(Pr, Gr, turbulent=None):
r'''Calculates Nusselt number for natural convection around a vertical
isothermal cylinder according to the results of [1]_ and [2]_ correlated by
[3]_, as presented in [4]_, [5]_, and [6]_.
.. math::
Nu_H = 0.59 Ra_H^{0.2... | [
"def",
"Nu_vertical_cylinder_McAdams_Weiss_Saunders",
"(",
"Pr",
",",
"Gr",
",",
"turbulent",
"=",
"None",
")",
":",
"Ra",
"=",
"Pr",
"*",
"Gr",
"if",
"turbulent",
"or",
"(",
"Ra",
">",
"1E9",
"and",
"turbulent",
"is",
"None",
")",
":",
"return",
"0.13",... | 38.704918 | 26.04918 |
def start_mon_service(distro, cluster, hostname):
"""
start mon service depending on distro init
"""
if distro.init == 'sysvinit':
service = distro.conn.remote_module.which_service()
remoto.process.run(
distro.conn,
[
service,
'ceph... | [
"def",
"start_mon_service",
"(",
"distro",
",",
"cluster",
",",
"hostname",
")",
":",
"if",
"distro",
".",
"init",
"==",
"'sysvinit'",
":",
"service",
"=",
"distro",
".",
"conn",
".",
"remote_module",
".",
"which_service",
"(",
")",
"remoto",
".",
"process... | 26.75 | 18.75 |
def from_array(array):
"""
Deserialize a new Game from a given dictionary.
:return: new Game instance.
:rtype: Game
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data... | [
"def",
"from_array",
"(",
"array",
")",
":",
"if",
"array",
"is",
"None",
"or",
"not",
"array",
":",
"return",
"None",
"# end if",
"assert_type_or_raise",
"(",
"array",
",",
"dict",
",",
"parameter_name",
"=",
"\"array\"",
")",
"data",
"=",
"{",
"}",
"da... | 43.52381 | 26.666667 |
def get_indices(integers):
"""
:param integers: a sequence of integers (with repetitions)
:returns: a dict integer -> [(start, stop), ...]
>>> get_indices([0, 0, 3, 3, 3, 2, 2, 0])
{0: [(0, 2), (7, 8)], 3: [(2, 5)], 2: [(5, 7)]}
"""
indices = AccumDict(accum=[]) # idx -> [(start, stop), ..... | [
"def",
"get_indices",
"(",
"integers",
")",
":",
"indices",
"=",
"AccumDict",
"(",
"accum",
"=",
"[",
"]",
")",
"# idx -> [(start, stop), ...]",
"start",
"=",
"0",
"for",
"i",
",",
"vals",
"in",
"itertools",
".",
"groupby",
"(",
"integers",
")",
":",
"n"... | 32.6 | 14.466667 |
def density(a_M, *args, **kwargs):
"""
ARGS
a_M matrix to analyze
*args[0] optional mask matrix; if passed, calculate
density of a_M using non-zero elements of
args[0] as a mask.
DESC
Determine the "dens... | [
"def",
"density",
"(",
"a_M",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rows",
",",
"cols",
"=",
"a_M",
".",
"shape",
"a_Mmask",
"=",
"ones",
"(",
"(",
"rows",
",",
"cols",
")",
")",
"if",
"len",
"(",
"args",
")",
":",
"a_Mmask",
... | 32.210526 | 21 |
def check(self, state, when):
"""
Checks state `state` to see if the breakpoint should fire.
:param state: The state.
:param when: Whether the check is happening before or after the event.
:return: A boolean representing whether the checkpoint should fire.
""... | [
"def",
"check",
"(",
"self",
",",
"state",
",",
"when",
")",
":",
"ok",
"=",
"self",
".",
"enabled",
"and",
"(",
"when",
"==",
"self",
".",
"when",
"or",
"self",
".",
"when",
"==",
"BP_BOTH",
")",
"if",
"not",
"ok",
":",
"return",
"ok",
"l",
".... | 37.808511 | 20.06383 |
def _load_hangul_syllable_types():
"""
Helper function for parsing the contents of "HangulSyllableType.txt" from the Unicode Character Database (UCD) and
generating a lookup table for determining whether or not a given Hangul syllable is of type "L", "V", "T", "LV" or
"LVT". For more info on the UCD, s... | [
"def",
"_load_hangul_syllable_types",
"(",
")",
":",
"filename",
"=",
"\"HangulSyllableType.txt\"",
"current_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"codecs",
".",
"open",
"(",
... | 61.35 | 29.35 |
def rtsp_url(self, channelno=None, typeno=None):
"""
Return RTSP streaming url
Params:
channelno: integer, the video channel index which starts from 1,
default 1 if not specified.
typeno: the stream type, default 0 if not specified. It can be
... | [
"def",
"rtsp_url",
"(",
"self",
",",
"channelno",
"=",
"None",
",",
"typeno",
"=",
"None",
")",
":",
"if",
"channelno",
"is",
"None",
":",
"channelno",
"=",
"1",
"if",
"typeno",
"is",
"None",
":",
"typeno",
"=",
"0",
"cmd",
"=",
"'cam/realmonitor?chann... | 31.935484 | 20.129032 |
def merge_asof(left, right, on=None,
left_on=None, right_on=None,
left_index=False, right_index=False,
by=None, left_by=None, right_by=None,
suffixes=('_x', '_y'),
tolerance=None,
allow_exact_matches=True,
direction... | [
"def",
"merge_asof",
"(",
"left",
",",
"right",
",",
"on",
"=",
"None",
",",
"left_on",
"=",
"None",
",",
"right_on",
"=",
"None",
",",
"left_index",
"=",
"False",
",",
"right_index",
"=",
"False",
",",
"by",
"=",
"None",
",",
"left_by",
"=",
"None",... | 35.060086 | 21.927039 |
def compose_title(projects, data):
""" Compose the projects JSON file only with the projects name
:param projects: projects.json
:param data: eclipse JSON with the origin format
:return: projects.json with titles
"""
for project in data:
projects[project] = {
'meta': {
... | [
"def",
"compose_title",
"(",
"projects",
",",
"data",
")",
":",
"for",
"project",
"in",
"data",
":",
"projects",
"[",
"project",
"]",
"=",
"{",
"'meta'",
":",
"{",
"'title'",
":",
"data",
"[",
"project",
"]",
"[",
"'title'",
"]",
"}",
"}",
"return",
... | 28.071429 | 14.142857 |
def attack_single_step(self, x, eta, g_feat):
"""
TensorFlow implementation of the Fast Feature Gradient. This is a
single step attack similar to Fast Gradient Method that attacks an
internal representation.
:param x: the input placeholder
:param eta: A tensor the same shape as x that holds the... | [
"def",
"attack_single_step",
"(",
"self",
",",
"x",
",",
"eta",
",",
"g_feat",
")",
":",
"adv_x",
"=",
"x",
"+",
"eta",
"a_feat",
"=",
"self",
".",
"model",
".",
"fprop",
"(",
"adv_x",
")",
"[",
"self",
".",
"layer",
"]",
"# feat.shape = (batch, c) or ... | 31.571429 | 20.571429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.