text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def pylog(self, *args, **kwargs):
"""Display all available logging information."""
printerr(self.name, args, kwargs, traceback.format_exc()) | [
"def",
"pylog",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"printerr",
"(",
"self",
".",
"name",
",",
"args",
",",
"kwargs",
",",
"traceback",
".",
"format_exc",
"(",
")",
")"
] | 51.333333 | 10.666667 |
def file_to_list(file_name, file_location):
"""
Function to import a text file to a list
Args:
file_name: The name of file to be import
file_location: The location of the file, derive from the os module
Returns: returns a list
"""
file = __os.path.join(file_location, file_name)... | [
"def",
"file_to_list",
"(",
"file_name",
",",
"file_location",
")",
":",
"file",
"=",
"__os",
".",
"path",
".",
"join",
"(",
"file_location",
",",
"file_name",
")",
"read_file",
"=",
"open",
"(",
"file",
",",
"\"r\"",
")",
"temp_list",
"=",
"read_file",
... | 28.466667 | 15.8 |
def addPoint( self, x, y ):
"""
Adds a new chart point to this item.
:param x | <variant>
y | <variant>
"""
self._points.append((x, y))
self._dirty = True | [
"def",
"addPoint",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"_points",
".",
"append",
"(",
"(",
"x",
",",
"y",
")",
")",
"self",
".",
"_dirty",
"=",
"True"
] | 26.222222 | 8.666667 |
def get_user_and_user_email_by_id(self, user_or_user_email_id):
"""Retrieve the User and UserEmail object by ID."""
if self.UserEmailClass:
user_email = self.db_adapter.get_object(self.UserEmailClass, user_or_user_email_id)
user = user_email.user if user_email else None
e... | [
"def",
"get_user_and_user_email_by_id",
"(",
"self",
",",
"user_or_user_email_id",
")",
":",
"if",
"self",
".",
"UserEmailClass",
":",
"user_email",
"=",
"self",
".",
"db_adapter",
".",
"get_object",
"(",
"self",
".",
"UserEmailClass",
",",
"user_or_user_email_id",
... | 51.666667 | 21.555556 |
def _find_usage_subnets(self):
"""find usage for Subnets; return dict of SubnetId to AZ"""
# subnets per VPC
subnet_to_az = {}
subnets = defaultdict(int)
for subnet in self.conn.describe_subnets()['Subnets']:
subnets[subnet['VpcId']] += 1
subnet_to_az[subn... | [
"def",
"_find_usage_subnets",
"(",
"self",
")",
":",
"# subnets per VPC",
"subnet_to_az",
"=",
"{",
"}",
"subnets",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"subnet",
"in",
"self",
".",
"conn",
".",
"describe_subnets",
"(",
")",
"[",
"'Subnets'",
"]",
"... | 39.733333 | 12.6 |
def _multitaper_spectrum(self, clm, k, convention='power', unit='per_l',
clat=None, clon=None, coord_degrees=True,
lmax=None, taper_wt=None):
"""
Return the multitaper spectrum estimate and standard error for an
input SHCoeffs class insta... | [
"def",
"_multitaper_spectrum",
"(",
"self",
",",
"clm",
",",
"k",
",",
"convention",
"=",
"'power'",
",",
"unit",
"=",
"'per_l'",
",",
"clat",
"=",
"None",
",",
"clon",
"=",
"None",
",",
"coord_degrees",
"=",
"True",
",",
"lmax",
"=",
"None",
",",
"t... | 40.71875 | 19.0625 |
def get_ancestors(self):
""" Get all unique instance ancestors """
ancestors = list(self.get_parents())
ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors])
ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)]
for ancestor in anc... | [
"def",
"get_ancestors",
"(",
"self",
")",
":",
"ancestors",
"=",
"list",
"(",
"self",
".",
"get_parents",
"(",
")",
")",
"ancestor_unique_attributes",
"=",
"set",
"(",
"[",
"(",
"a",
".",
"__class__",
",",
"a",
".",
"id",
")",
"for",
"a",
"in",
"ance... | 53.7 | 19.2 |
def list_operations(self, name, filter_, page_size=0, options=None):
"""
Lists operations that match the specified filter in the request. If the
server doesn't support this method, it returns ``UNIMPLEMENTED``.
NOTE: the ``name`` binding below allows API services to override the binding
... | [
"def",
"list_operations",
"(",
"self",
",",
"name",
",",
"filter_",
",",
"page_size",
"=",
"0",
",",
"options",
"=",
"None",
")",
":",
"# Create the request object.",
"request",
"=",
"operations_pb2",
".",
"ListOperationsRequest",
"(",
"name",
"=",
"name",
","... | 47.06 | 24.54 |
def length_estimate(self):
'''
Calculates and estimated word count based on number of characters, locations,
and arcs. For reference see:
http://www.writingexcuses.com/2017/07/02/12-27-choosing-a-length/
'''
characters = self.characterinstance_set.filter(
Q(ma... | [
"def",
"length_estimate",
"(",
"self",
")",
":",
"characters",
"=",
"self",
".",
"characterinstance_set",
".",
"filter",
"(",
"Q",
"(",
"main_character",
"=",
"True",
")",
"|",
"Q",
"(",
"pov_character",
"=",
"True",
")",
"|",
"Q",
"(",
"protagonist",
"=... | 41.266667 | 15.8 |
def save(f, arr, vocab):
"""
Save word embedding file.
Check :func:`word_embedding_loader.saver.glove.save` for the API.
"""
f.write(('%d %d' % (arr.shape[0], arr.shape[1])).encode('utf-8'))
for word, idx in vocab:
_write_line(f, arr[idx], word) | [
"def",
"save",
"(",
"f",
",",
"arr",
",",
"vocab",
")",
":",
"f",
".",
"write",
"(",
"(",
"'%d %d'",
"%",
"(",
"arr",
".",
"shape",
"[",
"0",
"]",
",",
"arr",
".",
"shape",
"[",
"1",
"]",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
... | 33.75 | 12.5 |
def size_r_img_inches(width, height):
"""Compute the width and height for an R image for display in IPython
Neight width nor height can be null but should be integer pixel values > 0.
Returns a tuple of (width, height) that should be used by ggsave in R to
produce an appropriately sized jpeg/png/pdf i... | [
"def",
"size_r_img_inches",
"(",
"width",
",",
"height",
")",
":",
"# both width and height are given",
"aspect_ratio",
"=",
"height",
"/",
"(",
"1.0",
"*",
"width",
")",
"return",
"R_IMAGE_SIZE",
",",
"round",
"(",
"aspect_ratio",
"*",
"R_IMAGE_SIZE",
",",
"2",... | 41 | 20.384615 |
def collect_aliases(self):
"""Collect the type aliases in the source.
:sig: () -> None
"""
self.aliases = get_aliases(self._code_lines)
for alias, signature in self.aliases.items():
_, _, requires = parse_signature(signature)
self.required_types |= requir... | [
"def",
"collect_aliases",
"(",
"self",
")",
":",
"self",
".",
"aliases",
"=",
"get_aliases",
"(",
"self",
".",
"_code_lines",
")",
"for",
"alias",
",",
"signature",
"in",
"self",
".",
"aliases",
".",
"items",
"(",
")",
":",
"_",
",",
"_",
",",
"requi... | 35.5 | 11.4 |
def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText() | [
"def",
"cut",
"(",
"self",
")",
":",
"self",
".",
"copy",
"(",
")",
"if",
"self",
".",
"can_cut",
"(",
")",
":",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
".",
"removeSelectedText",
"(",
")"
] | 35.428571 | 12 |
def read_file(rel_path, paths=None, raw=False, as_list=False, as_iter=False,
*args, **kwargs):
'''
find a file that lives somewhere within a set of paths and
return its contents. Default paths include 'static_dir'
'''
if not rel_path:
raise ValueError("rel_path can not ... | [
"def",
"read_file",
"(",
"rel_path",
",",
"paths",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"as_list",
"=",
"False",
",",
"as_iter",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"rel_path",
":",
"raise",
"Value... | 32.428571 | 20.085714 |
def scale_axes_from_data(self):
"""Restrict data limits for Y-axis based on what you can see
"""
# get tight limits for X-axis
if self.args.xmin is None:
self.args.xmin = min(ts.xspan[0] for ts in self.timeseries)
if self.args.xmax is None:
self.args.xmax ... | [
"def",
"scale_axes_from_data",
"(",
"self",
")",
":",
"# get tight limits for X-axis",
"if",
"self",
".",
"args",
".",
"xmin",
"is",
"None",
":",
"self",
".",
"args",
".",
"xmin",
"=",
"min",
"(",
"ts",
".",
"xspan",
"[",
"0",
"]",
"for",
"ts",
"in",
... | 45.1875 | 13.875 |
def add_errback(future, callback, loop=None):
'''Add a ``callback`` to a ``future`` executed only if an exception
or cancellation has occurred.'''
def _error_back(fut):
if fut._exception:
callback(fut.exception())
elif fut.cancelled():
callback(CancelledError())
... | [
"def",
"add_errback",
"(",
"future",
",",
"callback",
",",
"loop",
"=",
"None",
")",
":",
"def",
"_error_back",
"(",
"fut",
")",
":",
"if",
"fut",
".",
"_exception",
":",
"callback",
"(",
"fut",
".",
"exception",
"(",
")",
")",
"elif",
"fut",
".",
... | 34.166667 | 12.833333 |
def dump(archive, calc_id=0, user=None):
"""
Dump the openquake database and all the complete calculations into a zip
file. In a multiuser installation must be run as administrator.
"""
t0 = time.time()
assert archive.endswith('.zip'), archive
getfnames = 'select ds_calc_dir || ".hdf5" from ... | [
"def",
"dump",
"(",
"archive",
",",
"calc_id",
"=",
"0",
",",
"user",
"=",
"None",
")",
":",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"assert",
"archive",
".",
"endswith",
"(",
"'.zip'",
")",
",",
"archive",
"getfnames",
"=",
"'select ds_calc_dir || \... | 40 | 16.827586 |
def set_coords(self, x=0, y=0, z=0, t=0):
"""
set coords of agent in an arbitrary world
"""
self.coords = {}
self.coords['x'] = x
self.coords['y'] = y
self.coords['z'] = z
self.coords['t'] = t | [
"def",
"set_coords",
"(",
"self",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"z",
"=",
"0",
",",
"t",
"=",
"0",
")",
":",
"self",
".",
"coords",
"=",
"{",
"}",
"self",
".",
"coords",
"[",
"'x'",
"]",
"=",
"x",
"self",
".",
"coords",
"["... | 27.555556 | 8.222222 |
def _load_connection_error(hostname, error):
'''
Format and Return a connection error
'''
ret = {'code': None, 'content': 'Error: Unable to connect to the bigip device: {host}\n{error}'.format(host=hostname, error=error)}
return ret | [
"def",
"_load_connection_error",
"(",
"hostname",
",",
"error",
")",
":",
"ret",
"=",
"{",
"'code'",
":",
"None",
",",
"'content'",
":",
"'Error: Unable to connect to the bigip device: {host}\\n{error}'",
".",
"format",
"(",
"host",
"=",
"hostname",
",",
"error",
... | 30.875 | 33.875 |
def merkleroot(merkletree: 'MerkleTreeState') -> Locksroot:
""" Return the root element of the merkle tree. """
assert merkletree.layers, 'the merkle tree layers are empty'
assert merkletree.layers[MERKLEROOT], 'the root layer is empty'
return Locksroot(merkletree.layers[MERKLEROOT][0]) | [
"def",
"merkleroot",
"(",
"merkletree",
":",
"'MerkleTreeState'",
")",
"->",
"Locksroot",
":",
"assert",
"merkletree",
".",
"layers",
",",
"'the merkle tree layers are empty'",
"assert",
"merkletree",
".",
"layers",
"[",
"MERKLEROOT",
"]",
",",
"'the root layer is emp... | 49.833333 | 20.666667 |
def set_logfile(path, instance):
"""Specify logfile path"""
global logfile
logfile = os.path.normpath(path) + '/hfos.' + instance + '.log' | [
"def",
"set_logfile",
"(",
"path",
",",
"instance",
")",
":",
"global",
"logfile",
"logfile",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"+",
"'/hfos.'",
"+",
"instance",
"+",
"'.log'"
] | 29.4 | 19.4 |
def _create_syns(b, needed_syns):
"""
Create empty synthetics
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter list needed_syns: list of dictionaries containing kwargs to access
the dataset (dataset, component, kind)
:return: :class:`phoebe.parameters.parameters.Parameter... | [
"def",
"_create_syns",
"(",
"b",
",",
"needed_syns",
")",
":",
"# needs_mesh = {info['dataset']: info['kind'] for info in needed_syns if info['needs_mesh']}",
"params",
"=",
"[",
"]",
"for",
"needed_syn",
"in",
"needed_syns",
":",
"# print \"*** _create_syns needed_syn\", needed_... | 43.294118 | 26.196078 |
def alias_repository(self, repository_id, alias_id):
"""Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Repository`` is determined by the
provider. The new ``Id`` is an alias to the primary ``Id``. If
the alias is a pointer to an... | [
"def",
"alias_repository",
"(",
"self",
",",
"repository_id",
",",
"alias_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinLookupSession.alias_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_c... | 49 | 21.038462 |
def compile_model(self, input_model_config, output_model_config, role,
job_name, stop_condition, tags):
"""Create an Amazon SageMaker Neo compilation job.
Args:
input_model_config (dict): the trained model and the Amazon S3 location where it is stored.
outp... | [
"def",
"compile_model",
"(",
"self",
",",
"input_model_config",
",",
"output_model_config",
",",
"role",
",",
"job_name",
",",
"stop_condition",
",",
"tags",
")",
":",
"compilation_job_request",
"=",
"{",
"'InputConfig'",
":",
"input_model_config",
",",
"'OutputConf... | 50.727273 | 29.909091 |
def _set_prompt(self):
"""Set prompt so it displays the current working directory."""
self.cwd = os.getcwd()
self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET | [
"def",
"_set_prompt",
"(",
"self",
")",
":",
"self",
".",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"self",
".",
"prompt",
"=",
"Fore",
".",
"CYAN",
"+",
"'{!r} $ '",
".",
"format",
"(",
"self",
".",
"cwd",
")",
"+",
"Fore",
".",
"RESET"
] | 48.75 | 15.25 |
def create_tcp_monitor(self, topics, batch_size=1, batch_duration=0,
compression='gzip', format_type='json'):
"""Creates a TCP Monitor instance in Device Cloud for a given list of topics
:param topics: a string list of topics (e.g. ['DeviceCore[U]',
'FileDat... | [
"def",
"create_tcp_monitor",
"(",
"self",
",",
"topics",
",",
"batch_size",
"=",
"1",
",",
"batch_duration",
"=",
"0",
",",
"compression",
"=",
"'gzip'",
",",
"format_type",
"=",
"'json'",
")",
":",
"monitor_xml",
"=",
"\"\"\"\\\n <Monitor>\n <mo... | 43.555556 | 18.555556 |
def submit_sample(self, filepath, filename, tags=['TheHive']):
"""
Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param ... | [
"def",
"submit_sample",
"(",
"self",
",",
"filepath",
",",
"filename",
",",
"tags",
"=",
"[",
"'TheHive'",
"]",
")",
":",
"apiurl",
"=",
"'/rest/sample/submit?sample_file'",
"params",
"=",
"{",
"'sample_filename_b64enc'",
":",
"base64",
".",
"b64encode",
"(",
... | 43.133333 | 19.666667 |
def assign_edge_colors_and_widths(self):
"""
Resolve conflict of 'node_color' and 'node_style['fill'] args which are
redundant. Default is node_style.fill unless user entered node_color.
To enter multiple colors user must use node_color not style fill.
Either way, we build a lis... | [
"def",
"assign_edge_colors_and_widths",
"(",
"self",
")",
":",
"# node_color overrides fill. Tricky to catch cuz it can be many types.",
"# SET edge_widths and POP edge_style.stroke-width",
"if",
"self",
".",
"style",
".",
"edge_widths",
"is",
"None",
":",
"if",
"not",
"self",
... | 51.328571 | 22.642857 |
def list_subscriptions(self, target_id=None, ids=None, query_flags=None):
"""ListSubscriptions.
[Preview API]
:param str target_id:
:param [str] ids:
:param str query_flags:
:rtype: [NotificationSubscription]
"""
query_parameters = {}
if target_id ... | [
"def",
"list_subscriptions",
"(",
"self",
",",
"target_id",
"=",
"None",
",",
"ids",
"=",
"None",
",",
"query_flags",
"=",
"None",
")",
":",
"query_parameters",
"=",
"{",
"}",
"if",
"target_id",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'targetId... | 49.238095 | 20.571429 |
def euclidean(h1, h2): # 9 us @array, 33 us @list \w 100 bins
r"""
Equal to Minowski distance with :math:`p=2`.
See also
--------
minowski
"""
h1, h2 = __prepare_histogram(h1, h2)
return math.sqrt(scipy.sum(scipy.square(scipy.absolute(h1 - h2)))) | [
"def",
"euclidean",
"(",
"h1",
",",
"h2",
")",
":",
"# 9 us @array, 33 us @list \\w 100 bins",
"h1",
",",
"h2",
"=",
"__prepare_histogram",
"(",
"h1",
",",
"h2",
")",
"return",
"math",
".",
"sqrt",
"(",
"scipy",
".",
"sum",
"(",
"scipy",
".",
"square",
"... | 27.4 | 17.9 |
def get_vid_from_url(self, url):
"""Extracts video ID from live.qq.com.
"""
hit = re.search(r'live.qq.com/(\d+)', url)
if hit is not None:
return hit.group(1)
hit = re.search(r'live.qq.com/directory/match/(\d+)', url)
if hit is not None:
return sel... | [
"def",
"get_vid_from_url",
"(",
"self",
",",
"url",
")",
":",
"hit",
"=",
"re",
".",
"search",
"(",
"r'live.qq.com/(\\d+)'",
",",
"url",
")",
"if",
"hit",
"is",
"not",
"None",
":",
"return",
"hit",
".",
"group",
"(",
"1",
")",
"hit",
"=",
"re",
"."... | 37.714286 | 11.214286 |
def time_str (time_t, slug = False):
'''Converts floating point number a'la time.time()
using DEFAULT_TIMEFORMAT
'''
return datetime.fromtimestamp (int (time_t)).strftime (
DEFAULT_SLUGFORMAT if slug else DEFAULT_TIMEFORMAT) | [
"def",
"time_str",
"(",
"time_t",
",",
"slug",
"=",
"False",
")",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"time_t",
")",
")",
".",
"strftime",
"(",
"DEFAULT_SLUGFORMAT",
"if",
"slug",
"else",
"DEFAULT_TIMEFORMAT",
")"
] | 38.5 | 16.166667 |
def parse(self, fd):
"""very simple parser - but why would we want it to be complex?"""
def resolve_args(args):
# FIXME break this out, it's in common with the templating stuff elsewhere
root = self.sections[0]
val_dict = dict(('<' + t + '>', u) for (t, u) in root.ge... | [
"def",
"parse",
"(",
"self",
",",
"fd",
")",
":",
"def",
"resolve_args",
"(",
"args",
")",
":",
"# FIXME break this out, it's in common with the templating stuff elsewhere",
"root",
"=",
"self",
".",
"sections",
"[",
"0",
"]",
"val_dict",
"=",
"dict",
"(",
"(",
... | 40.49635 | 16.394161 |
def _wait_for_any_event(events, timeout_s):
"""Wait for any in a list of threading.Event's to be set.
Args:
events: List of threading.Event's.
timeout_s: Max duration in seconds to wait before returning.
Returns:
True if at least one event was set before the timeout expired, else False.
"""
de... | [
"def",
"_wait_for_any_event",
"(",
"events",
",",
"timeout_s",
")",
":",
"def",
"any_event_set",
"(",
")",
":",
"return",
"any",
"(",
"event",
".",
"is_set",
"(",
")",
"for",
"event",
"in",
"events",
")",
"result",
"=",
"timeouts",
".",
"loop_until_timeout... | 30.941176 | 21.176471 |
def FUNCTIONNOPROTO(self, _cursor_type):
"""Handles function with no prototype."""
# id, returns, attributes
returns = _cursor_type.get_result()
# if self.is_fundamental_type(returns):
returns = self.parse_cursor_type(returns)
attributes = []
obj = typedesc.Functi... | [
"def",
"FUNCTIONNOPROTO",
"(",
"self",
",",
"_cursor_type",
")",
":",
"# id, returns, attributes",
"returns",
"=",
"_cursor_type",
".",
"get_result",
"(",
")",
"# if self.is_fundamental_type(returns):",
"returns",
"=",
"self",
".",
"parse_cursor_type",
"(",
"returns",
... | 40.636364 | 8.909091 |
def replace_name_with_id(cls, name):
"""
Used to replace a foreign key reference using a name with an ID. Works by searching the
record in Pulsar and expects to find exactly one hit. First, will check if the foreign key
reference is an integer value and if so, returns that as it is presu... | [
"def",
"replace_name_with_id",
"(",
"cls",
",",
"name",
")",
":",
"try",
":",
"int",
"(",
"name",
")",
"return",
"name",
"#Already a presumed ID.",
"except",
"ValueError",
":",
"pass",
"#Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8.",
"if",
... | 48.04 | 28.6 |
def append(self, vals: list, index=None):
"""
Append a row to the main dataframe
:param vals: list of the row values to add
:type vals: list
:param index: index key, defaults to None
:param index: any, optional
:example: ``ds.append([0, 2, 2, 3, 4])``
""... | [
"def",
"append",
"(",
"self",
",",
"vals",
":",
"list",
",",
"index",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"df",
"=",
"self",
".",
"df",
".",
"loc",
"[",
"len",
"(",
"self",
".",
"df",
".",
"index",
")",
"]",
"=",
"vals",
"except",... | 31.176471 | 13.529412 |
def liveReceivers(receivers):
"""Filter sequence of receivers to get resolved, live receivers
This is a generator which will iterate over
the passed sequence, checking for weak references
and resolving them, then returning all live
receivers.
"""
for receiver in receivers:
if isinst... | [
"def",
"liveReceivers",
"(",
"receivers",
")",
":",
"for",
"receiver",
"in",
"receivers",
":",
"if",
"isinstance",
"(",
"receiver",
",",
"WEAKREF_TYPES",
")",
":",
"# Dereference the weak reference.",
"receiver",
"=",
"receiver",
"(",
")",
"if",
"receiver",
"is"... | 32.8125 | 11.8125 |
def record_set_absent(name, zone_name, resource_group, connection_auth=None):
'''
.. versionadded:: Fluorine
Ensure a record set does not exist in the DNS zone.
:param name:
Name of the record set.
:param zone_name:
Name of the DNS zone.
:param resource_group:
The res... | [
"def",
"record_set_absent",
"(",
"name",
",",
"zone_name",
",",
"resource_group",
",",
"connection_auth",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{... | 26.815385 | 25.738462 |
def del_doc(self, doc):
"""
Delete a document
"""
logger.info("Removing doc from the index: %s" % doc)
doc = doc.clone() # make sure it can be serialized safely
self.docsearch.index.del_doc(doc) | [
"def",
"del_doc",
"(",
"self",
",",
"doc",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing doc from the index: %s\"",
"%",
"doc",
")",
"doc",
"=",
"doc",
".",
"clone",
"(",
")",
"# make sure it can be serialized safely",
"self",
".",
"docsearch",
".",
"index... | 33.857143 | 11.285714 |
def set_beam_prop(self, prop, values, repeat="up"):
"""
Specify the properties of the beams
:param values:
:param repeat: if 'up' then duplicate up the structure
:return:
"""
values = np.array(values)
if repeat == "up":
assert len(values.shape... | [
"def",
"set_beam_prop",
"(",
"self",
",",
"prop",
",",
"values",
",",
"repeat",
"=",
"\"up\"",
")",
":",
"values",
"=",
"np",
".",
"array",
"(",
"values",
")",
"if",
"repeat",
"==",
"\"up\"",
":",
"assert",
"len",
"(",
"values",
".",
"shape",
")",
... | 37.684211 | 14.421053 |
def assert_text_visible(self, text, selector="html", by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Same as assert_text() """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return self.... | [
"def",
"assert_text_visible",
"(",
"self",
",",
"text",
",",
"selector",
"=",
"\"html\"",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"SMALL_TIMEOUT",
")",
":",
"if",
"self",
".",
"timeout_multiplier",
"and",
"timeout",
... | 61 | 21.5 |
def cleanup_all(data_home=None):
"""
Cleans up all the example datasets in the data directory specified by
``get_data_home`` either to clear up disk space or start from fresh.
"""
removed = 0
for name, meta in DATASETS.items():
_, ext = os.path.splitext(meta['url'])
removed += cl... | [
"def",
"cleanup_all",
"(",
"data_home",
"=",
"None",
")",
":",
"removed",
"=",
"0",
"for",
"name",
",",
"meta",
"in",
"DATASETS",
".",
"items",
"(",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"meta",
"[",
"'url'",
"]... | 35.538462 | 22 |
def connected_components(graph):
"""
Connected components.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: dictionary
@return: Pairing that associates each node to its connected component.
"""
recursionlimit = getrecursionlimit()
setrecursionlimit(max(len(graph.nodes(... | [
"def",
"connected_components",
"(",
"graph",
")",
":",
"recursionlimit",
"=",
"getrecursionlimit",
"(",
")",
"setrecursionlimit",
"(",
"max",
"(",
"len",
"(",
"graph",
".",
"nodes",
"(",
")",
")",
"*",
"2",
",",
"recursionlimit",
")",
")",
"visited",
"=",
... | 26.12 | 19.88 |
def get_file(self):
"""
Load data into a file and return file path.
:return: path to file as string
"""
content = self._load()
if not content:
return None
filename = "temporary_file.bin"
with open(filename, "wb") as file_name:
file... | [
"def",
"get_file",
"(",
"self",
")",
":",
"content",
"=",
"self",
".",
"_load",
"(",
")",
"if",
"not",
"content",
":",
"return",
"None",
"filename",
"=",
"\"temporary_file.bin\"",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"file_name",
":... | 27.076923 | 11.230769 |
def past_date(start='-30d'):
"""
Returns a ``date`` object in the past between 1 day ago and the
specified ``start``. ``start`` can be a string, another date, or a
timedelta. If it's a string, it must start with `-`, followed by and integer
and a unit, Eg: ``'-30d'``. Defaults to `'-30d'`
Valid... | [
"def",
"past_date",
"(",
"start",
"=",
"'-30d'",
")",
":",
"return",
"lambda",
"n",
",",
"f",
":",
"f",
".",
"past_date",
"(",
"start_date",
"=",
"start",
",",
"tzinfo",
"=",
"get_timezone",
"(",
")",
",",
")"
] | 32.166667 | 17.166667 |
def delete_pool(hostname, username, password, name):
'''
Delete an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool which will be deleted
'''
re... | [
"def",
"delete_pool",
"(",
"hostname",
",",
"username",
",",
"password",
",",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"if",
"__opts__"... | 27.735849 | 20.830189 |
def p_block(self, p):
'block : BEGIN block_statements END'
p[0] = Block(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_block",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Block",
"(",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",... | 36.75 | 8.25 |
def _cleanupConnections(senderkey, signal):
"""Delete any empty signals for senderkey. Delete senderkey if empty."""
try:
receivers = connections[senderkey][signal]
except:
pass
else:
if not receivers:
# No more connected receivers. Therefore, remove the signal.
... | [
"def",
"_cleanupConnections",
"(",
"senderkey",
",",
"signal",
")",
":",
"try",
":",
"receivers",
"=",
"connections",
"[",
"senderkey",
"]",
"[",
"signal",
"]",
"except",
":",
"pass",
"else",
":",
"if",
"not",
"receivers",
":",
"# No more connected receivers. ... | 34.666667 | 18 |
def add_hierarchy(self, parent, edge, child): # XXX DEPRECATED
""" Helper function to simplify the addition of part_of style
objectProperties to graphs. FIXME make a method of makeGraph?
"""
if type(parent) != rdflib.URIRef:
parent = self.check_thing(parent)
if ... | [
"def",
"add_hierarchy",
"(",
"self",
",",
"parent",
",",
"edge",
",",
"child",
")",
":",
"# XXX DEPRECATED",
"if",
"type",
"(",
"parent",
")",
"!=",
"rdflib",
".",
"URIRef",
":",
"parent",
"=",
"self",
".",
"check_thing",
"(",
"parent",
")",
"if",
"typ... | 42.705882 | 16.941176 |
def connect(jclassname, url, driver_args=None, jars=None, libs=None):
"""Open a connection to a database using a JDBC driver and return
a Connection instance.
jclassname: Full qualified Java class name of the JDBC driver.
url: Database url as required by the JDBC driver.
driver_args: Dictionary or ... | [
"def",
"connect",
"(",
"jclassname",
",",
"url",
",",
"driver_args",
"=",
"None",
",",
"jars",
"=",
"None",
",",
"libs",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"driver_args",
",",
"string_type",
")",
":",
"driver_args",
"=",
"[",
"driver_args",
... | 40.333333 | 18.515152 |
def verify_id(ctx, param, app):
"""Verify the experiment id."""
if app is None:
raise TypeError("Select an experiment using the --app parameter.")
elif app[0:5] == "dlgr-":
raise ValueError(
"The --app parameter requires the full "
"UUID beginning with {}-...".format(... | [
"def",
"verify_id",
"(",
"ctx",
",",
"param",
",",
"app",
")",
":",
"if",
"app",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Select an experiment using the --app parameter.\"",
")",
"elif",
"app",
"[",
"0",
":",
"5",
"]",
"==",
"\"dlgr-\"",
":",
"rais... | 34.6 | 17.7 |
def profile_package(self):
"""Returns memory stats for a package."""
target_modules = base_profiler.get_pkg_module_names(self._run_object)
try:
with _CodeEventsTracker(target_modules) as prof:
prof.compute_mem_overhead()
runpy.run_path(self._run_object... | [
"def",
"profile_package",
"(",
"self",
")",
":",
"target_modules",
"=",
"base_profiler",
".",
"get_pkg_module_names",
"(",
"self",
".",
"_run_object",
")",
"try",
":",
"with",
"_CodeEventsTracker",
"(",
"target_modules",
")",
"as",
"prof",
":",
"prof",
".",
"c... | 40.3 | 18.4 |
def authed_post(self, url, data, response_code=200, follow=False,
headers={}):
"""Does a django test client ``post`` against the given url after
logging in the admin first.
:param url:
URL to fetch
:param data:
Dictionary to form contents to post
... | [
"def",
"authed_post",
"(",
"self",
",",
"url",
",",
"data",
",",
"response_code",
"=",
"200",
",",
"follow",
"=",
"False",
",",
"headers",
"=",
"{",
"}",
")",
":",
"if",
"not",
"self",
".",
"authed",
":",
"self",
".",
"authorize",
"(",
")",
"respon... | 35.695652 | 17.521739 |
def cronitor(self):
"""Wrap run with requests to cronitor."""
url = f'https://cronitor.link/{self.opts.cronitor}/{{}}'
try:
run_url = url.format('run')
self.logger.debug(f'Pinging {run_url}')
requests.get(run_url, timeout=self.opts.timeout)
except re... | [
"def",
"cronitor",
"(",
"self",
")",
":",
"url",
"=",
"f'https://cronitor.link/{self.opts.cronitor}/{{}}'",
"try",
":",
"run_url",
"=",
"url",
".",
"format",
"(",
"'run'",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"f'Pinging {run_url}'",
")",
"requests",
... | 34.76 | 20.96 |
def register_with_password(self, username, password):
""" Register for a new account on this HS.
Args:
username (str): Account username
password (str): Account password
Returns:
str: Access Token
Raises:
MatrixRequestError
"""
... | [
"def",
"register_with_password",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"register",
"(",
"auth_body",
"=",
"{",
"\"type\"",
":",
"\"m.login.dummy\"",
"}",
",",
"kind",
"=",
"'user'",
",",
"usernam... | 27.35 | 15.8 |
def prev(self):
"""Get the previous segment."""
seg = Segment(segment_t=idaapi.get_prev_seg(self.ea))
if seg.ea >= self.ea:
raise exceptions.NoMoreSegments("This is the first segment. no segments exist before it.")
return seg | [
"def",
"prev",
"(",
"self",
")",
":",
"seg",
"=",
"Segment",
"(",
"segment_t",
"=",
"idaapi",
".",
"get_prev_seg",
"(",
"self",
".",
"ea",
")",
")",
"if",
"seg",
".",
"ea",
">=",
"self",
".",
"ea",
":",
"raise",
"exceptions",
".",
"NoMoreSegments",
... | 33 | 27.625 |
def _assign_value(self, pbuf_dp, value):
"""Assigns a value to the protobuf obj"""
self._assign_value_by_type(pbuf_dp, value, _bool=False,
error_prefix='Invalid value') | [
"def",
"_assign_value",
"(",
"self",
",",
"pbuf_dp",
",",
"value",
")",
":",
"self",
".",
"_assign_value_by_type",
"(",
"pbuf_dp",
",",
"value",
",",
"_bool",
"=",
"False",
",",
"error_prefix",
"=",
"'Invalid value'",
")"
] | 54 | 11.75 |
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
"""Signs a Ed25519Fulfillment.
Args:
input_ (:class:`~bigchaindb.common.transaction.
Input`) The input to be signed.
message (str): The message to be signed
k... | [
"def",
"_sign_simple_signature_fulfillment",
"(",
"cls",
",",
"input_",
",",
"message",
",",
"key_pairs",
")",
":",
"# NOTE: To eliminate the dangers of accidentally signing a condition by",
"# reference, we remove the reference of input_ here",
"# intentionally. If the user ... | 48.633333 | 22.333333 |
def taper(self, side='leftright'):
"""Taper the ends of this `TimeSeries` smoothly to zero.
Parameters
----------
side : `str`, optional
the side of the `TimeSeries` to taper, must be one of `'left'`,
`'right'`, or `'leftright'`
Returns
-------
... | [
"def",
"taper",
"(",
"self",
",",
"side",
"=",
"'leftright'",
")",
":",
"# check window properties",
"if",
"side",
"not",
"in",
"(",
"'left'",
",",
"'right'",
",",
"'leftright'",
")",
":",
"raise",
"ValueError",
"(",
"\"side must be one of 'left', 'right', \"",
... | 35.939394 | 20.681818 |
def get_all_templates(self, params=None):
"""
Get all templates
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_templates",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"self",
".",
"get_templates_per_page",
",",
"resource",
"=",
"TEMPLATES"... | 38.333333 | 22 |
def init(paths, output, **kwargs):
"""Init data package from list of files.
It will also infer tabular data's schemas from their contents.
"""
dp = goodtables.init_datapackage(paths)
click.secho(
json_module.dumps(dp.descriptor, indent=4),
file=output
)
exit(dp.valid) | [
"def",
"init",
"(",
"paths",
",",
"output",
",",
"*",
"*",
"kwargs",
")",
":",
"dp",
"=",
"goodtables",
".",
"init_datapackage",
"(",
"paths",
")",
"click",
".",
"secho",
"(",
"json_module",
".",
"dumps",
"(",
"dp",
".",
"descriptor",
",",
"indent",
... | 23.307692 | 20.615385 |
def _generate_filenames(sources):
"""Generate filenames.
:param tuple sources: Sequence of strings representing path to file(s).
:return: Path to file(s).
:rtype: :py:class:`str`
"""
for source in sources:
if os.path.isdir(source):
for path, dirlist, filelist in os.walk(so... | [
"def",
"_generate_filenames",
"(",
"sources",
")",
":",
"for",
"source",
"in",
"sources",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source",
")",
":",
"for",
"path",
",",
"dirlist",
",",
"filelist",
"in",
"os",
".",
"walk",
"(",
"source",
")"... | 33.731707 | 19.512195 |
def remove_major_minor_suffix(scripts):
"""Checks if executables already contain a "-MAJOR.MINOR" suffix. """
minor_major_regex = re.compile("-\d.?\d?$")
return [x for x in scripts if not minor_major_regex.search(x)] | [
"def",
"remove_major_minor_suffix",
"(",
"scripts",
")",
":",
"minor_major_regex",
"=",
"re",
".",
"compile",
"(",
"\"-\\d.?\\d?$\"",
")",
"return",
"[",
"x",
"for",
"x",
"in",
"scripts",
"if",
"not",
"minor_major_regex",
".",
"search",
"(",
"x",
")",
"]"
] | 56.25 | 8.5 |
def initialize(cls) -> None:
"""Initializes the ``SIGCHLD`` handler.
The signal handler is run on an `.IOLoop` to avoid locking issues.
Note that the `.IOLoop` used for signal handling need not be the
same one used by individual Subprocess objects (as long as the
``IOLoops`` are... | [
"def",
"initialize",
"(",
"cls",
")",
"->",
"None",
":",
"if",
"cls",
".",
"_initialized",
":",
"return",
"io_loop",
"=",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
"cls",
".",
"_old_sigchld",
"=",
"signal",
".",
"signal",
"(",
"signal",
".",
... | 35.636364 | 20.545455 |
def get_Mapping_key_value(mp):
"""Retrieves the key and value types from a PEP 484 mapping or subclass of such.
mp must be a (subclass of) typing.Mapping.
"""
try:
res = _select_Generic_superclass_parameters(mp, typing.Mapping)
except TypeError:
res = None
if res is None:
... | [
"def",
"get_Mapping_key_value",
"(",
"mp",
")",
":",
"try",
":",
"res",
"=",
"_select_Generic_superclass_parameters",
"(",
"mp",
",",
"typing",
".",
"Mapping",
")",
"except",
"TypeError",
":",
"res",
"=",
"None",
"if",
"res",
"is",
"None",
":",
"raise",
"T... | 33.5 | 17.583333 |
def FetchRequestsAndResponses(self, session_id, timestamp=None):
"""Fetches all outstanding requests and responses for this flow.
We first cache all requests and responses for this flow in memory to
prevent round trips.
Args:
session_id: The session_id to get the requests/responses for.
ti... | [
"def",
"FetchRequestsAndResponses",
"(",
"self",
",",
"session_id",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"(",
"0",
",",
"self",
".",
"frozen_timestamp",
"or",
"rdfvalue",
".",
"RDFDatetime",
".",
... | 34.121212 | 22.212121 |
def auto_init_default(column):
"""
Set the default value for a column when it's first accessed rather than
first committed to the database.
"""
if isinstance(column, ColumnProperty):
default = column.columns[0].default
else:
default = column.default
@event.listens_for(column... | [
"def",
"auto_init_default",
"(",
"column",
")",
":",
"if",
"isinstance",
"(",
"column",
",",
"ColumnProperty",
")",
":",
"default",
"=",
"column",
".",
"columns",
"[",
"0",
"]",
".",
"default",
"else",
":",
"default",
"=",
"column",
".",
"default",
"@",
... | 37.772727 | 16.318182 |
def retrieve_object_from_file(file_name, save_key, file_location):
"""
Function to retrieve objects from a shelve
Args:
file_name: Shelve storage file name
save_key: The name of the key the item is stored in
file_location: The location of the file, derive from the os module
Retu... | [
"def",
"retrieve_object_from_file",
"(",
"file_name",
",",
"save_key",
",",
"file_location",
")",
":",
"shelve_store",
"=",
"None",
"file",
"=",
"__os",
".",
"path",
".",
"join",
"(",
"file_location",
",",
"file_name",
")",
"try",
":",
"shelve_store",
"=",
"... | 36.52381 | 19.47619 |
def stretch(arr, fields=None, return_indices=False):
"""Stretch an array.
Stretch an array by ``hstack()``-ing multiple array fields while
preserving column names and record array structure. If a scalar field is
specified, it will be stretched along with array fields.
Parameters
----------
... | [
"def",
"stretch",
"(",
"arr",
",",
"fields",
"=",
"None",
",",
"return_indices",
"=",
"False",
")",
":",
"dtype",
"=",
"[",
"]",
"len_array",
"=",
"None",
"flatten",
"=",
"False",
"if",
"fields",
"is",
"None",
":",
"fields",
"=",
"arr",
".",
"dtype",... | 34.226804 | 19.185567 |
def load_extra_data(cls, data):
"""Loads extra JSON configuration parameters from a data buffer.
The data buffer must represent a JSON object.
Args:
data: str, the buffer to load the JSON data from.
"""
try:
cls._extra_config.update(json.loads(data))
except ValueError as exception:... | [
"def",
"load_extra_data",
"(",
"cls",
",",
"data",
")",
":",
"try",
":",
"cls",
".",
"_extra_config",
".",
"update",
"(",
"json",
".",
"loads",
"(",
"data",
")",
")",
"except",
"ValueError",
"as",
"exception",
":",
"sys",
".",
"stderr",
".",
"write",
... | 30.461538 | 19 |
def nin(self, qfield, *values):
''' Works the same as the query expression method ``nin_``
'''
self.__query_obj.nin(qfield, *values)
return self | [
"def",
"nin",
"(",
"self",
",",
"qfield",
",",
"*",
"values",
")",
":",
"self",
".",
"__query_obj",
".",
"nin",
"(",
"qfield",
",",
"*",
"values",
")",
"return",
"self"
] | 34.4 | 18 |
def select(self, name_or_index):
"""Locate a dataset.
Args::
name_or_index dataset name or index number
Returns::
SDS instance for the dataset
C library equivalent : SDselect
"""
if isi... | [
"def",
"select",
"(",
"self",
",",
"name_or_index",
")",
":",
"if",
"isinstance",
"(",
"name_or_index",
",",
"type",
"(",
"1",
")",
")",
":",
"idx",
"=",
"name_or_index",
"else",
":",
"try",
":",
"idx",
"=",
"self",
".",
"nametoindex",
"(",
"name_or_in... | 27.458333 | 18.666667 |
def drill_filter(esfilter, data):
"""
PARTIAL EVALUATE THE FILTER BASED ON DATA GIVEN
TODO: FIX THIS MONUMENALLY BAD IDEA
"""
esfilter = unwrap(esfilter)
primary_nested = [] # track if nested, changes if not
primary_column = [] # only one path allowed
primary_branch = (
[]
... | [
"def",
"drill_filter",
"(",
"esfilter",
",",
"data",
")",
":",
"esfilter",
"=",
"unwrap",
"(",
"esfilter",
")",
"primary_nested",
"=",
"[",
"]",
"# track if nested, changes if not",
"primary_column",
"=",
"[",
"]",
"# only one path allowed",
"primary_branch",
"=",
... | 32.457875 | 14.355311 |
def search(**criteria):
"""
Search registered *component* classes matching the given criteria.
:param criteria: search criteria of the form: ``a='1', b='x'``
:return: parts registered with the given criteria
:rtype: :class:`set`
Will return an empty :class:`set` if nothing is found.
::
... | [
"def",
"search",
"(",
"*",
"*",
"criteria",
")",
":",
"# Find all parts that match the given criteria",
"results",
"=",
"copy",
"(",
"class_list",
")",
"# start with full list",
"for",
"(",
"category",
",",
"value",
")",
"in",
"criteria",
".",
"items",
"(",
")",... | 31.137931 | 19.62069 |
def add_grid(self):
"""Add axis and ticks to figure.
Notes
-----
I know that visvis and pyqtgraphs can do this in much simpler way, but
those packages create too large a padding around the figure and this is
pretty fast.
"""
value = self.config.value
... | [
"def",
"add_grid",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"config",
".",
"value",
"# X-AXIS",
"# x-bottom",
"self",
".",
"scene",
".",
"addLine",
"(",
"value",
"[",
"'x_min'",
"]",
",",
"value",
"[",
"'y_min'",
"]",
",",
"value",
"[",
"'x_... | 43.25 | 18.1875 |
def initHldyDates(self):
""" Initialize holidays :class:`~ekmmeters.SerialBlock` """
self.m_hldy["reserved_20"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_hldy["Holiday_1_Mon"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_hldy["Holiday_1_Day"] = [2, F... | [
"def",
"initHldyDates",
"(",
"self",
")",
":",
"self",
".",
"m_hldy",
"[",
"\"reserved_20\"",
"]",
"=",
"[",
"6",
",",
"FieldType",
".",
"Hex",
",",
"ScaleType",
".",
"No",
",",
"\"\"",
",",
"0",
",",
"False",
",",
"False",
"]",
"self",
".",
"m_hld... | 87.729167 | 49 |
def nutation(date, eop_correction=True, terms=106): # pragma: no cover
"""Nutation as a rotation matrix
"""
epsilon_bar, delta_psi, delta_eps = np.deg2rad(_nutation(date, eop_correction, terms))
epsilon = epsilon_bar + delta_eps
return rot1(-epsilon_bar) @ rot3(delta_psi) @ rot1(epsilon) | [
"def",
"nutation",
"(",
"date",
",",
"eop_correction",
"=",
"True",
",",
"terms",
"=",
"106",
")",
":",
"# pragma: no cover",
"epsilon_bar",
",",
"delta_psi",
",",
"delta_eps",
"=",
"np",
".",
"deg2rad",
"(",
"_nutation",
"(",
"date",
",",
"eop_correction",
... | 43.428571 | 21 |
def process_whitelists():
"""Download approved top 1M lists."""
import csv
import grequests
import os
import StringIO
import zipfile
mapping = {
'http://s3.amazonaws.com/alexa-static/top-1m.csv.zip': {
'name': 'alexa.txt'
}, 'http://s3-us-west-1.amazonaws.com/umbr... | [
"def",
"process_whitelists",
"(",
")",
":",
"import",
"csv",
"import",
"grequests",
"import",
"os",
"import",
"StringIO",
"import",
"zipfile",
"mapping",
"=",
"{",
"'http://s3.amazonaws.com/alexa-static/top-1m.csv.zip'",
":",
"{",
"'name'",
":",
"'alexa.txt'",
"}",
... | 34 | 19.28125 |
def point_on_line(point, line_start, line_end, accuracy=50.):
"""Checks whether a point lies on a line
The function checks whether the point "point" (P) lies on the line defined by its starting point line_start (A) and
its end point line_end (B).
This is done by comparing the distance of [AB] with the ... | [
"def",
"point_on_line",
"(",
"point",
",",
"line_start",
",",
"line_end",
",",
"accuracy",
"=",
"50.",
")",
":",
"length",
"=",
"dist",
"(",
"line_start",
",",
"line_end",
")",
"ds",
"=",
"length",
"/",
"float",
"(",
"accuracy",
")",
"if",
"-",
"ds",
... | 54.15 | 29.8 |
def _downgrade_v3(op):
"""
Downgrade assets db by adding a not null constraint on
``equities.first_traded``
"""
op.create_table(
'_new_equities',
sa.Column(
'sid',
sa.Integer,
unique=True,
nullable=False,
primary_key=True,
... | [
"def",
"_downgrade_v3",
"(",
"op",
")",
":",
"op",
".",
"create_table",
"(",
"'_new_equities'",
",",
"sa",
".",
"Column",
"(",
"'sid'",
",",
"sa",
".",
"Integer",
",",
"unique",
"=",
"True",
",",
"nullable",
"=",
"False",
",",
"primary_key",
"=",
"True... | 29.644444 | 15.088889 |
def node_from_ini(ini_file, nodefactory=Node, root_name='ini'):
"""
Convert a .ini file into a Node object.
:param ini_file: a filename or a file like object in read mode
"""
fileobj = open(ini_file) if isinstance(ini_file, str) else ini_file
cfp = configparser.RawConfigParser()
cfp.read_fi... | [
"def",
"node_from_ini",
"(",
"ini_file",
",",
"nodefactory",
"=",
"Node",
",",
"root_name",
"=",
"'ini'",
")",
":",
"fileobj",
"=",
"open",
"(",
"ini_file",
")",
"if",
"isinstance",
"(",
"ini_file",
",",
"str",
")",
"else",
"ini_file",
"cfp",
"=",
"confi... | 34.066667 | 13 |
def as_list(self):
"""
returns a list version of the object, based on it's attributes
"""
if hasattr(self, 'cust_list'):
return self.cust_list
if hasattr(self, 'attr_check'):
self.attr_check()
cls_bltns = set(dir(self.__class__))
r... | [
"def",
"as_list",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'cust_list'",
")",
":",
"return",
"self",
".",
"cust_list",
"if",
"hasattr",
"(",
"self",
",",
"'attr_check'",
")",
":",
"self",
".",
"attr_check",
"(",
")",
"cls_bltns",
"=",... | 36.363636 | 12.363636 |
def get_group(self, group_descriptor):
"""GetGroup.
[Preview API] Get a group by its descriptor.
:param str group_descriptor: The descriptor of the desired graph group.
:rtype: :class:`<GraphGroup> <azure.devops.v5_0.graph.models.GraphGroup>`
"""
route_values = {}
... | [
"def",
"get_group",
"(",
"self",
",",
"group_descriptor",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"group_descriptor",
"is",
"not",
"None",
":",
"route_values",
"[",
"'groupDescriptor'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'group_des... | 53.642857 | 19.571429 |
def search_results_last_url(html, xpath, label):
""" Get the URL of the 'last' button in a search results listing. """
for container in html.findall(xpath):
if container.text_content().strip() == label:
return container.find('.//a').get('href') | [
"def",
"search_results_last_url",
"(",
"html",
",",
"xpath",
",",
"label",
")",
":",
"for",
"container",
"in",
"html",
".",
"findall",
"(",
"xpath",
")",
":",
"if",
"container",
".",
"text_content",
"(",
")",
".",
"strip",
"(",
")",
"==",
"label",
":",... | 53.6 | 7 |
def query_lookupd(self):
"""
Trigger a query of the configured ``nsq_lookupd_http_addresses``.
"""
endpoint = self.lookupd_http_addresses[self.lookupd_query_index]
self.lookupd_query_index = (self.lookupd_query_index + 1) % len(self.lookupd_http_addresses)
# urlsplit() i... | [
"def",
"query_lookupd",
"(",
"self",
")",
":",
"endpoint",
"=",
"self",
".",
"lookupd_http_addresses",
"[",
"self",
".",
"lookupd_query_index",
"]",
"self",
".",
"lookupd_query_index",
"=",
"(",
"self",
".",
"lookupd_query_index",
"+",
"1",
")",
"%",
"len",
... | 41.785714 | 22 |
def rnni(self, times=1, **kwargs):
""" Applies a NNI operation on a randomly chosen edge.
keyword args: use_weighted_choice (True/False) weight the random edge selection by edge length
transform (callable) transforms the edges using this function, prior to weighted selection
... | [
"def",
"rnni",
"(",
"self",
",",
"times",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"nni",
"=",
"NNI",
"(",
"self",
".",
"copy",
"(",
")",
")",
"for",
"_",
"in",
"range",
"(",
"times",
")",
":",
"nni",
".",
"rnni",
"(",
"*",
"*",
"kwargs... | 41.909091 | 21.818182 |
def recv(self):
"""
Receive a message from the other end. Returns a tuple of the
command (a string) and payload (a list).
"""
# See if we have a message to process...
if self._recvbuf:
return self._recvbuf_pop()
# If it's closed, don't try to read m... | [
"def",
"recv",
"(",
"self",
")",
":",
"# See if we have a message to process...",
"if",
"self",
".",
"_recvbuf",
":",
"return",
"self",
".",
"_recvbuf_pop",
"(",
")",
"# If it's closed, don't try to read more data",
"if",
"not",
"self",
".",
"_sock",
":",
"raise",
... | 32.877193 | 16.45614 |
def safe_sum(x, alt_value=-np.inf, name=None):
"""Elementwise adds list members, replacing non-finite results with alt_value.
Typically the `alt_value` is chosen so the `MetropolisHastings`
`TransitionKernel` always rejects the proposal.
Args:
x: Python `list` of `Tensors` to elementwise add.
alt_valu... | [
"def",
"safe_sum",
"(",
"x",
",",
"alt_value",
"=",
"-",
"np",
".",
"inf",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'safe_sum'",
",",
"[",
"x",
",",
"alt_value",
"]",
")",
... | 37.382353 | 18.882353 |
def _get_element(name, element_type, server=None, with_properties=True):
'''
Get an element with or without properties
'''
element = {}
name = quote(name, safe='')
data = _api_get('{0}/{1}'.format(element_type, name), server)
# Format data, get properties if asked, and return the whole thin... | [
"def",
"_get_element",
"(",
"name",
",",
"element_type",
",",
"server",
"=",
"None",
",",
"with_properties",
"=",
"True",
")",
":",
"element",
"=",
"{",
"}",
"name",
"=",
"quote",
"(",
"name",
",",
"safe",
"=",
"''",
")",
"data",
"=",
"_api_get",
"("... | 37.625 | 23 |
def check_validity(self):
"""
Raise an error if any invalid attribute found.
Raises
------
TypeError
If an attribute has an invalid type.
ValueError
If an attribute has an invalid value (of the correct type).
"""
# tracks
... | [
"def",
"check_validity",
"(",
"self",
")",
":",
"# tracks",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"if",
"not",
"isinstance",
"(",
"track",
",",
"Track",
")",
":",
"raise",
"TypeError",
"(",
"\"`tracks` must be a list of \"",
"\"`pypianoroll.Track` in... | 42.159091 | 18.659091 |
def checkValue(self,value,strict=0):
"""Check and convert a parameter value.
Raises an exception if the value is not permitted for this
parameter. Otherwise returns the value (converted to the
right type.)
"""
v = self._coerceValue(value,strict)
return self.chec... | [
"def",
"checkValue",
"(",
"self",
",",
"value",
",",
"strict",
"=",
"0",
")",
":",
"v",
"=",
"self",
".",
"_coerceValue",
"(",
"value",
",",
"strict",
")",
"return",
"self",
".",
"checkOneValue",
"(",
"v",
",",
"strict",
")"
] | 36.777778 | 13.444444 |
def visit_object(self, node):
"""Fallback rendering for objects.
If the current application is in debug-mode
(``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment
-->`` will be rendered, indicating which class is missing a visitation
function.
Outside of deb... | [
"def",
"visit_object",
"(",
"self",
",",
"node",
")",
":",
"if",
"current_app",
".",
"debug",
":",
"return",
"tags",
".",
"comment",
"(",
"'no implementation in {} to render {}'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"node",
".... | 37.533333 | 19.066667 |
def zeldovich(dim=2, N=256, n=-2.5, t=None, scale=1, seed=None):
"""Creates a zeldovich DataFrame.
"""
import vaex.file
return vaex.file.other.Zeldovich(dim=dim, N=N, n=n, t=t, scale=scale) | [
"def",
"zeldovich",
"(",
"dim",
"=",
"2",
",",
"N",
"=",
"256",
",",
"n",
"=",
"-",
"2.5",
",",
"t",
"=",
"None",
",",
"scale",
"=",
"1",
",",
"seed",
"=",
"None",
")",
":",
"import",
"vaex",
".",
"file",
"return",
"vaex",
".",
"file",
".",
... | 40.2 | 15.4 |
def freeze(self, dest_dir):
"""Freezes every resource within a context"""
for resource in self.resources():
if resource.present:
resource.freeze(dest_dir) | [
"def",
"freeze",
"(",
"self",
",",
"dest_dir",
")",
":",
"for",
"resource",
"in",
"self",
".",
"resources",
"(",
")",
":",
"if",
"resource",
".",
"present",
":",
"resource",
".",
"freeze",
"(",
"dest_dir",
")"
] | 38.8 | 4.6 |
def get_subdomain(url):
"""Get the subdomain of the given URL.
Args:
url (str): The URL to get the subdomain from.
Returns:
str: The subdomain(s)
"""
if url not in URLHelper.__cache:
URLHelper.__cache[url] = urlparse(url)
return ".... | [
"def",
"get_subdomain",
"(",
"url",
")",
":",
"if",
"url",
"not",
"in",
"URLHelper",
".",
"__cache",
":",
"URLHelper",
".",
"__cache",
"[",
"url",
"]",
"=",
"urlparse",
"(",
"url",
")",
"return",
"\".\"",
".",
"join",
"(",
"URLHelper",
".",
"__cache",
... | 23.933333 | 22.133333 |
def _connect(self):
"Wrap the socket with SSL support"
sock = super(SSLConnection, self)._connect()
if hasattr(ssl, "create_default_context"):
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = self.cert_reqs
... | [
"def",
"_connect",
"(",
"self",
")",
":",
"sock",
"=",
"super",
"(",
"SSLConnection",
",",
"self",
")",
".",
"_connect",
"(",
")",
"if",
"hasattr",
"(",
"ssl",
",",
"\"create_default_context\"",
")",
":",
"context",
"=",
"ssl",
".",
"create_default_context... | 48.136364 | 15.409091 |
def __set_token_expired(self, value):
"""Internal helper for oauth code"""
self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value)
return | [
"def",
"__set_token_expired",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_token_expired",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"value",
")",
"return"
] | 46 | 19.5 |
def dump2sqlite(records, output_file):
"""Dumps tests results to database."""
results_keys = list(records.results[0].keys())
pad_data = []
for key in REQUIRED_KEYS:
if key not in results_keys:
results_keys.append(key)
pad_data.append("")
conn = sqlite3.connect(os.pa... | [
"def",
"dump2sqlite",
"(",
"records",
",",
"output_file",
")",
":",
"results_keys",
"=",
"list",
"(",
"records",
".",
"results",
"[",
"0",
"]",
".",
"keys",
"(",
")",
")",
"pad_data",
"=",
"[",
"]",
"for",
"key",
"in",
"REQUIRED_KEYS",
":",
"if",
"ke... | 31.25 | 24.916667 |
def find_transactions(
self,
bundles=None, # type: Optional[Iterable[BundleHash]]
addresses=None, # type: Optional[Iterable[Address]]
tags=None, # type: Optional[Iterable[Tag]]
approvees=None, # type: Optional[Iterable[TransactionHash]]
):
# ty... | [
"def",
"find_transactions",
"(",
"self",
",",
"bundles",
"=",
"None",
",",
"# type: Optional[Iterable[BundleHash]]",
"addresses",
"=",
"None",
",",
"# type: Optional[Iterable[Address]]",
"tags",
"=",
"None",
",",
"# type: Optional[Iterable[Tag]]",
"approvees",
"=",
"None"... | 28.390244 | 22.243902 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.