text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def destiny_addr_mode(pkt):
"""destiny_addr_mode
This function depending on the arguments returns the amount of bits to be
used by the destiny address.
Keyword arguments:
pkt -- packet object instance
"""
if pkt.m == 0 and pkt.dac == 0:
if pkt.dam == 0x0:
return 16
... | [
"def",
"destiny_addr_mode",
"(",
"pkt",
")",
":",
"if",
"pkt",
".",
"m",
"==",
"0",
"and",
"pkt",
".",
"dac",
"==",
"0",
":",
"if",
"pkt",
".",
"dam",
"==",
"0x0",
":",
"return",
"16",
"elif",
"pkt",
".",
"dam",
"==",
"0x1",
":",
"return",
"8",... | 26.133333 | 14.422222 |
def reload(self, env=None, silent=None): # pragma: no cover
"""Clean end Execute all loaders"""
self.clean()
self.execute_loaders(env, silent) | [
"def",
"reload",
"(",
"self",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
")",
":",
"# pragma: no cover",
"self",
".",
"clean",
"(",
")",
"self",
".",
"execute_loaders",
"(",
"env",
",",
"silent",
")"
] | 41 | 10.25 |
def _log_file_processing_stats(self, known_file_paths):
"""
Print out stats about how files are getting processed.
:param known_file_paths: a list of file paths that may contain Airflow
DAG definitions
:type known_file_paths: list[unicode]
:return: None
"""
... | [
"def",
"_log_file_processing_stats",
"(",
"self",
",",
"known_file_paths",
")",
":",
"# File Path: Path to the file containing the DAG definition",
"# PID: PID associated with the process that's processing the file. May",
"# be empty.",
"# Runtime: If the process is currently running, how long... | 40.4 | 19.68 |
def create_session_config(log_device_placement=False,
enable_graph_rewriter=False,
gpu_mem_fraction=0.95,
use_tpu=False,
xla_jit_level=tf.OptimizerOptions.OFF,
inter_op_parallelism_threads=0... | [
"def",
"create_session_config",
"(",
"log_device_placement",
"=",
"False",
",",
"enable_graph_rewriter",
"=",
"False",
",",
"gpu_mem_fraction",
"=",
"0.95",
",",
"use_tpu",
"=",
"False",
",",
"xla_jit_level",
"=",
"tf",
".",
"OptimizerOptions",
".",
"OFF",
",",
... | 41.424242 | 16.848485 |
def cep(numero):
"""Valida um número de CEP. O número deverá ser informado como uma string
contendo 8 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCEPError`.
.. warning::
Qualquer string que contenha 8 dígitos será considerada como um CEP
vál... | [
"def",
"cep",
"(",
"numero",
")",
":",
"_digitos",
"=",
"digitos",
"(",
"numero",
")",
"if",
"len",
"(",
"_digitos",
")",
"!=",
"8",
"or",
"len",
"(",
"numero",
")",
"!=",
"8",
":",
"raise",
"NumeroCEPError",
"(",
"'CEP \"%s\" nao possui 8 digitos'",
"%"... | 34.5 | 23.277778 |
def pomodoro(self):
"""
Pomodoro response handling and countdown
"""
if not self._initialized:
self._init()
cached_until = self.py3.time_in(0)
if self._running:
self._time_left = ceil(self._end_time - time())
time_left = ceil(self._tim... | [
"def",
"pomodoro",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_initialized",
":",
"self",
".",
"_init",
"(",
")",
"cached_until",
"=",
"self",
".",
"py3",
".",
"time_in",
"(",
"0",
")",
"if",
"self",
".",
"_running",
":",
"self",
".",
"_time... | 29.485294 | 18.014706 |
def save_model(self, file_name='model.cx'):
"""Save the assembled CX network in a file.
Parameters
----------
file_name : Optional[str]
The name of the file to save the CX network to. Default: model.cx
"""
with open(file_name, 'wt') as fh:
cx_str ... | [
"def",
"save_model",
"(",
"self",
",",
"file_name",
"=",
"'model.cx'",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"'wt'",
")",
"as",
"fh",
":",
"cx_str",
"=",
"self",
".",
"print_cx",
"(",
")",
"fh",
".",
"write",
"(",
"cx_str",
")"
] | 32.363636 | 13.454545 |
def insert(self, _values=None, **values):
"""
Insert a new record into the database
:param _values: The new record values
:type _values: dict or list
:param values: The new record values as keyword arguments
:type values: dict
:return: The result
:rtype... | [
"def",
"insert",
"(",
"self",
",",
"_values",
"=",
"None",
",",
"*",
"*",
"values",
")",
":",
"if",
"not",
"values",
"and",
"not",
"_values",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"_values",
",",
"list",
")",
":",
"if",
"_values",
... | 26.108108 | 17.945946 |
def attrsignal(descriptor, signal_name, *, defer=False):
"""
Connect the decorated method or coroutine method to the addressed signal on
a descriptor.
:param descriptor: The descriptor to connect to.
:type descriptor: :class:`Descriptor` subclass.
:param signal_name: Attribute name of the signa... | [
"def",
"attrsignal",
"(",
"descriptor",
",",
"signal_name",
",",
"*",
",",
"defer",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"add_handler_spec",
"(",
"f",
",",
"_attrsignal_spec",
"(",
"descriptor",
",",
"signal_name",
",",
"f",
",... | 40.333333 | 25.571429 |
def set_runtime_value_int(self, ihcid: int, value: int) -> bool:
""" Set integer runtime value with re-authenticate if needed"""
if self.client.set_runtime_value_int(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_int(ihcid, value) | [
"def",
"set_runtime_value_int",
"(",
"self",
",",
"ihcid",
":",
"int",
",",
"value",
":",
"int",
")",
"->",
"bool",
":",
"if",
"self",
".",
"client",
".",
"set_runtime_value_int",
"(",
"ihcid",
",",
"value",
")",
":",
"return",
"True",
"self",
".",
"re... | 51.5 | 15.333333 |
def shuffle_song(
self, song, *, num_songs=100, only_library=False, recently_played=None
):
"""Get a listing of song shuffle/mix songs.
Parameters:
song (dict): A song dict.
num_songs (int, Optional): The maximum number of songs to return from the station.
Default: ``100``
only_library (bool, Optio... | [
"def",
"shuffle_song",
"(",
"self",
",",
"song",
",",
"*",
",",
"num_songs",
"=",
"100",
",",
"only_library",
"=",
"False",
",",
"recently_played",
"=",
"None",
")",
":",
"station_info",
"=",
"{",
"'num_entries'",
":",
"num_songs",
",",
"'library_content_onl... | 27.782609 | 24.608696 |
def RGB_to_XYZ(cobj, target_illuminant=None, *args, **kwargs):
"""
RGB to XYZ conversion. Expects 0-255 RGB values.
Based off of: http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html
"""
# Will contain linearized RGB channels (removed the gamma func).
linear_channels = {}
if isinst... | [
"def",
"RGB_to_XYZ",
"(",
"cobj",
",",
"target_illuminant",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Will contain linearized RGB channels (removed the gamma func).",
"linear_channels",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"cobj",
","... | 38 | 18.115385 |
def delete(self):
"""
Remove the document and all of its bundles from ProvStore.
.. warning::
Cannot be undone.
"""
if self.abstract:
raise AbstractDocumentException()
self._api.delete_document(self.id)
self._id = None
return True | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"abstract",
":",
"raise",
"AbstractDocumentException",
"(",
")",
"self",
".",
"_api",
".",
"delete_document",
"(",
"self",
".",
"id",
")",
"self",
".",
"_id",
"=",
"None",
"return",
"True"
] | 21.928571 | 18.642857 |
def set_taker(self, resource_id):
"""Sets the resource who will be taking this assessment.
arg: resource_id (osid.id.Id): the resource Id
raise: InvalidArgument - ``resource_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- Th... | [
"def",
"set_taker",
"(",
"self",
",",
"resource_id",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.set_avatar_template",
"if",
"self",
".",
"get_taker_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
":",
"raise",
"errors",
".",
"NoAccess",
... | 44.466667 | 17.066667 |
def process_view(self, request, view_func, view_args, view_kwargs):
"""
Collect data on Class-Based Views
"""
# Purge data in view method cache
# Python 3's keys() method returns an iterator, so force evaluation before iterating.
view_keys = list(VIEW_METHOD_DATA.keys())... | [
"def",
"process_view",
"(",
"self",
",",
"request",
",",
"view_func",
",",
"view_args",
",",
"view_kwargs",
")",
":",
"# Purge data in view method cache",
"# Python 3's keys() method returns an iterator, so force evaluation before iterating.",
"view_keys",
"=",
"list",
"(",
"... | 37.548387 | 22.516129 |
def insert(self, index, key, value):
"""Inserts the key, value pair before the item with the given index."""
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
... | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"self",
".",
"keyOrder",
":",
"n",
"=",
"self",
".",
"keyOrder",
".",
"index",
"(",
"key",
")",
"del",
"self",
".",
"keyOrder",
"[",
"n",
"]",
"i... | 40.555556 | 7.111111 |
def largestNativeClique(self, max_chain_length=None):
"""Returns the largest native clique embedding we can find on the
processor, with the shortest chainlength possible (for that clique
size). If possible, returns a uniform choice among all largest
cliques.
INPUTS:
... | [
"def",
"largestNativeClique",
"(",
"self",
",",
"max_chain_length",
"=",
"None",
")",
":",
"def",
"f",
"(",
"x",
")",
":",
"return",
"x",
".",
"largestNativeClique",
"(",
"max_chain_length",
"=",
"max_chain_length",
")",
"objective",
"=",
"self",
".",
"_obje... | 43.307692 | 26 |
def lx4dec(string, first):
"""
Scan a string from a specified starting position for the
end of a decimal number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4dec_c.html
:param string: Any character string.
:type string: str
:param first: First character to scan from in string... | [
"def",
"lx4dec",
"(",
"string",
",",
"first",
")",
":",
"string",
"=",
"stypes",
".",
"stringToCharP",
"(",
"string",
")",
"first",
"=",
"ctypes",
".",
"c_int",
"(",
"first",
")",
"last",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"nchar",
"=",
"ctypes",... | 30.85 | 16.65 |
def asnum(number, limit=None, return_format=None):
"""Returns a summary of the information our database holds for a
particular ASNUM (similar to /asdetailsascii.html) with return limit.
:param limit: number of records to be returned (max 2000)
"""
uri = 'asnum/{number}'.format(number=number)
if... | [
"def",
"asnum",
"(",
"number",
",",
"limit",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'asnum/{number}'",
".",
"format",
"(",
"number",
"=",
"number",
")",
"if",
"limit",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"... | 39.6 | 14.5 |
def _initialize_client_from_environment():
''' Initialize a KeenClient instance using environment variables. '''
global _client, project_id, write_key, read_key, master_key, base_url
if _client is None:
# check environment for project ID and keys
project_id = project_id or os.environ.get("K... | [
"def",
"_initialize_client_from_environment",
"(",
")",
":",
"global",
"_client",
",",
"project_id",
",",
"write_key",
",",
"read_key",
",",
"master_key",
",",
"base_url",
"if",
"_client",
"is",
"None",
":",
"# check environment for project ID and keys",
"project_id",
... | 48.35 | 23.45 |
def _get_zone_id_from_name(self, name):
"""Return zone ID based on a zone."""
results = self.client['Account'].getDomains(
filter={"domains": {"name": utils.query_filter(name)}})
return [x['id'] for x in results] | [
"def",
"_get_zone_id_from_name",
"(",
"self",
",",
"name",
")",
":",
"results",
"=",
"self",
".",
"client",
"[",
"'Account'",
"]",
".",
"getDomains",
"(",
"filter",
"=",
"{",
"\"domains\"",
":",
"{",
"\"name\"",
":",
"utils",
".",
"query_filter",
"(",
"n... | 48.8 | 8.2 |
def init():
""" Setup Mocha in the current directory """
mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))
header("Initializing Mocha ...")
if os.path.isfile(mochapyfile):
print("WARNING: It seems like Mocha is already setup!")
print("*" * 80)
else:
print("")
... | [
"def",
"init",
"(",
")",
":",
"mochapyfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CWD",
",",
"\"brew.py\"",
")",
")",
"header",
"(",
"\"Initializing Mocha ...\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",... | 32.96 | 21.24 |
def sinkhorn(w1, w2, M, reg, k):
"""Sinkhorn algorithm with fixed number of iteration (autograd)
"""
K = np.exp(-M / reg)
ui = np.ones((M.shape[0],))
vi = np.ones((M.shape[1],))
for i in range(k):
vi = w2 / (np.dot(K.T, ui))
ui = w1 / (np.dot(K, vi))
G = ui.reshape((M.shape[0... | [
"def",
"sinkhorn",
"(",
"w1",
",",
"w2",
",",
"M",
",",
"reg",
",",
"k",
")",
":",
"K",
"=",
"np",
".",
"exp",
"(",
"-",
"M",
"/",
"reg",
")",
"ui",
"=",
"np",
".",
"ones",
"(",
"(",
"M",
".",
"shape",
"[",
"0",
"]",
",",
")",
")",
"v... | 33 | 11.727273 |
def oneday_weather_forecast(
location='Portland, OR',
inputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity', 'Mean Humidity', 'Min Humidity', 'Max Sea Level Pressure', 'Mean Sea Level Pressure', 'Min Sea Level Pressure', 'Wind Direction'),
outputs=('Min Temperature', '... | [
"def",
"oneday_weather_forecast",
"(",
"location",
"=",
"'Portland, OR'",
",",
"inputs",
"=",
"(",
"'Min Temperature'",
",",
"'Mean Temperature'",
",",
"'Max Temperature'",
",",
"'Max Humidity'",
",",
"'Mean Humidity'",
",",
"'Min Humidity'",
",",
"'Max Sea Level Pressure... | 45.073171 | 30.097561 |
def create(self, object_type, under=None, attributes=None, **kwattrs):
"""Create a new automation object.
Arguments:
object_type -- Type of object to create.
under -- Handle of the parent of the new object.
attributes -- Dictionary of attributes (name-value pairs).
... | [
"def",
"create",
"(",
"self",
",",
"object_type",
",",
"under",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"*",
"*",
"kwattrs",
")",
":",
"data",
"=",
"self",
".",
"createx",
"(",
"object_type",
",",
"under",
",",
"attributes",
",",
"*",
"*",
... | 36.066667 | 21.733333 |
def phmmer(query, db, type, out, threads = '4', evalue = '0.01'):
"""
run phmmer
"""
if os.path.exists(out) is False:
print('# ... running phmmer with %s as query and %s as database' % (query, db))
os.system('phmmer -o %s.ph1 --tblout %s.ph2 --acc --noali --notextw -E %s --cpu %s %s %s' ... | [
"def",
"phmmer",
"(",
"query",
",",
"db",
",",
"type",
",",
"out",
",",
"threads",
"=",
"'4'",
",",
"evalue",
"=",
"'0.01'",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"out",
")",
"is",
"False",
":",
"print",
"(",
"'# ... running phmmer... | 49.2 | 28.6 |
def _makeButtons(self):
"""Makes buttons and wires them up.
"""
self.button = button = urwid.Button(u"OK")
urwid.connect_signal(button, "click", self._completed)
return [self.button] | [
"def",
"_makeButtons",
"(",
"self",
")",
":",
"self",
".",
"button",
"=",
"button",
"=",
"urwid",
".",
"Button",
"(",
"u\"OK\"",
")",
"urwid",
".",
"connect_signal",
"(",
"button",
",",
"\"click\"",
",",
"self",
".",
"_completed",
")",
"return",
"[",
"... | 31 | 14.428571 |
def select_update_method(self, force_interactive, force_change_set):
"""Select the correct update method when updating a stack.
Args:
force_interactive (str): Whether or not to force interactive mode
no matter what mode the provider is in.
force_change_set (bool)... | [
"def",
"select_update_method",
"(",
"self",
",",
"force_interactive",
",",
"force_change_set",
")",
":",
"if",
"self",
".",
"interactive",
"or",
"force_interactive",
":",
"return",
"self",
".",
"interactive_update_stack",
"elif",
"force_change_set",
":",
"return",
"... | 40.588235 | 20.529412 |
def copy_file(self):
share_name = self._create_share()
directory_name = self._create_directory(share_name)
source_file_name = self._get_file_reference()
self.service.create_file(share_name, directory_name, source_file_name, 512)
# Basic
# Copy the file from the directory... | [
"def",
"copy_file",
"(",
"self",
")",
":",
"share_name",
"=",
"self",
".",
"_create_share",
"(",
")",
"directory_name",
"=",
"self",
".",
"_create_directory",
"(",
"share_name",
")",
"source_file_name",
"=",
"self",
".",
"_get_file_reference",
"(",
")",
"self"... | 42.875 | 24.325 |
def children_bp(self, feature, child_featuretype='exon', merge=False,
ignore_strand=False):
"""
Total bp of all children of a featuretype.
Useful for getting the exonic bp of an mRNA.
Parameters
----------
feature : str or Feature instance
... | [
"def",
"children_bp",
"(",
"self",
",",
"feature",
",",
"child_featuretype",
"=",
"'exon'",
",",
"merge",
"=",
"False",
",",
"ignore_strand",
"=",
"False",
")",
":",
"children",
"=",
"self",
".",
"children",
"(",
"feature",
",",
"featuretype",
"=",
"child_... | 30.615385 | 23.025641 |
def __insert(self):
"""Insert rows to table
"""
if len(self.__buffer) > 0:
# Insert data
statement = self.__table.insert()
if self.__autoincrement:
statement = statement.returning(
getattr(self.__table.c, self.__autoincremen... | [
"def",
"__insert",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"__buffer",
")",
">",
"0",
":",
"# Insert data",
"statement",
"=",
"self",
".",
"__table",
".",
"insert",
"(",
")",
"if",
"self",
".",
"__autoincrement",
":",
"statement",
"=",
... | 38 | 10.1 |
def imresize_single_image(image, sizes, interpolation=None):
"""
Resizes a single image.
dtype support::
See :func:`imgaug.imgaug.imresize_many_images`.
Parameters
----------
image : (H,W,C) ndarray or (H,W) ndarray
Array of the image to resize.
Usually recommended to... | [
"def",
"imresize_single_image",
"(",
"image",
",",
"sizes",
",",
"interpolation",
"=",
"None",
")",
":",
"grayscale",
"=",
"False",
"if",
"image",
".",
"ndim",
"==",
"2",
":",
"grayscale",
"=",
"True",
"image",
"=",
"image",
"[",
":",
",",
":",
",",
... | 26.567568 | 20.945946 |
def add_binding(self, binding: Binding):
"""Stores binding"""
binding.add_error_info = lambda error: error.add_view_info(self._xml_node.view_info)
self._bindings.append(binding) | [
"def",
"add_binding",
"(",
"self",
",",
"binding",
":",
"Binding",
")",
":",
"binding",
".",
"add_error_info",
"=",
"lambda",
"error",
":",
"error",
".",
"add_view_info",
"(",
"self",
".",
"_xml_node",
".",
"view_info",
")",
"self",
".",
"_bindings",
".",
... | 49.5 | 13.5 |
def get_callback_url(self, provider):
"""Return the callback url for this provider."""
info = self.model._meta.app_label, self.model._meta.model_name
return reverse('admin:%s_%s_callback' % info, kwargs={'provider': provider.id}) | [
"def",
"get_callback_url",
"(",
"self",
",",
"provider",
")",
":",
"info",
"=",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"model_name",
"return",
"reverse",
"(",
"'admin:%s_%s_callback'",
"%",
"info... | 62.5 | 20 |
def resolve_tag(name, **kwargs):
'''
.. versionadded:: 2017.7.2
.. versionchanged:: 2018.3.0
Instead of matching against pulled tags using
:py:func:`docker.list_tags <salt.modules.dockermod.list_tags>`, this
function now simply inspects the passed image name using
:py:func:`d... | [
"def",
"resolve_tag",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"__utils__",
"[",
"'args.clean_kwargs'",
"]",
"(",
"*",
"*",
"kwargs",
")",
"all_",
"=",
"kwargs",
".",
"pop",
"(",
"'all'",
",",
"False",
")",
"if",
"kwargs",
":",
... | 35.969697 | 23.939394 |
def _get_function_name(self, fn, default="None"):
""" Return name of function, using default value if function not defined
"""
if fn is None:
fn_name = default
else:
fn_name = fn.__name__
return fn_name | [
"def",
"_get_function_name",
"(",
"self",
",",
"fn",
",",
"default",
"=",
"\"None\"",
")",
":",
"if",
"fn",
"is",
"None",
":",
"fn_name",
"=",
"default",
"else",
":",
"fn_name",
"=",
"fn",
".",
"__name__",
"return",
"fn_name"
] | 32.375 | 11.25 |
def read_text(forfn, nrows=None, verbose=True):
r""" Read all the lines (up to nrows) from a text file or txt.gz file
>>> fn = os.path.join(DATA_PATH, 'mavis-batey-greetings.txt')
>>> len(read_text(fn, nrows=3))
3
"""
tqdm_prog = tqdm if verbose else no_tqdm
nrows = wc(forfn, nrows=nrows) ... | [
"def",
"read_text",
"(",
"forfn",
",",
"nrows",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"tqdm_prog",
"=",
"tqdm",
"if",
"verbose",
"else",
"no_tqdm",
"nrows",
"=",
"wc",
"(",
"forfn",
",",
"nrows",
"=",
"nrows",
")",
"# not necessary when nro... | 44.8 | 18.64 |
def _clean_directory(self, name):
"""Clean a directory if exists and not in dry run"""
if not os.path.exists(name):
return
self.announce(
"removing directory '{}' and all its contents".format(name)
)
if not self.dry_run:
rmtree(name, True) | [
"def",
"_clean_directory",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"return",
"self",
".",
"announce",
"(",
"\"removing directory '{}' and all its contents\"",
".",
"format",
"(",
"name",
")",
... | 34.111111 | 15 |
def spherical(coordinates):
"""No error is propagated"""
c = coordinates
r = N.linalg.norm(c,axis=0)
theta = N.arccos(c[2]/r)
phi = N.arctan2(c[1],c[0])
return N.column_stack((r,theta,phi)) | [
"def",
"spherical",
"(",
"coordinates",
")",
":",
"c",
"=",
"coordinates",
"r",
"=",
"N",
".",
"linalg",
".",
"norm",
"(",
"c",
",",
"axis",
"=",
"0",
")",
"theta",
"=",
"N",
".",
"arccos",
"(",
"c",
"[",
"2",
"]",
"/",
"r",
")",
"phi",
"=",
... | 29.571429 | 9.285714 |
def pack_metadata(self) -> List[Tuple[str, Any]]:
"""Packs the log fields and the invocation metadata into a new metadata
The log fields are added in the new metadata with the key
`LOG_FIELDS_KEY_META`.
"""
metadata = [(k, v) for k, v in self._invocation_metadata.items()
... | [
"def",
"pack_metadata",
"(",
"self",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"metadata",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_invocation_metadata",
".",
"items",
"(",
")",
... | 40.818182 | 19.363636 |
def cache(self):
"""Call a user defined query and cache the results"""
if not self._bucket_width or self._untrusted_time is None:
raise ValueError('QueryCompute must be initialized with a bucket_width '
'and an untrusted_time in order to write to the cache.')
now = datetime.dat... | [
"def",
"cache",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_bucket_width",
"or",
"self",
".",
"_untrusted_time",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'QueryCompute must be initialized with a bucket_width '",
"'and an untrusted_time in order to write to t... | 44.416667 | 22.833333 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document_label') and self.document_label is not None:
_dict['document_label'] = self.document_label
if hasattr(self, 'location') and self.location is not None:
... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'document_label'",
")",
"and",
"self",
".",
"document_label",
"is",
"not",
"None",
":",
"_dict",
"[",
"'document_label'",
"]",
"=",
"self",
".",
"docu... | 55.4375 | 22.25 |
def get_bytes(self, n):
"""
Return the next C{n} bytes of the Message, without decomposing into
an int, string, etc. Just the raw bytes are returned.
@return: a string of the next C{n} bytes of the Message, or a string
of C{n} zero bytes, if there aren't C{n} bytes remainin... | [
"def",
"get_bytes",
"(",
"self",
",",
"n",
")",
":",
"b",
"=",
"self",
".",
"packet",
".",
"read",
"(",
"n",
")",
"if",
"len",
"(",
"b",
")",
"<",
"n",
":",
"return",
"b",
"+",
"'\\x00'",
"*",
"(",
"n",
"-",
"len",
"(",
"b",
")",
")",
"re... | 35.538462 | 19.384615 |
def delete_dag(dag_id):
"""
Delete all DB records related to the specified Dag.
"""
try:
count = delete.delete_dag(dag_id)
except AirflowException as err:
_log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return ... | [
"def",
"delete_dag",
"(",
"dag_id",
")",
":",
"try",
":",
"count",
"=",
"delete",
".",
"delete_dag",
"(",
"dag_id",
")",
"except",
"AirflowException",
"as",
"err",
":",
"_log",
".",
"error",
"(",
"err",
")",
"response",
"=",
"jsonify",
"(",
"error",
"=... | 32.916667 | 13.083333 |
def do_some_expensive_things(number):
"""
Perform one expensive computation cooperatively with any
other iterator passed into twisted's cooperate, then
use it's result to pass into the second computation.
:param number:
:return:
"""
result = yield batch_accumulate(1000, expensive(numb... | [
"def",
"do_some_expensive_things",
"(",
"number",
")",
":",
"result",
"=",
"yield",
"batch_accumulate",
"(",
"1000",
",",
"expensive",
"(",
"number",
")",
")",
"total",
"=",
"reduce",
"(",
"add",
",",
"result",
",",
"0",
")",
"log",
".",
"msg",
"(",
"\... | 34.470588 | 16.823529 |
def orient_graph(self, df_data, graph, nb_runs=6, printout=None, **kwargs):
"""Orient an undirected graph using the pairwise method defined by the subclass.
The pairwise method is ran on every undirected edge.
Args:
df_data (pandas.DataFrame): Data
umg (networkx.Graph):... | [
"def",
"orient_graph",
"(",
"self",
",",
"df_data",
",",
"graph",
",",
"nb_runs",
"=",
"6",
",",
"printout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"type",
"(",
"graph",
")",
"==",
"nx",
".",
"DiGraph",
":",
"edges",
"=",
"[",
"a",... | 38.490909 | 20.872727 |
def get_request_authorization(method, resource, key, params, headers):
""" :return bytes (PY2) or string (PY2) """
if not key:
return six.b('')
content = method + "\n"
if 'Content-MD5' in headers:
content += headers['Content-MD5']
content += '\n'
... | [
"def",
"get_request_authorization",
"(",
"method",
",",
"resource",
",",
"key",
",",
"params",
",",
"headers",
")",
":",
"if",
"not",
"key",
":",
"return",
"six",
".",
"b",
"(",
"''",
")",
"content",
"=",
"method",
"+",
"\"\\n\"",
"if",
"'Content-MD5'",
... | 41.933333 | 11.266667 |
def run_script(self, container, instance=None, map_name=None, **kwargs):
"""
Runs a script or single command in the context of a container. By the default implementation this means creating
the container along with all of its dependencies, mounting the script path, and running the script. The re... | [
"def",
"run_script",
"(",
"self",
",",
"container",
",",
"instance",
"=",
"None",
",",
"map_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"run_actions",
"(",
"'script'",
",",
"container",
",",
"instances",
"=",
"instance",... | 64.736842 | 32.842105 |
def authority(self, column=None, value=None, **kwargs):
"""Provides codes and associated authorizing statutes."""
return self._resolve_call('GIC_AUTHORITY', column, value, **kwargs) | [
"def",
"authority",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'GIC_AUTHORITY'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | 65 | 16.666667 |
def parse_synset(self, offset=None, debug=False):
"""Parses Synset from file
"""
if False:
pass
else:
# WORD_INSTANCE
def _word_instance():
_synset(True)
# WORD_MEANING
def _synset(pn=False):
if ... | [
"def",
"parse_synset",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"if",
"False",
":",
"pass",
"else",
":",
"# WORD_INSTANCE",
"def",
"_word_instance",
"(",
")",
":",
"_synset",
"(",
"True",
")",
"# WORD_MEANING",
"def"... | 38.751553 | 18.742236 |
def handles(self, src, path):
"""Must return a list of files that this handler will produce after
successfully processing `path`. If the current handler does not operate
on `path`, None should be returned. If instead `path` should not
produce output by itself (but should be compiled none... | [
"def",
"handles",
"(",
"self",
",",
"src",
",",
"path",
")",
":",
"if",
"not",
"pathtools",
".",
"patterns",
".",
"match_path",
"(",
"path",
",",
"self",
".",
"patterns",
",",
"self",
".",
"ignore_patterns",
")",
":",
"return",
"None",
"return",
"self"... | 57.285714 | 24.5 |
def append(self, observation, action, reward, terminal, training=True):
"""Append a reward to the memory
# Argument
observation (dict): Observation returned by environment
action (int): Action taken to obtain this observation
reward (float): Reward obtained by taking... | [
"def",
"append",
"(",
"self",
",",
"observation",
",",
"action",
",",
"reward",
",",
"terminal",
",",
"training",
"=",
"True",
")",
":",
"super",
"(",
"EpisodeParameterMemory",
",",
"self",
")",
".",
"append",
"(",
"observation",
",",
"action",
",",
"rew... | 47.5 | 23.583333 |
def credit_note(request, note_id, access_code=None):
''' Displays a credit note.
If ``request`` is a ``POST`` request, forms for applying or refunding
a credit note will be processed.
This view requires a login, and the logged in user must be staff.
Arguments:
note_id (castable to int): T... | [
"def",
"credit_note",
"(",
"request",
",",
"note_id",
",",
"access_code",
"=",
"None",
")",
":",
"note_id",
"=",
"int",
"(",
"note_id",
")",
"current_note",
"=",
"CreditNoteController",
".",
"for_id_or_404",
"(",
"note_id",
")",
"apply_form",
"=",
"forms",
"... | 34.227273 | 23.113636 |
def pluck(obj, selector, default=None, skipmissing=True):
"""Alternative implementation of `plucks` that accepts more complex
selectors. It's a wrapper around `pluckable`, so a `selector` can be any
valid Python expression comprising attribute getters (``.attr``) and item
getters (``[1, 4:8, "key"]``).
... | [
"def",
"pluck",
"(",
"obj",
",",
"selector",
",",
"default",
"=",
"None",
",",
"skipmissing",
"=",
"True",
")",
":",
"if",
"not",
"selector",
":",
"return",
"obj",
"if",
"selector",
"[",
"0",
"]",
"!=",
"'['",
":",
"selector",
"=",
"'.%s'",
"%",
"s... | 32.857143 | 23.619048 |
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 signal_stop(self, test_id=None):
"""
Set ts_end for the analysis represented by test_id
:param test_id: integer that represents the analysis
:return: test_id
"""
if test_id is None:
test_id = self._default_test_id
if self._analyses[test_id].ts_end:
return CONSTANTS.OK
sel... | [
"def",
"signal_stop",
"(",
"self",
",",
"test_id",
"=",
"None",
")",
":",
"if",
"test_id",
"is",
"None",
":",
"test_id",
"=",
"self",
".",
"_default_test_id",
"if",
"self",
".",
"_analyses",
"[",
"test_id",
"]",
".",
"ts_end",
":",
"return",
"CONSTANTS",... | 34.583333 | 13.083333 |
def from_text(text):
"""Convert the text form of a TTL to an integer.
The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported.
@param text: the textual TTL
@type text: string
@raises dns.ttl.BadTTL: the TTL is not well-formed
@rtype: int
"""
if text.isdigit():
total... | [
"def",
"from_text",
"(",
"text",
")",
":",
"if",
"text",
".",
"isdigit",
"(",
")",
":",
"total",
"=",
"long",
"(",
"text",
")",
"else",
":",
"if",
"not",
"text",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"raise",
"BadTTL",
"total",
"=",
"0L... | 29.761905 | 15.261905 |
def wait_until_complete(job_list):
"""
Args: Accepts a list of GPJob objects
This method will not return until all GPJob objects in the list have
finished running. That us, they are either complete and have resulted in
an error state.
This method will occasionally query... | [
"def",
"wait_until_complete",
"(",
"job_list",
")",
":",
"complete",
"=",
"[",
"False",
"]",
"*",
"len",
"(",
"job_list",
")",
"wait",
"=",
"1",
"while",
"not",
"all",
"(",
"complete",
")",
":",
"time",
".",
"sleep",
"(",
"wait",
")",
"for",
"i",
"... | 35.6 | 15.3 |
def feed(self, data):
"""
Feed data to the parser.
"""
assert isinstance(data, binary_type)
for b in iterbytes(data):
self._parser.send(int2byte(b)) | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"binary_type",
")",
"for",
"b",
"in",
"iterbytes",
"(",
"data",
")",
":",
"self",
".",
"_parser",
".",
"send",
"(",
"int2byte",
"(",
"b",
")",
")"
] | 27.714286 | 5.714286 |
def _parse_handler_result(self, result):
"""Parses the item(s) returned by your handler implementation.
Handlers may return a single item (payload), or a tuple that gets
passed to the Response class __init__ method of your HTTP layer.
_parse_handler_result separates the payload from th... | [
"def",
"_parse_handler_result",
"(",
"self",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"payload",
"=",
"result",
"[",
"0",
"]",
"list_result",
"=",
"list",
"(",
"result",
")",
"else",
"... | 41.882353 | 18.882353 |
def cacheback(lifetime=None, fetch_on_miss=None, cache_alias=None,
job_class=None, task_options=None, **job_class_kwargs):
"""
Decorate function to cache its return value.
:lifetime: How long to cache items for
:fetch_on_miss: Whether to perform a synchronous fetch when no cached
... | [
"def",
"cacheback",
"(",
"lifetime",
"=",
"None",
",",
"fetch_on_miss",
"=",
"None",
",",
"cache_alias",
"=",
"None",
",",
"job_class",
"=",
"None",
",",
"task_options",
"=",
"None",
",",
"*",
"*",
"job_class_kwargs",
")",
":",
"if",
"job_class",
"is",
"... | 43.181818 | 19.545455 |
def send_message(self, message, callback):
""" send a message over the wire; callback=None indicates a safe=False call where we write and forget about it"""
if self.__callback is not None:
raise ProgrammingError('connection already in use')
if callback:
err_call... | [
"def",
"send_message",
"(",
"self",
",",
"message",
",",
"callback",
")",
":",
"if",
"self",
".",
"__callback",
"is",
"not",
"None",
":",
"raise",
"ProgrammingError",
"(",
"'connection already in use'",
")",
"if",
"callback",
":",
"err_callback",
"=",
"functoo... | 41.407407 | 20.62963 |
def numRegisteredForRole(self, role, includeTemporaryRegs=False):
'''
Accepts a DanceRole object and returns the number of registrations of that role.
'''
count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count()
if includeTemporaryRegs:
... | [
"def",
"numRegisteredForRole",
"(",
"self",
",",
"role",
",",
"includeTemporaryRegs",
"=",
"False",
")",
":",
"count",
"=",
"self",
".",
"eventregistration_set",
".",
"filter",
"(",
"cancelled",
"=",
"False",
",",
"dropIn",
"=",
"False",
",",
"role",
"=",
... | 54.777778 | 33.888889 |
def mahalanobis_norm(self, dx):
"""compute the Mahalanobis norm that is induced by the adapted
sample distribution, covariance matrix ``C`` times ``sigma**2``,
including ``sigma_vec``. The expected Mahalanobis distance to
the sample mean is about ``sqrt(dimension)``.
Argument
... | [
"def",
"mahalanobis_norm",
"(",
"self",
",",
"dx",
")",
":",
"return",
"sqrt",
"(",
"sum",
"(",
"(",
"self",
".",
"D",
"**",
"-",
"1.",
"*",
"np",
".",
"dot",
"(",
"self",
".",
"B",
".",
"T",
",",
"dx",
"/",
"self",
".",
"sigma_vec",
")",
")"... | 40.76 | 23.2 |
def random_card(cards, remove=False):
"""
Returns a random card from the Stack. If ``remove=True``, it will
also remove the card from the deck.
:arg bool remove:
Whether or not to remove the card from the deck.
:returns:
A random Card object, from the Stack.
"""
if not rem... | [
"def",
"random_card",
"(",
"cards",
",",
"remove",
"=",
"False",
")",
":",
"if",
"not",
"remove",
":",
"return",
"random",
".",
"choice",
"(",
"cards",
")",
"else",
":",
"i",
"=",
"random",
".",
"randrange",
"(",
"len",
"(",
"cards",
")",
")",
"car... | 24.105263 | 17.684211 |
def make_runserver(app_factory, hostname='localhost', port=5000,
use_reloader=False, use_debugger=False, use_evalex=True,
threaded=False, processes=1, static_files=None,
extra_files=None, ssl_context=None):
"""Returns an action callback that spawns a new deve... | [
"def",
"make_runserver",
"(",
"app_factory",
",",
"hostname",
"=",
"'localhost'",
",",
"port",
"=",
"5000",
",",
"use_reloader",
"=",
"False",
",",
"use_debugger",
"=",
"False",
",",
"use_evalex",
"=",
"True",
",",
"threaded",
"=",
"False",
",",
"processes",... | 49.787879 | 21.454545 |
def _run(self):
"""Run the receiver.
"""
port = broadcast_port
nameservers = []
if self._multicast_enabled:
recv = MulticastReceiver(port).settimeout(2.)
while True:
try:
recv = MulticastReceiver(port).settimeout(2.)
... | [
"def",
"_run",
"(",
"self",
")",
":",
"port",
"=",
"broadcast_port",
"nameservers",
"=",
"[",
"]",
"if",
"self",
".",
"_multicast_enabled",
":",
"recv",
"=",
"MulticastReceiver",
"(",
"port",
")",
".",
"settimeout",
"(",
"2.",
")",
"while",
"True",
":",
... | 42.196721 | 14.442623 |
def add_local(self, field_name, field):
"""Add a local variable in the current scope
:field_name: The field's name
:field: The field
:returns: None
"""
self._dlog("adding local '{}'".format(field_name))
field._pfp__name = field_name
# TODO do we allow cl... | [
"def",
"add_local",
"(",
"self",
",",
"field_name",
",",
"field",
")",
":",
"self",
".",
"_dlog",
"(",
"\"adding local '{}'\"",
".",
"format",
"(",
"field_name",
")",
")",
"field",
".",
"_pfp__name",
"=",
"field_name",
"# TODO do we allow clobbering of locals???",... | 31.916667 | 13.333333 |
def get_acquaintance_size(obj: Union[circuits.Circuit, ops.Operation]) -> int:
"""The maximum number of qubits to be acquainted with each other."""
if isinstance(obj, circuits.Circuit):
if not is_acquaintance_strategy(obj):
raise TypeError('not is_acquaintance_strategy(circuit)')
ret... | [
"def",
"get_acquaintance_size",
"(",
"obj",
":",
"Union",
"[",
"circuits",
".",
"Circuit",
",",
"ops",
".",
"Operation",
"]",
")",
"->",
"int",
":",
"if",
"isinstance",
"(",
"obj",
",",
"circuits",
".",
"Circuit",
")",
":",
"if",
"not",
"is_acquaintance_... | 50.541667 | 14.041667 |
def process_response(self, result):
""" process a response from the API. We check the API version against
the client's to see if it's old, and give them a warning (once)
Parameters
==========
result: the result from the API
"""
if len(result) == 3... | [
"def",
"process_response",
"(",
"self",
",",
"result",
")",
":",
"if",
"len",
"(",
"result",
")",
"==",
"3",
":",
"data",
"=",
"result",
"[",
"0",
"]",
"headers",
"=",
"result",
"[",
"2",
"]",
"if",
"self",
".",
"HEADER_API_VERSION",
"in",
"headers",... | 44.952381 | 18.857143 |
def update(self):
"""
Reload the keys if necessary
This is a forced update, will happen even if cache time has not elapsed.
Replaced keys will be marked as inactive and not removed.
"""
res = True # An update was successful
if self.source:
_k... | [
"def",
"update",
"(",
"self",
")",
":",
"res",
"=",
"True",
"# An update was successful",
"if",
"self",
".",
"source",
":",
"_keys",
"=",
"self",
".",
"_keys",
"# just in case",
"# reread everything",
"self",
".",
"_keys",
"=",
"[",
"]",
"try",
":",
"if",
... | 35.472222 | 17.527778 |
def Registry(address='https://index.docker.io', **kwargs):
"""
:return:
"""
registry = None
try:
try:
registry = V1(address, **kwargs)
registry.ping()
except RegistryException:
registry = V2(address, **kwargs)
registry.ping()
except... | [
"def",
"Registry",
"(",
"address",
"=",
"'https://index.docker.io'",
",",
"*",
"*",
"kwargs",
")",
":",
"registry",
"=",
"None",
"try",
":",
"try",
":",
"registry",
"=",
"V1",
"(",
"address",
",",
"*",
"*",
"kwargs",
")",
"registry",
".",
"ping",
"(",
... | 28.947368 | 21.052632 |
def get_commit_from_tag(self, tag: str) -> Commit:
"""
Obtain the tagged commit.
:param str tag: the tag
:return: Commit commit: the commit the tag referred to
"""
try:
selected_tag = self.repo.tags[tag]
return self.get_commit(selected_tag.commit.... | [
"def",
"get_commit_from_tag",
"(",
"self",
",",
"tag",
":",
"str",
")",
"->",
"Commit",
":",
"try",
":",
"selected_tag",
"=",
"self",
".",
"repo",
".",
"tags",
"[",
"tag",
"]",
"return",
"self",
".",
"get_commit",
"(",
"selected_tag",
".",
"commit",
".... | 32.923077 | 13.846154 |
def enter(self, path):
"""
Enters the given node. Creates it if it does not exist.
Returns the node.
"""
self.current.append(self.add(path))
return self.current[-1] | [
"def",
"enter",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"current",
".",
"append",
"(",
"self",
".",
"add",
"(",
"path",
")",
")",
"return",
"self",
".",
"current",
"[",
"-",
"1",
"]"
] | 29.428571 | 9.714286 |
def entry(self):
"""
Connects to Youtube Api and retrieves the video entry object
Return:
gdata.youtube.YouTubeVideoEntry
"""
api = Api()
api.authenticate()
return api.fetch_video(self.video_id) | [
"def",
"entry",
"(",
"self",
")",
":",
"api",
"=",
"Api",
"(",
")",
"api",
".",
"authenticate",
"(",
")",
"return",
"api",
".",
"fetch_video",
"(",
"self",
".",
"video_id",
")"
] | 25.4 | 16 |
def sign_decorated(self, data):
"""Sign a bytes-like object and return the decorated signature.
Sign a bytes-like object by signing the data using the signing
(private) key, and return a decorated signature, which includes the
last four bytes of the public key as a signature hint to go ... | [
"def",
"sign_decorated",
"(",
"self",
",",
"data",
")",
":",
"signature",
"=",
"self",
".",
"sign",
"(",
"data",
")",
"hint",
"=",
"self",
".",
"signature_hint",
"(",
")",
"return",
"Xdr",
".",
"types",
".",
"DecoratedSignature",
"(",
"hint",
",",
"sig... | 41.066667 | 21.466667 |
def getClassAlias(self, klass):
"""
Gets a class alias based on the supplied C{klass}. If one is not found
in the global context, one is created locally.
If you supply a string alias and the class is not registered,
L{pyamf.UnknownClassAlias} will be raised.
@param klas... | [
"def",
"getClassAlias",
"(",
"self",
",",
"klass",
")",
":",
"try",
":",
"return",
"self",
".",
"_class_aliases",
"[",
"klass",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"alias",
"=",
"self",
".",
"_class_aliases",
"[",
"klass",
"]",
"=",
"py... | 33.933333 | 21.533333 |
def login(self):
"""
This method performs the login on TheTVDB given the api key, user name and account identifier.
:return: None
"""
auth_data = dict()
auth_data['apikey'] = self.api_key
auth_data['username'] = self.username
auth_data['userkey'] = self.a... | [
"def",
"login",
"(",
"self",
")",
":",
"auth_data",
"=",
"dict",
"(",
")",
"auth_data",
"[",
"'apikey'",
"]",
"=",
"self",
".",
"api_key",
"auth_data",
"[",
"'username'",
"]",
"=",
"self",
".",
"username",
"auth_data",
"[",
"'userkey'",
"]",
"=",
"self... | 39.857143 | 22.047619 |
def return_multiple_convert_numpy(self, start_id, end_id, converter, add_args=None):
"""
Converts several objects, with ids in the range (start_id, end_id)
into a 2d numpy array and returns the array, the conversion is done by the 'converter' function
Parameters
----------
... | [
"def",
"return_multiple_convert_numpy",
"(",
"self",
",",
"start_id",
",",
"end_id",
",",
"converter",
",",
"add_args",
"=",
"None",
")",
":",
"if",
"end_id",
"==",
"-",
"1",
":",
"end_id",
"=",
"self",
".",
"points_amt",
"return",
"return_multiple_convert_num... | 53.045455 | 33.5 |
def find_old_vidyo_rooms(max_room_event_age):
"""Finds all Vidyo rooms that are:
- linked to no events
- linked only to events whose start date precedes today - max_room_event_age days
"""
recently_used = (db.session.query(VCRoom.id)
.filter(VCRoom.type == 'vidyo',
... | [
"def",
"find_old_vidyo_rooms",
"(",
"max_room_event_age",
")",
":",
"recently_used",
"=",
"(",
"db",
".",
"session",
".",
"query",
"(",
"VCRoom",
".",
"id",
")",
".",
"filter",
"(",
"VCRoom",
".",
"type",
"==",
"'vidyo'",
",",
"Event",
".",
"end_dt",
">"... | 48.928571 | 18.857143 |
def _set_name(self):
"""Set device name."""
try:
self._name = pretty(self.machine_name)
self._serial = self.serial_number
except AttributeError:
self._name = None
self._serial = None | [
"def",
"_set_name",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_name",
"=",
"pretty",
"(",
"self",
".",
"machine_name",
")",
"self",
".",
"_serial",
"=",
"self",
".",
"serial_number",
"except",
"AttributeError",
":",
"self",
".",
"_name",
"=",
"N... | 30.875 | 11.625 |
def cartogram(df, projection=None,
scale=None, limits=(0.2, 1), scale_func=None, trace=True, trace_kwargs=None,
hue=None, categorical=False, scheme=None, k=5, cmap='viridis', vmin=None, vmax=None,
legend=False, legend_values=None, legend_labels=None, legend_kwargs=None, legend_... | [
"def",
"cartogram",
"(",
"df",
",",
"projection",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"limits",
"=",
"(",
"0.2",
",",
"1",
")",
",",
"scale_func",
"=",
"None",
",",
"trace",
"=",
"True",
",",
"trace_kwargs",
"=",
"None",
",",
"hue",
"=",
... | 45.574394 | 29.768166 |
def draw(self):
"""Draws the Text in the window."""
if not self.visible:
return
# If this input text has focus, draw an outline around the text image
if self.focus:
pygame.draw.rect(self.window, self.focusColor, self.focusedImageRect, 1)
# Blit ... | [
"def",
"draw",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"visible",
":",
"return",
"# If this input text has focus, draw an outline around the text image\r",
"if",
"self",
".",
"focus",
":",
"pygame",
".",
"draw",
".",
"rect",
"(",
"self",
".",
"window",
... | 46.464286 | 27.821429 |
def reload(self):
"""
Reload the program.
:return:
None.
"""
# Get reload mode
reload_mode = self._reload_mode
# If reload mode is `exec`
if self._reload_mode == self.RELOAD_MODE_V_EXEC:
# Call `reload_using_exec`
self... | [
"def",
"reload",
"(",
"self",
")",
":",
"# Get reload mode",
"reload_mode",
"=",
"self",
".",
"_reload_mode",
"# If reload mode is `exec`",
"if",
"self",
".",
"_reload_mode",
"==",
"self",
".",
"RELOAD_MODE_V_EXEC",
":",
"# Call `reload_using_exec`",
"self",
".",
"r... | 29.125 | 16.125 |
def copy(self):
"Return a copy of the drop target (to avoid wx problems on rebuild)"
return ToolBoxDropTarget(self.dv, self.root,
self.designer, self.inspector) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"ToolBoxDropTarget",
"(",
"self",
".",
"dv",
",",
"self",
".",
"root",
",",
"self",
".",
"designer",
",",
"self",
".",
"inspector",
")"
] | 51.75 | 24.25 |
def parse_sv_frequencies(variant):
"""Parsing of some custom sv frequencies
These are very specific at the moment, this will hopefully get better over time when the
field of structural variants is more developed.
Args:
variant(cyvcf2.Variant)
Returns:
sv_frequencies(dict)
... | [
"def",
"parse_sv_frequencies",
"(",
"variant",
")",
":",
"frequency_keys",
"=",
"[",
"'clingen_cgh_benignAF'",
",",
"'clingen_cgh_benign'",
",",
"'clingen_cgh_pathogenicAF'",
",",
"'clingen_cgh_pathogenic'",
",",
"'clingen_ngi'",
",",
"'clingen_ngiAF'",
",",
"'swegen'",
"... | 24.685714 | 18.085714 |
def import_project_modules(module_name):
"""Imports modules from registered apps using given module name
and returns them as a list.
:param str module_name:
:rtype: list
"""
from django.conf import settings
submodules = []
for app in settings.INSTALLED_APPS:
module = import_ap... | [
"def",
"import_project_modules",
"(",
"module_name",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"submodules",
"=",
"[",
"]",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"module",
"=",
"import_app_module",
"(",
"app",
",",
... | 24.823529 | 16.235294 |
def map(self, func, value_shape=None, dtype=None):
"""
Apply an array -> array function on each subarray.
The function can change the shape of the subarray, but only along
dimensions that are not chunked.
Parameters
----------
func : function
Functio... | [
"def",
"map",
"(",
"self",
",",
"func",
",",
"value_shape",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"value_shape",
"is",
"None",
"or",
"dtype",
"is",
"None",
":",
"# try to compute the size of each mapped element by applying func to a random array",
... | 38.769231 | 23.876923 |
def update_args(self, override_args):
"""Update the argument used to invoke the application
Note that this will also update the dictionary of input and output files.
Parameters
-----------
override_args : dict
Dictionary of arguments to override the current values
... | [
"def",
"update_args",
"(",
"self",
",",
"override_args",
")",
":",
"self",
".",
"args",
"=",
"extract_arguments",
"(",
"override_args",
",",
"self",
".",
"args",
")",
"self",
".",
"_latch_file_info",
"(",
")",
"scratch_dir",
"=",
"self",
".",
"args",
".",
... | 35.5 | 19.875 |
def setup(self, settings):
'''
Does the actual setup of the middleware
'''
# set up the default sc logger
my_level = settings.get('SC_LOG_LEVEL', 'INFO')
my_name = settings.get('SClogger_NAME', 'sc-logger')
my_output = settings.get('SC_LOG_STDOUT', True)
m... | [
"def",
"setup",
"(",
"self",
",",
"settings",
")",
":",
"# set up the default sc logger",
"my_level",
"=",
"settings",
".",
"get",
"(",
"'SC_LOG_LEVEL'",
",",
"'INFO'",
")",
"my_name",
"=",
"settings",
".",
"get",
"(",
"'SClogger_NAME'",
",",
"'sc-logger'",
")... | 41.026316 | 18.5 |
def load(self, entity_class, entity):
"""
Load the given repository entity into the session and return a
clone. If it was already loaded before, look up the loaded entity
and return it.
All entities referenced by the loaded entity will also be loaded
(and cloned) recursi... | [
"def",
"load",
"(",
"self",
",",
"entity_class",
",",
"entity",
")",
":",
"if",
"self",
".",
"__needs_flushing",
":",
"self",
".",
"flush",
"(",
")",
"if",
"entity",
".",
"id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Can not load entity without an... | 38.884615 | 17.269231 |
def license_file_is_valid(license_filename, data_filename,
dirpath='.', verbose=False):
"""Check that XML license file for given filename_to_verify is valid.
Input:
license_filename: XML license file (must be an absolute path name)
data_filename: The data filename that... | [
"def",
"license_file_is_valid",
"(",
"license_filename",
",",
"data_filename",
",",
"dirpath",
"=",
"'.'",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"'Parsing'",
",",
"license_filename",
"doc",
"=",
"xml2object",
"(",
"license_filena... | 30.100592 | 18.573964 |
def delete_comment(self, comment_id):
"""Deletes a ``Comment``.
arg: comment_id (osid.id.Id): the ``Id`` of the ``Comment``
to remove
raise: NotFound - ``comment_id`` not found
raise: NullArgument - ``comment_id`` is ``null``
raise: OperationFailed - unable... | [
"def",
"delete_comment",
"(",
"self",
",",
"comment_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.delete_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'commenting'",
",",
"collection",
"=",
"'Comment'",
",",
"run... | 48.2 | 20.76 |
def k8s_events_handle_experiment_job_statuses(self: 'celery_app.task', payload: Dict) -> None:
"""Experiment jobs statuses"""
details = payload['details']
job_uuid = details['labels']['job_uuid']
logger.debug('handling events status for job_uuid: %s, status: %s',
job_uuid, payload['stat... | [
"def",
"k8s_events_handle_experiment_job_statuses",
"(",
"self",
":",
"'celery_app.task'",
",",
"payload",
":",
"Dict",
")",
"->",
"None",
":",
"details",
"=",
"payload",
"[",
"'details'",
"]",
"job_uuid",
"=",
"details",
"[",
"'labels'",
"]",
"[",
"'job_uuid'",... | 40.314286 | 22.257143 |
def insert(self, collection_name, instance):
""" inserts a unit of work into MongoDB. """
assert isinstance(instance, SiteStatistics)
collection = self.ds.connection(collection_name)
return collection.insert_one(instance.document).inserted_id | [
"def",
"insert",
"(",
"self",
",",
"collection_name",
",",
"instance",
")",
":",
"assert",
"isinstance",
"(",
"instance",
",",
"SiteStatistics",
")",
"collection",
"=",
"self",
".",
"ds",
".",
"connection",
"(",
"collection_name",
")",
"return",
"collection",
... | 54 | 11.6 |
def get_all_incomings(self, params=None):
"""
Get all incomings
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
i... | [
"def",
"get_all_incomings",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"self",
".",
"get_incomings_per_page",
",",
"resource",
"=",
"INCOMINGS"... | 38.333333 | 22 |
def hours(self,local=False):
""" Returns the number of hours of difference
"""
delta = self.delta(local)
return delta.total_seconds()/3600 | [
"def",
"hours",
"(",
"self",
",",
"local",
"=",
"False",
")",
":",
"delta",
"=",
"self",
".",
"delta",
"(",
"local",
")",
"return",
"delta",
".",
"total_seconds",
"(",
")",
"/",
"3600"
] | 33.2 | 4 |
def dep(self, source_name):
"""Return a bundle dependency from the sources list
:param source_name: Source name. The URL field must be a bundle or partition reference
:return:
"""
from ambry.orm.exc import NotFoundError
from ambry.dbexceptions import ConfigurationError
... | [
"def",
"dep",
"(",
"self",
",",
"source_name",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"from",
"ambry",
".",
"dbexceptions",
"import",
"ConfigurationError",
"source",
"=",
"self",
".",
"source",
"(",
"source_name",
")",
... | 32.564103 | 25.025641 |
async def _receive_data_chunk(self, chunk):
"""
Handle a DATA chunk.
"""
self._sack_needed = True
# mark as received
if self._mark_received(chunk.tsn):
return
# find stream
inbound_stream = self._get_inbound_stream(chunk.stream_id)
#... | [
"async",
"def",
"_receive_data_chunk",
"(",
"self",
",",
"chunk",
")",
":",
"self",
".",
"_sack_needed",
"=",
"True",
"# mark as received",
"if",
"self",
".",
"_mark_received",
"(",
"chunk",
".",
"tsn",
")",
":",
"return",
"# find stream",
"inbound_stream",
"=... | 29.526316 | 14.789474 |
def _resolve_placeholders(self):
"""Resolve objects that have been imported from elsewhere."""
modules = {}
for module in self.paths.values():
children = {child["name"]: child for child in module["children"]}
modules[module["name"]] = (module, children)
resolved ... | [
"def",
"_resolve_placeholders",
"(",
"self",
")",
":",
"modules",
"=",
"{",
"}",
"for",
"module",
"in",
"self",
".",
"paths",
".",
"values",
"(",
")",
":",
"children",
"=",
"{",
"child",
"[",
"\"name\"",
"]",
":",
"child",
"for",
"child",
"in",
"modu... | 44.454545 | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.