text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def update_publisher_asset(self, upload_stream, publisher_name, asset_type=None, file_name=None, **kwargs):
"""UpdatePublisherAsset.
[Preview API] Update publisher asset like logo. It accepts asset file as an octet stream and file name is passed in header values.
:param object upload_stream: Str... | [
"def",
"update_publisher_asset",
"(",
"self",
",",
"upload_stream",
",",
"publisher_name",
",",
"asset_type",
"=",
"None",
",",
"file_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"publisher_name",
"is",
"not",
... | 56.785714 | 25.321429 |
def _open_path_window(self):
"""
Hides this window and opens path window.
Passes all needed data and kwargs.
"""
self.data['top_assistant'] = self.top_assistant
self.data['current_main_assistant'] = self.get_current_main_assistant()
self.data['kwargs'] = self.kwar... | [
"def",
"_open_path_window",
"(",
"self",
")",
":",
"self",
".",
"data",
"[",
"'top_assistant'",
"]",
"=",
"self",
".",
"top_assistant",
"self",
".",
"data",
"[",
"'current_main_assistant'",
"]",
"=",
"self",
".",
"get_current_main_assistant",
"(",
")",
"self",... | 39 | 9.6 |
def files_stat(self, path, **kwargs):
"""Returns basic ``stat`` information for an MFS file
(including its hash).
.. code-block:: python
>>> c.files_stat("/test")
{'Hash': 'QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn',
'Size': 0, 'CumulativeSize': 4, 'Ty... | [
"def",
"files_stat",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"path",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/files/stat'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
"*",
"*",... | 29.545455 | 19.636364 |
def policy_definition_present(name, policy_rule=None, policy_type=None, mode=None, display_name=None, description=None,
metadata=None, parameters=None, policy_rule_json=None, policy_rule_file=None,
template='jinja', source_hash=None, source_hash_name=None, ski... | [
"def",
"policy_definition_present",
"(",
"name",
",",
"policy_rule",
"=",
"None",
",",
"policy_type",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"display_name",
"=",
"None",
",",
"description",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"parameters",
... | 39.621723 | 27.441948 |
def remove(self, observableElement):
"""
remove an obsrvable element
:param str observableElement: the name of the observable element
"""
if observableElement in self._observables:
self._observables.remove(observableElement) | [
"def",
"remove",
"(",
"self",
",",
"observableElement",
")",
":",
"if",
"observableElement",
"in",
"self",
".",
"_observables",
":",
"self",
".",
"_observables",
".",
"remove",
"(",
"observableElement",
")"
] | 33.75 | 13.25 |
def _comparator_lt(filter_value, tested_value):
"""
Tests if the filter value is strictly greater than the tested value
tested_value < filter_value
"""
if is_string(filter_value):
value_type = type(tested_value)
try:
# Try a conversion
filter_value = value_ty... | [
"def",
"_comparator_lt",
"(",
"filter_value",
",",
"tested_value",
")",
":",
"if",
"is_string",
"(",
"filter_value",
")",
":",
"value_type",
"=",
"type",
"(",
"tested_value",
")",
"try",
":",
"# Try a conversion",
"filter_value",
"=",
"value_type",
"(",
"filter_... | 29.821429 | 13.535714 |
def expKEGG(organism,names_KEGGids):
"""
Gets all KEGG pathways for an organism
:param organism: an organism as listed in organismsKEGG()
:param names_KEGGids: a Pandas dataframe with the columns 'gene_name': and 'KEGGid' as reported from idsKEGG(organism) (or a subset of it).
:returns df: a Pand... | [
"def",
"expKEGG",
"(",
"organism",
",",
"names_KEGGids",
")",
":",
"#print \"KEGG API: http://rest.kegg.jp/list/pathway/\"+organism",
"#sys.stdout.flush()",
"kegg_paths",
"=",
"urlopen",
"(",
"\"http://rest.kegg.jp/list/pathway/\"",
"+",
"organism",
")",
".",
"read",
"(",
"... | 39.942308 | 17.711538 |
def from_data(cls, data):
"""Create gyroscope stream from data array
Parameters
-------------------
data : (N, 3) ndarray
Data array of angular velocities (rad/s)
Returns
-------------------
GyroStream
Stream object
"""
if... | [
"def",
"from_data",
"(",
"cls",
",",
"data",
")",
":",
"if",
"not",
"data",
".",
"shape",
"[",
"1",
"]",
"==",
"3",
":",
"raise",
"ValueError",
"(",
"\"Gyroscope data must have shape (N, 3)\"",
")",
"instance",
"=",
"cls",
"(",
")",
"instance",
".",
"dat... | 25 | 18.315789 |
def _tryMatch(self, textToMatchObject):
"""Try to find themselves in the text.
Returns (count, matchedRule) or (None, None) if doesn't match
"""
# andreikop: This check is not described in kate docs, and I haven't found it in the code
if not textToMatchObject.isWordStart:
... | [
"def",
"_tryMatch",
"(",
"self",
",",
"textToMatchObject",
")",
":",
"# andreikop: This check is not described in kate docs, and I haven't found it in the code",
"if",
"not",
"textToMatchObject",
".",
"isWordStart",
":",
"return",
"None",
"index",
"=",
"self",
".",
"_tryMat... | 47.653846 | 25.846154 |
def _get_sector(self, channel, nlines, ncols):
"""Determine which sector was scanned"""
if self._is_vis(channel):
margin = 100
sectors_ref = self.vis_sectors
else:
margin = 50
sectors_ref = self.ir_sectors
for (nlines_ref, ncols_ref), sect... | [
"def",
"_get_sector",
"(",
"self",
",",
"channel",
",",
"nlines",
",",
"ncols",
")",
":",
"if",
"self",
".",
"_is_vis",
"(",
"channel",
")",
":",
"margin",
"=",
"100",
"sectors_ref",
"=",
"self",
".",
"vis_sectors",
"else",
":",
"margin",
"=",
"50",
... | 33.933333 | 15.933333 |
def unregister(self, document):
"""
Unregisters an existing document, so that this document is no longer available.
This function is mainly used during plugin deactivation.
:param document: Name of the document
"""
if document not in self.documents.keys():
s... | [
"def",
"unregister",
"(",
"self",
",",
"document",
")",
":",
"if",
"document",
"not",
"in",
"self",
".",
"documents",
".",
"keys",
"(",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"Can not unregister document %s\"",
"%",
"document",
")",
"else",
... | 38.230769 | 20.538462 |
def rlm(data, xseq, **params):
"""
Fit RLM
"""
X = sm.add_constant(data['x'])
Xseq = sm.add_constant(xseq)
init_kwargs, fit_kwargs = separate_method_kwargs(
params['method_args'], sm.RLM, sm.RLM.fit)
model = sm.RLM(data['y'], X, **init_kwargs)
results = model.fit(**fit_kwargs)
... | [
"def",
"rlm",
"(",
"data",
",",
"xseq",
",",
"*",
"*",
"params",
")",
":",
"X",
"=",
"sm",
".",
"add_constant",
"(",
"data",
"[",
"'x'",
"]",
")",
"Xseq",
"=",
"sm",
".",
"add_constant",
"(",
"xseq",
")",
"init_kwargs",
",",
"fit_kwargs",
"=",
"s... | 27.2 | 17.3 |
def plugins():
'''Display some details about the local plugins'''
plugins = current_app.config['PLUGINS']
for name, description in entrypoints.ENTRYPOINTS.items():
echo('{0} ({1})'.format(white(description), name))
if name == 'udata.themes':
actives = [current_app.config['THEME']... | [
"def",
"plugins",
"(",
")",
":",
"plugins",
"=",
"current_app",
".",
"config",
"[",
"'PLUGINS'",
"]",
"for",
"name",
",",
"description",
"in",
"entrypoints",
".",
"ENTRYPOINTS",
".",
"items",
"(",
")",
":",
"echo",
"(",
"'{0} ({1})'",
".",
"format",
"(",... | 44.538462 | 15.769231 |
def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts_... | [
"def",
"get_server_id",
"(",
")",
":",
"# Provides:",
"# server_id",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_proxy",
"(",
")",
":",
"server_id",
"=",
"{",
"}",
"else",
":",
"use_crc",
"=",
"__opts__",
".",
"get",
"(",
"'server_id_use_crc'",... | 37.541667 | 26.958333 |
def handle(self, *args, **options):
"""
Alter the tables
"""
from categories.migration import drop_field
if 'app_name' not in options or 'model_name' not in options or 'field_name' not in options:
raise CommandError("You must specify an Application name, a Model name ... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"from",
"categories",
".",
"migration",
"import",
"drop_field",
"if",
"'app_name'",
"not",
"in",
"options",
"or",
"'model_name'",
"not",
"in",
"options",
"or",
"'field_name... | 46.333333 | 26.333333 |
def run_mutect(job, tumor_bam, normal_bam, univ_options, mutect_options):
"""
Spawn a MuTect job for each chromosome on the DNA bams.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_options: Dict of univers... | [
"def",
"run_mutect",
"(",
"job",
",",
"tumor_bam",
",",
"normal_bam",
",",
"univ_options",
",",
"mutect_options",
")",
":",
"# Get a list of chromosomes to handle",
"if",
"mutect_options",
"[",
"'chromosomes'",
"]",
":",
"chromosomes",
"=",
"mutect_options",
"[",
"'... | 47.529412 | 22.764706 |
def get_member_calendar(self, max_results=0):
''' a method to retrieve the upcoming events for all groups member belongs to
:param max_results: [optional] integer with number of events to include
:return: dictionary with list of event details inside [json] key
event_details = s... | [
"def",
"get_member_calendar",
"(",
"self",
",",
"max_results",
"=",
"0",
")",
":",
"# https://www.meetup.com/meetup_api/docs/self/calendar/#list\r",
"title",
"=",
"'%s.get_member_calendar'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_field... | 34 | 24.444444 |
def _uploadStream(self, fileName, update=False, encrypt=True):
"""
Yields a context manager that can be used to write to the bucket
with a stream. See :class:`~toil.jobStores.utils.WritablePipe` for an example.
Will throw assertion error if the file shouldn't be updated
and yet ... | [
"def",
"_uploadStream",
"(",
"self",
",",
"fileName",
",",
"update",
"=",
"False",
",",
"encrypt",
"=",
"True",
")",
":",
"blob",
"=",
"self",
".",
"bucket",
".",
"blob",
"(",
"bytes",
"(",
"fileName",
")",
",",
"encryption_key",
"=",
"self",
".",
"s... | 39.444444 | 19.666667 |
def Rforce(self,R,z,phi=0.,t=0.,v=None):
"""
NAME:
Rforce
PURPOSE:
evaluate cylindrical radial force F_R (R,z)
INPUT:
R - Cylindrical Galactocentric radius (can be Quantity)
z - vertical height (can be Quantity)
phi - azimuth... | [
"def",
"Rforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
",",
"v",
"=",
"None",
")",
":",
"return",
"self",
".",
"_Rforce_nodecorator",
"(",
"R",
",",
"z",
",",
"phi",
"=",
"phi",
",",
"t",
"=",
"t",
","... | 19 | 25.875 |
def create(vm_):
r'''
Create a single VM from a data dict.
vm\_
The dictionary use to create a VM.
Optional vm\_ dict options for overwriting template:
region_id
Optional - OpenNebula Zone ID
memory
Optional - In MB
cpu
Optional - Percent of host CPU to a... | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"'openn... | 32.735849 | 21.801887 |
def session(self):
"""Provide access to request session with local cache enabled."""
if self._session is None:
self._session = cachecontrol.CacheControl(
requests.Session(),
cache=caches.FileCache('.tvdb_cache'))
return self._session | [
"def",
"session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"self",
".",
"_session",
"=",
"cachecontrol",
".",
"CacheControl",
"(",
"requests",
".",
"Session",
"(",
")",
",",
"cache",
"=",
"caches",
".",
"FileCache",
"(",... | 42.142857 | 10.571429 |
def blend_mode(self):
"""BlendMode: The blend mode used for drawing operations."""
blend_mode_ptr = ffi.new('int *')
check_int_err(lib.SDL_GetRenderDrawBlendMode(self._ptr, blend_mode_ptr))
return BlendMode(blend_mode_ptr[0]) | [
"def",
"blend_mode",
"(",
"self",
")",
":",
"blend_mode_ptr",
"=",
"ffi",
".",
"new",
"(",
"'int *'",
")",
"check_int_err",
"(",
"lib",
".",
"SDL_GetRenderDrawBlendMode",
"(",
"self",
".",
"_ptr",
",",
"blend_mode_ptr",
")",
")",
"return",
"BlendMode",
"(",
... | 50.6 | 12.6 |
def set_motor_position(self, motor_name, position):
""" Sets the motor target position. """
self.call_remote_api('simxSetJointTargetPosition',
self.get_object_handle(motor_name),
position,
sending=True) | [
"def",
"set_motor_position",
"(",
"self",
",",
"motor_name",
",",
"position",
")",
":",
"self",
".",
"call_remote_api",
"(",
"'simxSetJointTargetPosition'",
",",
"self",
".",
"get_object_handle",
"(",
"motor_name",
")",
",",
"position",
",",
"sending",
"=",
"Tru... | 50 | 9.5 |
def b(self, number):
"""A parameter to tune the amount of field length normalisation that is
applied when calculating relevance scores.
A value of 0 will completely disable any normalisation and a value of 1
will fully normalise field lengths. The default is 0.75. Values of b
wi... | [
"def",
"b",
"(",
"self",
",",
"number",
")",
":",
"if",
"number",
"<",
"0",
":",
"self",
".",
"_b",
"=",
"0",
"elif",
"number",
">",
"1",
":",
"self",
".",
"_b",
"=",
"1",
"else",
":",
"self",
".",
"_b",
"=",
"number"
] | 35.071429 | 18.214286 |
def settings(request=None):
"""
Add the settings object to the template context.
"""
from yacms.conf import settings
allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS
template_settings = TemplateSettings(settings, allowed_settings)
template_settings.update(DEPRECATED)
# This is... | [
"def",
"settings",
"(",
"request",
"=",
"None",
")",
":",
"from",
"yacms",
".",
"conf",
"import",
"settings",
"allowed_settings",
"=",
"settings",
".",
"TEMPLATE_ACCESSIBLE_SETTINGS",
"template_settings",
"=",
"TemplateSettings",
"(",
"settings",
",",
"allowed_setti... | 38.5 | 21.6 |
def create_profiles(self, prefix, weeks, ip_user=False):
"""Create the user profiles for the given weeks."""
# Future: Add a time range in weeks for how long a user is considered
# as the same user.
# Count accessed records
record_counter = {}
for year, week in w... | [
"def",
"create_profiles",
"(",
"self",
",",
"prefix",
",",
"weeks",
",",
"ip_user",
"=",
"False",
")",
":",
"# Future: Add a time range in weeks for how long a user is considered",
"# as the same user.",
"# Count accessed records",
"record_counter",
"=",
"{",
"}",
"... | 37.32 | 18.4 |
def offload_expired_service_cargo(self, service):
"""Remove docker images for a specific service. This method will call itself recursively for dependents and
dependencies.
:param service:
:return None:
"""
# TODO: move offload cargo logic to this method
self._s... | [
"def",
"offload_expired_service_cargo",
"(",
"self",
",",
"service",
")",
":",
"# TODO: move offload cargo logic to this method",
"self",
".",
"_service_map",
"(",
"service",
",",
"self",
".",
"_offload_cargo",
",",
"descending",
"=",
"True",
")"
] | 41 | 16.666667 |
def create(message_type, priority=0):
"""Create a ProtocolMessage."""
message = protobuf.ProtocolMessage()
message.type = message_type
message.priority = priority
return message | [
"def",
"create",
"(",
"message_type",
",",
"priority",
"=",
"0",
")",
":",
"message",
"=",
"protobuf",
".",
"ProtocolMessage",
"(",
")",
"message",
".",
"type",
"=",
"message_type",
"message",
".",
"priority",
"=",
"priority",
"return",
"message"
] | 32 | 7.166667 |
def render_head(self, ctx, data):
"""
This renderer calculates content for the <head> tag by concatenating the
values from L{getHeadContent} and the overridden L{head} method.
"""
req = inevow.IRequest(ctx)
more = getattr(self.fragment, 'head', None)
if more is no... | [
"def",
"render_head",
"(",
"self",
",",
"ctx",
",",
"data",
")",
":",
"req",
"=",
"inevow",
".",
"IRequest",
"(",
"ctx",
")",
"more",
"=",
"getattr",
"(",
"self",
".",
"fragment",
",",
"'head'",
",",
"None",
")",
"if",
"more",
"is",
"not",
"None",
... | 39.307692 | 14.230769 |
def is_bytes(string):
"""Check if a string is a bytes instance
:param Union[str, bytes] string: A string that may be string or bytes like
:return: Whether the provided string is a bytes type or not
:rtype: bool
"""
if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): # noqa
... | [
"def",
"is_bytes",
"(",
"string",
")",
":",
"if",
"six",
".",
"PY3",
"and",
"isinstance",
"(",
"string",
",",
"(",
"bytes",
",",
"memoryview",
",",
"bytearray",
")",
")",
":",
"# noqa",
"return",
"True",
"elif",
"six",
".",
"PY2",
"and",
"isinstance",
... | 35.833333 | 23.083333 |
def K(self, parm):
""" Returns the Gram Matrix
Parameters
----------
parm : np.ndarray
Parameters for the Gram Matrix
Returns
----------
- Gram Matrix (np.ndarray)
"""
return ARD_K_matrix(self.X, parm) + np.identity(self.X.shape[0])*(... | [
"def",
"K",
"(",
"self",
",",
"parm",
")",
":",
"return",
"ARD_K_matrix",
"(",
"self",
".",
"X",
",",
"parm",
")",
"+",
"np",
".",
"identity",
"(",
"self",
".",
"X",
".",
"shape",
"[",
"0",
"]",
")",
"*",
"(",
"10",
"**",
"-",
"10",
")"
] | 24.307692 | 19.846154 |
def parse(self, rrstr):
# type: (bytes) -> None
'''
Parse a Rock Ridge Time Stamp record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.P... | [
"def",
"parse",
"(",
"self",
",",
"rrstr",
")",
":",
"# type: (bytes) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'TF record already initialized!'",
")",
"# We assume that the caller has already checked t... | 35.142857 | 25.485714 |
def find_nested_meta_first(d, prop_name, version):
"""Returns obj. for badgerfish and val for hbf. Appropriate for nested literals"""
if _is_badgerfish_version(version):
return find_nested_meta_first_bf(d, prop_name)
p = '^' + prop_name
return d.get(p) | [
"def",
"find_nested_meta_first",
"(",
"d",
",",
"prop_name",
",",
"version",
")",
":",
"if",
"_is_badgerfish_version",
"(",
"version",
")",
":",
"return",
"find_nested_meta_first_bf",
"(",
"d",
",",
"prop_name",
")",
"p",
"=",
"'^'",
"+",
"prop_name",
"return"... | 45.166667 | 10.5 |
def fromFile(path_or_buffer):
"""Creates abstraction using path to file
:param str path_or_buffer: path to tex file or buffer
:return: TreeOfContents object
"""
return TOC.fromLatex(open(path_or_buffer).read()
if isinstance(path_or_buffer, str)
... | [
"def",
"fromFile",
"(",
"path_or_buffer",
")",
":",
"return",
"TOC",
".",
"fromLatex",
"(",
"open",
"(",
"path_or_buffer",
")",
".",
"read",
"(",
")",
"if",
"isinstance",
"(",
"path_or_buffer",
",",
"str",
")",
"else",
"path_or_buffer",
")"
] | 39.666667 | 13.666667 |
def _get_function_type(self, function_name):
"""
Returns the function object that matches the provided name.
Only Fn:: and Ref functions are supported here so that other
functions specific to troposphere are skipped.
"""
if (function_name.startswith("Fn::") and
... | [
"def",
"_get_function_type",
"(",
"self",
",",
"function_name",
")",
":",
"if",
"(",
"function_name",
".",
"startswith",
"(",
"\"Fn::\"",
")",
"and",
"function_name",
"[",
"4",
":",
"]",
"in",
"self",
".",
"inspect_functions",
")",
":",
"return",
"self",
"... | 47.363636 | 15.181818 |
def rewind(self, count):
"""Rewind index."""
if count > self._index: # pragma: no cover
raise ValueError("Can't rewind past beginning!")
self._index -= count | [
"def",
"rewind",
"(",
"self",
",",
"count",
")",
":",
"if",
"count",
">",
"self",
".",
"_index",
":",
"# pragma: no cover",
"raise",
"ValueError",
"(",
"\"Can't rewind past beginning!\"",
")",
"self",
".",
"_index",
"-=",
"count"
] | 27.142857 | 19.857143 |
def domain_sites():
"""
Get a list of domains
Each domain is an attribute dict with name, site_id and settings
"""
if not hasattr(env,'domains'):
sites = _get_django_sites()
site_ids = sites.keys()
site_ids.sort()
domains = []
for id in site_ids... | [
"def",
"domain_sites",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"env",
",",
"'domains'",
")",
":",
"sites",
"=",
"_get_django_sites",
"(",
")",
"site_ids",
"=",
"sites",
".",
"keys",
"(",
")",
"site_ids",
".",
"sort",
"(",
")",
"domains",
"=",
"["... | 29.771429 | 17.771429 |
def do_json_set_many(self, params):
"""
\x1b[1mNAME\x1b[0m
json_set_many - like `json_set`, but for multiple key/value pairs
\x1b[1mSYNOPSIS\x1b[0m
json_set_many <path> <keys> <value> <value_type> <keys1> <value1> <value_type1> ...
\x1b[1mDESCRIPTION\x1b[0m
If the key exists and the va... | [
"def",
"do_json_set_many",
"(",
"self",
",",
"params",
")",
":",
"# Ensure we have a balance set of (key, value, type) tuples.",
"if",
"len",
"(",
"params",
".",
"keys_values_types",
")",
"%",
"3",
"!=",
"0",
":",
"self",
".",
"show_output",
"(",
"'Bad list of param... | 34.191176 | 23.691176 |
def load_transcript_fpkm_dict_from_gtf(
gtf_path,
transcript_id_column_name="reference_id",
fpkm_column_name="FPKM",
feature_column_name="feature"):
"""
Load a GTF file generated by StringTie which contains transcript-level
quantification of abundance. Returns a dictionary ma... | [
"def",
"load_transcript_fpkm_dict_from_gtf",
"(",
"gtf_path",
",",
"transcript_id_column_name",
"=",
"\"reference_id\"",
",",
"fpkm_column_name",
"=",
"\"FPKM\"",
",",
"feature_column_name",
"=",
"\"feature\"",
")",
":",
"df",
"=",
"gtfparse",
".",
"read_gtf",
"(",
"g... | 39.25 | 16.375 |
def visible(self, status):
"""Turn the display on/off (quickly)"""
self._display_control = ByteUtil.apply_flag(self._display_control, Command.DISPLAY_ON, status)
self.command(self._display_control) | [
"def",
"visible",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"_display_control",
"=",
"ByteUtil",
".",
"apply_flag",
"(",
"self",
".",
"_display_control",
",",
"Command",
".",
"DISPLAY_ON",
",",
"status",
")",
"self",
".",
"command",
"(",
"self",
... | 54.5 | 19.75 |
def qubit_adjacent_lifted_gate(i, matrix, n_qubits):
"""
Lifts input k-qubit gate on adjacent qubits starting from qubit i
to complete Hilbert space of dimension 2 ** num_qubits.
Ex: 1-qubit gate, lifts from qubit i
Ex: 2-qubit gate, lifts from qubits (i+1, i)
Ex: 3-qubit gate, lifts from qubit... | [
"def",
"qubit_adjacent_lifted_gate",
"(",
"i",
",",
"matrix",
",",
"n_qubits",
")",
":",
"n_rows",
",",
"n_cols",
"=",
"matrix",
".",
"shape",
"assert",
"n_rows",
"==",
"n_cols",
",",
"'Matrix must be square'",
"gate_size",
"=",
"np",
".",
"log2",
"(",
"n_ro... | 45.044444 | 24.6 |
def parse_characters(self, character_page):
"""Parses the DOM and returns media character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: character attributes.
"""
media_info = self.parse_sid... | [
"def",
"parse_characters",
"(",
"self",
",",
"character_page",
")",
":",
"media_info",
"=",
"self",
".",
"parse_sidebar",
"(",
"character_page",
")",
"try",
":",
"character_title",
"=",
"filter",
"(",
"lambda",
"x",
":",
"u'Characters'",
"in",
"x",
".",
"tex... | 39.114286 | 20.571429 |
def describe_version(self):
"""
Query the Cassandra server for the version.
:returns: string -- the version tag
"""
def _vers(client):
return client.describe_version()
d = self._connection()
d.addCallback(_vers)
return d | [
"def",
"describe_version",
"(",
"self",
")",
":",
"def",
"_vers",
"(",
"client",
")",
":",
"return",
"client",
".",
"describe_version",
"(",
")",
"d",
"=",
"self",
".",
"_connection",
"(",
")",
"d",
".",
"addCallback",
"(",
"_vers",
")",
"return",
"d"
... | 23.916667 | 14.25 |
def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
posterior_model = self.posterior_model
if self.dims is None:
dims = {}
else:
dims = self.dims
observed_names = self.observed_data
if isinstance(observed_names, str):
... | [
"def",
"observed_data_to_xarray",
"(",
"self",
")",
":",
"posterior_model",
"=",
"self",
".",
"posterior_model",
"if",
"self",
".",
"dims",
"is",
"None",
":",
"dims",
"=",
"{",
"}",
"else",
":",
"dims",
"=",
"self",
".",
"dims",
"observed_names",
"=",
"s... | 43.736842 | 14.526316 |
def add_permission_role(self, role, perm_view):
"""
Add permission-ViewMenu object to Role
:param role:
The role object
:param perm_view:
The PermissionViewMenu object
"""
if perm_view not in role.permissions:
try:
... | [
"def",
"add_permission_role",
"(",
"self",
",",
"role",
",",
"perm_view",
")",
":",
"if",
"perm_view",
"not",
"in",
"role",
".",
"permissions",
":",
"try",
":",
"role",
".",
"permissions",
".",
"append",
"(",
"perm_view",
")",
"self",
".",
"get_session",
... | 35.85 | 13.15 |
def emit(self, action, event):
"""
Send an event to all the client listening for notifications
:param action: Action name
:param event: Event to send
"""
NotificationManager.instance().emit(action, event, project_id=self.id) | [
"def",
"emit",
"(",
"self",
",",
"action",
",",
"event",
")",
":",
"NotificationManager",
".",
"instance",
"(",
")",
".",
"emit",
"(",
"action",
",",
"event",
",",
"project_id",
"=",
"self",
".",
"id",
")"
] | 33.25 | 15.75 |
def remove_duplicate_faces(self):
"""
On the current mesh remove any faces which are duplicates.
Alters
----------
self.faces : removes duplicates
"""
unique, inverse = grouping.unique_rows(np.sort(self.faces, axis=1))
self.update_faces(unique) | [
"def",
"remove_duplicate_faces",
"(",
"self",
")",
":",
"unique",
",",
"inverse",
"=",
"grouping",
".",
"unique_rows",
"(",
"np",
".",
"sort",
"(",
"self",
".",
"faces",
",",
"axis",
"=",
"1",
")",
")",
"self",
".",
"update_faces",
"(",
"unique",
")"
] | 30 | 16.4 |
def create_event(options, config, credentials):
"""
Create event in calendar with sms reminder.
"""
try:
http = credentials.authorize(httplib2.Http())
service = build("calendar", "v3", http=http)
event = {
"summary": options.message,
"location": "",
... | [
"def",
"create_event",
"(",
"options",
",",
"config",
",",
"credentials",
")",
":",
"try",
":",
"http",
"=",
"credentials",
".",
"authorize",
"(",
"httplib2",
".",
"Http",
"(",
")",
")",
"service",
"=",
"build",
"(",
"\"calendar\"",
",",
"\"v3\"",
",",
... | 31.517241 | 19.931034 |
def get_grade_systems(self):
"""Gets all ``GradeSystems``.
In plenary mode, the returned list contains all known grade
systems or an error results. Otherwise, the returned list may
contain only those grade systems that are accessible through
this session.
return: (osid.... | [
"def",
"get_grade_systems",
"(",
"self",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'grading'",
",",
"collection",
"=... | 48.318182 | 23.590909 |
def is_primitive(var):
"""
Checks if an object is in ( float, long, str, int, dict, list, unicode, tuple, set, frozenset, datetime.datetime, datetime.timedelta )
"""
primitives = ( float, long, str, int, dict, list, unicode, tuple, set, frozenset, datetime.datetime, datetime.timedelta, type(None) )
... | [
"def",
"is_primitive",
"(",
"var",
")",
":",
"primitives",
"=",
"(",
"float",
",",
"long",
",",
"str",
",",
"int",
",",
"dict",
",",
"list",
",",
"unicode",
",",
"tuple",
",",
"set",
",",
"frozenset",
",",
"datetime",
".",
"datetime",
",",
"datetime"... | 41.8 | 30.6 |
def modify_image_attribute(self, image_id, attribute='launchPermission',
operation='add', user_ids=None, groups=None,
product_codes=None):
"""
Changes an attribute of an image.
:type image_id: string
:param image_id: The imag... | [
"def",
"modify_image_attribute",
"(",
"self",
",",
"image_id",
",",
"attribute",
"=",
"'launchPermission'",
",",
"operation",
"=",
"'add'",
",",
"user_ids",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"product_codes",
"=",
"None",
")",
":",
"params",
"=",
... | 40.567568 | 21.540541 |
def evaluate(args, embedding, vocab, global_step, eval_analogy=False):
"""Evaluation helper"""
if 'eval_tokens' not in globals():
global eval_tokens
eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args)
if not args.no_eval_analogy:
eval_tokens_set.update(vocab... | [
"def",
"evaluate",
"(",
"args",
",",
"embedding",
",",
"vocab",
",",
"global_step",
",",
"eval_analogy",
"=",
"False",
")",
":",
"if",
"'eval_tokens'",
"not",
"in",
"globals",
"(",
")",
":",
"global",
"eval_tokens",
"eval_tokens_set",
"=",
"evaluation",
".",... | 36.416667 | 21.055556 |
def to_1000(portal_setup):
"""Initial version to 1000
:param portal_setup: The portal_setup tool
"""
logger.info("Run all import steps from SENAITE LIMS ...")
context = portal_setup._getImportContext(PROFILE_ID)
portal = context.getSite()
setup_html_filter(portal)
portal_setup.runAllIm... | [
"def",
"to_1000",
"(",
"portal_setup",
")",
":",
"logger",
".",
"info",
"(",
"\"Run all import steps from SENAITE LIMS ...\"",
")",
"context",
"=",
"portal_setup",
".",
"_getImportContext",
"(",
"PROFILE_ID",
")",
"portal",
"=",
"context",
".",
"getSite",
"(",
")"... | 33.833333 | 16.583333 |
def get_value(self, variant_line=None, variant_dict=None, entry=None,
raw_entry=None, vcf_header=None, csq_format=None, dict_key=None,
individual_id=None):
"""
Return the value as specified by plugin
Get value will return one value or None if no correct value is found.... | [
"def",
"get_value",
"(",
"self",
",",
"variant_line",
"=",
"None",
",",
"variant_dict",
"=",
"None",
",",
"entry",
"=",
"None",
",",
"raw_entry",
"=",
"None",
",",
"vcf_header",
"=",
"None",
",",
"csq_format",
"=",
"None",
",",
"dict_key",
"=",
"None",
... | 39.531746 | 14.674603 |
def parse(self, text):
"""Parse the given text, return a list of Keywords."""
token_stream = self.lexer.tokenize(text)
return self.expr(token_stream, next(token_stream)) | [
"def",
"parse",
"(",
"self",
",",
"text",
")",
":",
"token_stream",
"=",
"self",
".",
"lexer",
".",
"tokenize",
"(",
"text",
")",
"return",
"self",
".",
"expr",
"(",
"token_stream",
",",
"next",
"(",
"token_stream",
")",
")"
] | 47.5 | 11 |
def derivatives_factory(cls, coef, domain, kind, **kwargs):
"""
Given some coefficients, return a the derivative of a certain kind of
orthogonal polynomial defined over a specific domain.
"""
basis_polynomial = cls._basis_polynomial_factory(kind)
return basis_polynomial(... | [
"def",
"derivatives_factory",
"(",
"cls",
",",
"coef",
",",
"domain",
",",
"kind",
",",
"*",
"*",
"kwargs",
")",
":",
"basis_polynomial",
"=",
"cls",
".",
"_basis_polynomial_factory",
"(",
"kind",
")",
"return",
"basis_polynomial",
"(",
"coef",
",",
"domain"... | 41.75 | 19 |
def export_xhtml(html, filename, image_tag=None):
""" Export the contents of the ConsoleWidget as XHTML with inline SVGs.
Parameters:
-----------
html : str,
A utf-8 encoded Python string containing the Qt HTML to export.
filename : str
The file to be saved.
image_tag : callab... | [
"def",
"export_xhtml",
"(",
"html",
",",
"filename",
",",
"image_tag",
"=",
"None",
")",
":",
"if",
"image_tag",
"is",
"None",
":",
"image_tag",
"=",
"default_image_tag",
"else",
":",
"image_tag",
"=",
"ensure_utf8",
"(",
"image_tag",
")",
"with",
"open",
... | 33.433333 | 20.9 |
def loads(*strings, missing=Missing.silent):
"""
Read a `.Configuration` instance from strings.
:param strings: configuration contents
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance ... | [
"def",
"loads",
"(",
"*",
"strings",
",",
"missing",
"=",
"Missing",
".",
"silent",
")",
":",
"return",
"Configuration",
"(",
"*",
"(",
"yaml",
".",
"safe_load",
"(",
"string",
")",
"for",
"string",
"in",
"strings",
")",
",",
"missing",
"=",
"missing",... | 42.636364 | 18.090909 |
def prepareToCalcEndOfPrdvP(self):
'''
Prepare to calculate end-of-period marginal value by creating an array
of market resources that the agent could have next period, considering
the grid of end-of-period assets and the distribution of shocks he might
experience next period. T... | [
"def",
"prepareToCalcEndOfPrdvP",
"(",
"self",
")",
":",
"KinkBool",
"=",
"self",
".",
"Rboro",
">",
"self",
".",
"Rsave",
"# Boolean indicating that there is actually a kink.",
"# When Rboro == Rsave, this method acts just like it did in IndShock.",
"# When Rboro < Rsave, the solv... | 50.590164 | 31.213115 |
def hugoniot_rho_single(p, rho0, c0, s, min_strain=0.01):
"""
calculate density in g/cm^3 from a hugoniot curve
:param p: pressure in GPa
:param rho0: density at 1 bar in g/cm^3
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param min_strain: defining minimum v... | [
"def",
"hugoniot_rho_single",
"(",
"p",
",",
"rho0",
",",
"c0",
",",
"s",
",",
"min_strain",
"=",
"0.01",
")",
":",
"if",
"p",
"<=",
"1.e-5",
":",
"return",
"rho0",
"def",
"f_diff",
"(",
"rho",
")",
":",
"return",
"hugoniot_p",
"(",
"rho",
",",
"rh... | 30.333333 | 15.111111 |
def handle_signature(self, sig, signode):
"""Parse the signature *sig* into individual nodes and append them to the
*signode*. If ValueError is raises, parsing is aborted and the whole
*sig* string is put into a single desc_name node.
The return value is the value that identifies the ob... | [
"def",
"handle_signature",
"(",
"self",
",",
"sig",
",",
"signode",
")",
":",
"if",
"self",
".",
"_is_attr_like",
"(",
")",
":",
"sig_match",
"=",
"chpl_attr_sig_pattern",
".",
"match",
"(",
"sig",
")",
"if",
"sig_match",
"is",
"None",
":",
"raise",
"Val... | 42.835294 | 21.023529 |
def format_key_for_backend(self, key, remove_slash_prefix=False, trailing_slash=False):
"""Add a possible prefix to the key before sending it to the backend"""
path = self.prefix + key
if trailing_slash:
if not path or path[-1] != "/":
path += "/"
else:
... | [
"def",
"format_key_for_backend",
"(",
"self",
",",
"key",
",",
"remove_slash_prefix",
"=",
"False",
",",
"trailing_slash",
"=",
"False",
")",
":",
"path",
"=",
"self",
".",
"prefix",
"+",
"key",
"if",
"trailing_slash",
":",
"if",
"not",
"path",
"or",
"path... | 45.454545 | 18.818182 |
def time(self, target=None):
"""
Get server time.
Optional arguments:
* target=None - Target server.
"""
with self.lock:
if target:
self.send('TIME %s' % target)
else:
self.send('TIME')
time = ''
... | [
"def",
"time",
"(",
"self",
",",
"target",
"=",
"None",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"target",
":",
"self",
".",
"send",
"(",
"'TIME %s'",
"%",
"target",
")",
"else",
":",
"self",
".",
"send",
"(",
"'TIME'",
")",
"time",
"=",... | 29.375 | 12.125 |
def device_event_list(self, **kwargs): # noqa: E501
"""List all device events. # noqa: E501
List all device events for an account. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thr... | [
"def",
"device_event_list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"device_event_list_with... | 161.2 | 133.96 |
def popone(self, key, default=_marker):
"""Remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise
KeyError is raised.
"""
identity = self._title(key)
for i in range(len(self._impl._items)):
if self._im... | [
"def",
"popone",
"(",
"self",
",",
"key",
",",
"default",
"=",
"_marker",
")",
":",
"identity",
"=",
"self",
".",
"_title",
"(",
"key",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_impl",
".",
"_items",
")",
")",
":",
"if",
"... | 33.055556 | 12.166667 |
def start(self):
"""Start the firewall."""
self.clear()
self.setDefaultPolicy()
self.acceptIcmp()
self.acceptInput('lo') | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"setDefaultPolicy",
"(",
")",
"self",
".",
"acceptIcmp",
"(",
")",
"self",
".",
"acceptInput",
"(",
"'lo'",
")"
] | 25.833333 | 13 |
def on_epoch_end(self, epoch_info):
""" Update data in visdom on push """
metrics_df = pd.DataFrame([epoch_info.result]).set_index('epoch_idx')
visdom_append_metrics(
self.vis,
metrics_df,
first_epoch=epoch_info.global_epoch_idx == 1
) | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch_info",
")",
":",
"metrics_df",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"epoch_info",
".",
"result",
"]",
")",
".",
"set_index",
"(",
"'epoch_idx'",
")",
"visdom_append_metrics",
"(",
"self",
".",
"vis",
",",
... | 32.888889 | 19.444444 |
def add_sim_errors(self, qname, sname, value, sym=True):
"""Add a similarity error value to self.similarity_errors."""
self.similarity_errors.loc[qname, sname] = value
if sym:
self.similarity_errors.loc[sname, qname] = value | [
"def",
"add_sim_errors",
"(",
"self",
",",
"qname",
",",
"sname",
",",
"value",
",",
"sym",
"=",
"True",
")",
":",
"self",
".",
"similarity_errors",
".",
"loc",
"[",
"qname",
",",
"sname",
"]",
"=",
"value",
"if",
"sym",
":",
"self",
".",
"similarity... | 51.2 | 15.4 |
def handle_nick(self, params):
"""
Handle the initial setting of the user's nickname and nick changes.
"""
nick = params
# Valid nickname?
if re.search(r'[^a-zA-Z0-9\-\[\]\'`^{}_]', nick):
raise IRCError.from_name('erroneusnickname', ':%s' % nick)
if... | [
"def",
"handle_nick",
"(",
"self",
",",
"params",
")",
":",
"nick",
"=",
"params",
"# Valid nickname?",
"if",
"re",
".",
"search",
"(",
"r'[^a-zA-Z0-9\\-\\[\\]\\'`^{}_]'",
",",
"nick",
")",
":",
"raise",
"IRCError",
".",
"from_name",
"(",
"'erroneusnickname'",
... | 35.73913 | 18.391304 |
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else... | [
"def",
"render_state",
"(",
"self",
",",
"sls",
",",
"saltenv",
",",
"mods",
",",
"matches",
",",
"local",
"=",
"False",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"not",
"local",
":",
"state_data",
"=",
"self",
".",
"client",
".",
"get_state",
"(",
... | 46.603261 | 19.36413 |
def send(self, payload):
"""
Send a payload to exchange to containing command and payload to the queue specified in config.
:param command: str: name of the command we want run by WorkQueueProcessor
:param payload: str: string data that will be put into the exchange's message body
... | [
"def",
"send",
"(",
"self",
",",
"payload",
")",
":",
"result",
"=",
"self",
".",
"connection",
".",
"send_durable_exchange_message",
"(",
"self",
".",
"exchange_name",
",",
"payload",
")",
"logging",
".",
"info",
"(",
"\"Sent message to exchange.\"",
".",
"fo... | 55.8 | 28.6 |
def wait_until_element_does_not_have_focus(self, locator, timeout=None):
"""Waits until the element identified by `locator` doesn't have focus.
You might rather want to use `Element Focus Should Not Be Set`
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator | id=my_id |
| timeo... | [
"def",
"wait_until_element_does_not_have_focus",
"(",
"self",
",",
"locator",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_info",
"(",
"\"Waiting until '%s' does not have focus\"",
"%",
"(",
"locator",
")",
")",
"self",
".",
"_wait_until_no_error",
"(",
"... | 57.6 | 23.1 |
def run_supernova(ctx, executable, debug, quiet, environment, command, conf,
echo, dashboard):
"""
You can use supernova with many OpenStack clients and avoid the pain of
managing multiple sets of environment variables. Getting started is easy
and there's some documentation that can h... | [
"def",
"run_supernova",
"(",
"ctx",
",",
"executable",
",",
"debug",
",",
"quiet",
",",
"environment",
",",
"command",
",",
"conf",
",",
"echo",
",",
"dashboard",
")",
":",
"# Retrieve our credentials from the configuration file",
"try",
":",
"nova_creds",
"=",
... | 39.401639 | 23.270492 |
def normalize_values_queryset(values_queryset, model=None, app=None, verbosity=1):
'''Shoehorn the values from one database table into another
* Remove padding (leading/trailing spaces) from `CharField` and `TextField` values
* Truncate all `CharField`s to the max_length of the destination `model`
* Su... | [
"def",
"normalize_values_queryset",
"(",
"values_queryset",
",",
"model",
"=",
"None",
",",
"app",
"=",
"None",
",",
"verbosity",
"=",
"1",
")",
":",
"model",
"=",
"model",
"or",
"values_queryset",
".",
"model",
"app",
"=",
"app",
"or",
"DEFAULT_APP",
"new... | 47.634146 | 24.02439 |
def start(self, message):
"""
Manually starts timer with the message.
:param message: The display message.
"""
self._start = time.clock()
VSGLogger.info("{0:<20} - Started".format(message)) | [
"def",
"start",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"_start",
"=",
"time",
".",
"clock",
"(",
")",
"VSGLogger",
".",
"info",
"(",
"\"{0:<20} - Started\"",
".",
"format",
"(",
"message",
")",
")"
] | 29 | 11.5 |
def _get_tz(tz):
""" for a tz-aware type, return an encoded zone """
zone = timezones.get_timezone(tz)
if zone is None:
zone = tz.utcoffset().total_seconds()
return zone | [
"def",
"_get_tz",
"(",
"tz",
")",
":",
"zone",
"=",
"timezones",
".",
"get_timezone",
"(",
"tz",
")",
"if",
"zone",
"is",
"None",
":",
"zone",
"=",
"tz",
".",
"utcoffset",
"(",
")",
".",
"total_seconds",
"(",
")",
"return",
"zone"
] | 31.333333 | 12.833333 |
def enable(self, cmd="sudo su", pattern="ssword", re_flags=re.IGNORECASE):
"""Attempt to become root."""
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
if not self.check_enable_mode():
self.write_channel(self.normalize_cmd(cmd))
time.sleep(0.3... | [
"def",
"enable",
"(",
"self",
",",
"cmd",
"=",
"\"sudo su\"",
",",
"pattern",
"=",
"\"ssword\"",
",",
"re_flags",
"=",
"re",
".",
"IGNORECASE",
")",
":",
"delay_factor",
"=",
"self",
".",
"select_delay_factor",
"(",
"delay_factor",
"=",
"0",
")",
"output",... | 43.695652 | 15.826087 |
def _get_config(self, unit, filename):
"""Get a ConfigParser object for parsing a unit's config file."""
file_contents = unit.file_contents(filename)
# NOTE(beisner): by default, ConfigParser does not handle options
# with no value, such as the flags used in the mysql my.cnf file.
... | [
"def",
"_get_config",
"(",
"self",
",",
"unit",
",",
"filename",
")",
":",
"file_contents",
"=",
"unit",
".",
"file_contents",
"(",
"filename",
")",
"# NOTE(beisner): by default, ConfigParser does not handle options",
"# with no value, such as the flags used in the mysql my.cn... | 48.6 | 17.5 |
def cli(env, **args):
"""Allows for creating a virtual guest in a reserved capacity."""
create_args = _parse_create_args(env.client, args)
create_args['primary_disk'] = args.get('primary_disk')
manager = CapacityManager(env.client)
capacity_id = args.get('capacity_id')
test = args.get('test')
... | [
"def",
"cli",
"(",
"env",
",",
"*",
"*",
"args",
")",
":",
"create_args",
"=",
"_parse_create_args",
"(",
"env",
".",
"client",
",",
"args",
")",
"create_args",
"[",
"'primary_disk'",
"]",
"=",
"args",
".",
"get",
"(",
"'primary_disk'",
")",
"manager",
... | 34.833333 | 17.75 |
def _deferGenerator(g, deferred=None):
"""
See L{waitForDeferred}.
"""
result = None
while 1:
if deferred is None:
deferred = defer.Deferred()
try:
result = g.next()
except StopIteration:
deferred.callback(result)
return deferre... | [
"def",
"_deferGenerator",
"(",
"g",
",",
"deferred",
"=",
"None",
")",
":",
"result",
"=",
"None",
"while",
"1",
":",
"if",
"deferred",
"is",
"None",
":",
"deferred",
"=",
"defer",
".",
"Deferred",
"(",
")",
"try",
":",
"result",
"=",
"g",
".",
"ne... | 34.97561 | 15.658537 |
def flatten_links(td, _recurse=False):
"""Flattens relative URLs within text of a table cell to IDs and returns
the result.
:td: the PyQuery object for the HTML to convert
:returns: the string with the links flattened to IDs
"""
# helper function to flatten individual strings/links
def _fl... | [
"def",
"flatten_links",
"(",
"td",
",",
"_recurse",
"=",
"False",
")",
":",
"# helper function to flatten individual strings/links",
"def",
"_flatten_node",
"(",
"c",
")",
":",
"if",
"isinstance",
"(",
"c",
",",
"basestring",
")",
":",
"return",
"c",
".",
"str... | 33.375 | 15.916667 |
def load_churn():
"""Load and return the churn dataset (classification).
The bank marketing is a easily transformable example-dependent cost-sensitive classification dataset.
Returns
-------
data : Bunch
Dictionary-like object, the interesting attributes are:
'data', the data to le... | [
"def",
"load_churn",
"(",
")",
":",
"module_path",
"=",
"dirname",
"(",
"__file__",
")",
"raw_data",
"=",
"pd",
".",
"read_csv",
"(",
"join",
"(",
"module_path",
",",
"'data'",
",",
"'churn_tv_subscriptions.csv.gz'",
")",
",",
"delimiter",
"=",
"','",
",",
... | 39.54717 | 25.45283 |
def Space(self, n = 1, dl = 0):
"""空格键n次
"""
self.Delay(dl)
self.keyboard.tap_key(" ", n) | [
"def",
"Space",
"(",
"self",
",",
"n",
"=",
"1",
",",
"dl",
"=",
"0",
")",
":",
"self",
".",
"Delay",
"(",
"dl",
")",
"self",
".",
"keyboard",
".",
"tap_key",
"(",
"\" \"",
",",
"n",
")"
] | 23.4 | 6 |
def record_diff(old, new):
"""
Generate a human-readable diff of two performance records.
"""
return '\n'.join(difflib.ndiff(
['%s: %s' % (k, v) for op in old for k, v in op.items()],
['%s: %s' % (k, v) for op in new for k, v in op.items()],
)) | [
"def",
"record_diff",
"(",
"old",
",",
"new",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"difflib",
".",
"ndiff",
"(",
"[",
"'%s: %s'",
"%",
"(",
"k",
",",
"v",
")",
"for",
"op",
"in",
"old",
"for",
"k",
",",
"v",
"in",
"op",
".",
"items",
... | 34.125 | 15.625 |
def toy_data(n_obs):
"""
Randomly samples from the Dentate Gyrus dataset.
Arguments
---------
n_obs: `int`
Size of the sampled dataset
Returns
-------
Returns `adata` object
"""
"""Random samples from Dentate Gyrus.
"""
adata = dentategyrus()
indices = np.r... | [
"def",
"toy_data",
"(",
"n_obs",
")",
":",
"\"\"\"Random samples from Dentate Gyrus.\n \"\"\"",
"adata",
"=",
"dentategyrus",
"(",
")",
"indices",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"adata",
".",
"n_obs",
",",
"n_obs",
")",
"adata",
"=",
"adata",... | 21.5 | 18.136364 |
def lat_from_inc(inc, a95=None):
"""
Calculate paleolatitude from inclination using the dipole equation
Required Parameter
----------
inc: (paleo)magnetic inclination in degrees
Optional Parameter
----------
a95: 95% confidence interval from Fisher mean
Returns
----------
... | [
"def",
"lat_from_inc",
"(",
"inc",
",",
"a95",
"=",
"None",
")",
":",
"rad",
"=",
"old_div",
"(",
"np",
".",
"pi",
",",
"180.",
")",
"paleo_lat",
"=",
"old_div",
"(",
"np",
".",
"arctan",
"(",
"0.5",
"*",
"np",
".",
"tan",
"(",
"inc",
"*",
"rad... | 30.074074 | 19.259259 |
def propagate(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Return a position and velocity vector for a given date and time."""
j = jday(year, month, day, hour, minute, second)
m = (j - self.jdsatepoch) * minutes_per_day
r, v = sgp4(self, m)
return r, v | [
"def",
"propagate",
"(",
"self",
",",
"year",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0.0",
")",
":",
"j",
"=",
"jday",
"(",
"year",
",",
"month",
",",
"day",
",",
"... | 43.428571 | 18.857143 |
def registerMachine(self, machineName, adminURL):
"""
For a server machine to participate in a site, it needs to be
registered with the site. The server machine must have ArcGIS
Server software installed and authorized.
Registering machines this way is a "pull" approa... | [
"def",
"registerMachine",
"(",
"self",
",",
"machineName",
",",
"adminURL",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"machineName\"",
":",
"machineName",
",",
"\"adminURL\"",
":",
"adminURL",
"}",
"uURL",
"=",
"\"%s/register\"",
"%",
"s... | 45.666667 | 17.148148 |
def load_files(filenames,multiproc=False,**kwargs):
""" Load a set of FITS files with kwargs. """
filenames = np.atleast_1d(filenames)
logger.debug("Loading %s files..."%len(filenames))
kwargs = [dict(filename=f,**kwargs) for f in filenames]
if multiproc:
from multiprocessing import Pool
... | [
"def",
"load_files",
"(",
"filenames",
",",
"multiproc",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"filenames",
"=",
"np",
".",
"atleast_1d",
"(",
"filenames",
")",
"logger",
".",
"debug",
"(",
"\"Loading %s files...\"",
"%",
"len",
"(",
"filenames"... | 33.458333 | 15.333333 |
def get_cache_settings(self, service_id, version_number, name):
"""Get a specific cache settings object."""
content = self._fetch("/service/%s/version/%d/cache_settings/%s" % (service_id, version_number, name))
return FastlyCacheSettings(self, content) | [
"def",
"get_cache_settings",
"(",
"self",
",",
"service_id",
",",
"version_number",
",",
"name",
")",
":",
"content",
"=",
"self",
".",
"_fetch",
"(",
"\"/service/%s/version/%d/cache_settings/%s\"",
"%",
"(",
"service_id",
",",
"version_number",
",",
"name",
")",
... | 63.75 | 22.5 |
def calc_qjoints_v1(self):
"""Apply the routing equation.
Required derived parameters:
|NmbSegments|
|C1|
|C2|
|C3|
Updated state sequence:
|QJoints|
Basic equation:
:math:`Q_{space+1,time+1} =
c1 \\cdot Q_{space,time+1} +
c2 \\cdot Q_{space,time} +
... | [
"def",
"calc_qjoints_v1",
"(",
"self",
")",
":",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"new",
"=",
"self",
".",
"sequences",
".",
"states",
".",
"fastaccess_new",
"old",
"=",
"self",
".",
"sequences",
".",
"states",
".... | 28.821053 | 16.789474 |
def name(self):
"""
Get function name from the labels of the very first block.
:return: Function name if there is any, None otherwise
:rtype: string
"""
if self._name is not None:
return self._name
if not self.blocks:
return None
... | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_name",
"if",
"not",
"self",
".",
"blocks",
":",
"return",
"None",
"if",
"not",
"self",
".",
"blocks",
"[",
"0",
"]",
".",
"instru... | 23.72 | 20.36 |
def get_reaction(self, reactants, products):
"""
Gets a reaction from the Materials Project.
Args:
reactants ([str]): List of formulas
products ([str]): List of formulas
Returns:
rxn
"""
return self._make_request("/reaction",
... | [
"def",
"get_reaction",
"(",
"self",
",",
"reactants",
",",
"products",
")",
":",
"return",
"self",
".",
"_make_request",
"(",
"\"/reaction\"",
",",
"payload",
"=",
"{",
"\"reactants[]\"",
":",
"reactants",
",",
"\"products[]\"",
":",
"products",
"}",
",",
"m... | 32.285714 | 18.714286 |
def lookup_ids(handles):
""" Fetch the twitter ids of each screen_name. """
ids = set()
for handle_list in [handles[100 * i:100 * i + 100] for i in range(len(handles))]:
if len(handle_list) > 0:
while True:
r = twapi.request('users/lookup', {'screen_name': ','.join(handle... | [
"def",
"lookup_ids",
"(",
"handles",
")",
":",
"ids",
"=",
"set",
"(",
")",
"for",
"handle_list",
"in",
"[",
"handles",
"[",
"100",
"*",
"i",
":",
"100",
"*",
"i",
"+",
"100",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"handles",
")",
")"... | 44.789474 | 23.631579 |
def disable_validation(self, field_name):
"""Disable the validation rules for a field"""
field = self.field_dict.get(field_name)
if not field:
raise exceptions.FieldNotFound('Field not found: \'%s\' when trying to disable validation' % field_name)
field.validators =... | [
"def",
"disable_validation",
"(",
"self",
",",
"field_name",
")",
":",
"field",
"=",
"self",
".",
"field_dict",
".",
"get",
"(",
"field_name",
")",
"if",
"not",
"field",
":",
"raise",
"exceptions",
".",
"FieldNotFound",
"(",
"'Field not found: \\'%s\\' when tryi... | 39.5 | 23.25 |
def _set_tunnel_router_interface(self, v, load=False):
"""
Setter method for tunnel_router_interface, mapped from YANG variable /interface/tunnel/tunnel_router_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tunnel_router_interface is considered as ... | [
"def",
"_set_tunnel_router_interface",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | 86.454545 | 40.681818 |
def get(self, request, enterprise_customer_uuid):
"""
Handle GET request - render "Transmit courses metadata" form.
Arguments:
request (django.http.request.HttpRequest): Request instance
enterprise_customer_uuid (str): Enterprise Customer UUID
Returns:
... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"enterprise_customer_uuid",
")",
":",
"context",
"=",
"self",
".",
"_build_context",
"(",
"request",
",",
"enterprise_customer_uuid",
")",
"transmit_courses_metadata_form",
"=",
"TransmitEnterpriseCoursesForm",
"(",
")",... | 42.5625 | 26.9375 |
def serialize_message(message):
"""
Serializes an object. It must subclass :class:`FranzEvent`.
Parameters
----------
message : FranzEvent
The object to be serialized.
Returns
-------
bytes
"""
try:
return bson.dum... | [
"def",
"serialize_message",
"(",
"message",
")",
":",
"try",
":",
"return",
"bson",
".",
"dumps",
"(",
"message",
".",
"serialize",
"(",
")",
")",
"except",
"bson",
".",
"UnknownSerializerError",
":",
"raise",
"SerializationError",
"(",
"\"Unable to serialize me... | 25.684211 | 18.210526 |
def getFieldBitRange(self) -> Tuple[int, int]:
"""
:return: bit range which contains data of this part on interface
of field
"""
offset = self.inFieldOffset
return (self.bit_length() + offset, offset) | [
"def",
"getFieldBitRange",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"offset",
"=",
"self",
".",
"inFieldOffset",
"return",
"(",
"self",
".",
"bit_length",
"(",
")",
"+",
"offset",
",",
"offset",
")"
] | 35.142857 | 10.571429 |
def check_path(filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the given path, printing out any warnings detected."""
try:
with open(filename, 'U') as f:
codestr = f.read() + '\n'
except UnicodeError:
reporter.unexpected_error(filename, ... | [
"def",
"check_path",
"(",
"filename",
",",
"reporter",
"=",
"modReporter",
".",
"Default",
",",
"settings_path",
"=",
"None",
",",
"*",
"*",
"setting_overrides",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'U'",
")",
"as",
"f",
":",
"c... | 43 | 21.076923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.