_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q40300 | SensitivityInput.set_wd_noise | train | def set_wd_noise(self, wd_noise):
"""Add White Dwarf Background Noise
This adds the White Dwarf (WD) Background noise. This can either do calculations with,
without, or with and without WD noise.
Args:
wd_noise (bool or str, optional): Add or remove WD background noise. Fir... | python | {
"resource": ""
} |
q40301 | ParallelInput.set_generation_type | train | def set_generation_type(self, num_processors=-1, num_splits=1000, verbose=-1):
"""Change generation type.
Choose weather to generate the data in parallel or on a single processor.
Args:
num_processors (int or None, optional): Number of parallel processors to use.
If... | python | {
"resource": ""
} |
q40302 | SNRInput.set_signal_type | train | def set_signal_type(self, sig_type):
"""Set the signal type of interest.
Sets the signal type for which the SNR is calculated.
This means inspiral, merger, and/or ringdown.
Args:
sig_type (str or list of str): Signal type desired by user.
Choices are `ins`, ... | python | {
"resource": ""
} |
q40303 | pretty_print | train | def pretty_print(ast, indent_str=' '):
"""
Simple pretty print function; returns a string rendering of an input
AST of an ES5 Program.
arguments
ast
The AST to pretty print
indent_str
The string used for indentations. Defaults to two spaces.
"""
return ''.join(chunk.... | python | {
"resource": ""
} |
q40304 | minify_printer | train | def minify_printer(
obfuscate=False,
obfuscate_globals=False,
shadow_funcname=False,
drop_semi=False):
"""
Construct a minimum printer.
Arguments
obfuscate
If True, obfuscate identifiers nested in each scope with a
shortened identifier name to further re... | python | {
"resource": ""
} |
q40305 | minify_print | train | def minify_print(
ast,
obfuscate=False,
obfuscate_globals=False,
shadow_funcname=False,
drop_semi=False):
"""
Simple minify print function; returns a string rendering of an input
AST of an ES5 program
Arguments
ast
The AST to minify print
obfusca... | python | {
"resource": ""
} |
q40306 | encode_vlq | train | def encode_vlq(i):
"""
Encode integer `i` into a VLQ encoded string.
"""
# shift in the sign to least significant bit
raw = (-i << 1) + 1 if i < 0 else i << 1
if raw < VLQ_MULTI_CHAR:
# short-circuit simple case as it doesn't need continuation
return INT_B64[raw]
result = [... | python | {
"resource": ""
} |
q40307 | decode_vlqs | train | def decode_vlqs(s):
"""
Decode str `s` into a list of integers.
"""
ints = []
i = 0
shift = 0
for c in s:
raw = B64_INT[c]
cont = VLQ_CONT & raw
i = ((VLQ_BASE_MASK & raw) << shift) | i
shift += VLQ_SHIFT
if not cont:
sign = -1 if 1 & i e... | python | {
"resource": ""
} |
q40308 | Primes._findNextPrime | train | def _findNextPrime(self, N):
"""Generate the first N primes"""
primes = self.primes
nextPrime = primes[-1]+1
while(len(primes)<N):
maximum = nextPrime * nextPrime
prime = 1
for i in primes:
if i > maximum:
break
... | python | {
"resource": ""
} |
q40309 | vsh | train | def vsh(cmd, *args, **kw):
""" Execute a command installed into the active virtualenv.
"""
args = '" "'.join(i.replace('"', r'\"') for i in args)
easy.sh('"%s" "%s"' % (venv_bin(cmd), args)) | python | {
"resource": ""
} |
q40310 | install_tools | train | def install_tools(dependencies):
""" Install a required tool before using it, if it's missing.
Note that C{dependencies} can be a distutils requirement,
or a simple name from the C{tools} task configuration, or
a (nested) list of such requirements.
"""
tools = getattr(easy.options, ... | python | {
"resource": ""
} |
q40311 | toplevel_packages | train | def toplevel_packages():
""" Get package list, without sub-packages.
"""
packages = set(easy.options.setup.packages)
for pkg in list(packages):
packages -= set(p for p in packages if str(p).startswith(pkg + '.'))
return list(sorted(packages)) | python | {
"resource": ""
} |
q40312 | Menu.widget_status | train | def widget_status(self):
"""This method will return the status of all of the widgets in the
widget list"""
widget_status_list = []
for i in self.widgetlist:
widget_status_list += [[i.name, i.status]]
return widget_status_list | python | {
"resource": ""
} |
q40313 | Menu.update | train | def update(self, screen, clock):
"""Event handling loop for the menu"""
# If a music file was passed, start playing it on repeat
if self.music is not None:
pygame.mixer.music.play(-1)
while True:
clock.tick(30)
for event in pygame.event.get():
... | python | {
"resource": ""
} |
q40314 | Textscreens.Screens | train | def Screens(self, text, prog, screen, clock):
"""Prog = 0 for first page, 1 for middle pages, 2 for last page"""
# Initialize the screen class
BaseScreen.__init__(self, self.size, self.background)
# Determine the mid position of the given screen size and the
# y button height
... | python | {
"resource": ""
} |
q40315 | Commerce.create_commerce | train | def create_commerce():
"""
Creates commerce from environment variables ``TBK_COMMERCE_ID``, ``TBK_COMMERCE_KEY``
or for testing purposes ``TBK_COMMERCE_TESTING``.
"""
commerce_id = os.getenv('TBK_COMMERCE_ID')
commerce_key = os.getenv('TBK_COMMERCE_KEY')
commerce_... | python | {
"resource": ""
} |
q40316 | Commerce.get_config_tbk | train | def get_config_tbk(self, confirmation_url):
'''
Returns a string with the ``TBK_CONFIG.dat``.
:param confirmation_url: URL where callback is made.
'''
config = (
"IDCOMERCIO = {commerce_id}\n"
"MEDCOM = 1\n"
"TBK_KEY_ID = 101\n"
"P... | python | {
"resource": ""
} |
q40317 | indent | train | def indent(indent_str=None):
"""
An example indentation ruleset.
"""
def indentation_rule():
inst = Indentator(indent_str)
return {'layout_handlers': {
Indent: inst.layout_handler_indent,
Dedent: inst.layout_handler_dedent,
Newline: inst.layout_handle... | python | {
"resource": ""
} |
q40318 | LocaleURLMiddleware._is_lang_change | train | def _is_lang_change(self, request):
"""Return True if the lang param is present and URL isn't exempt."""
if 'lang' not in request.GET:
return False
return not any(request.path.endswith(url) for url in self.exempt_urls) | python | {
"resource": ""
} |
q40319 | BooleanParser.add | train | def add(self, *matches, **kw): # kw=default=None, boolean=False
'''Add an argument; this is optional, and mostly useful for setting up aliases or setting boolean=True
Apparently `def add(self, *matches, default=None, boolean=False):` is invalid syntax in Python. Not only is this absolutely ridiculous,... | python | {
"resource": ""
} |
q40320 | GitExtension.parse | train | def parse(self, parser):
"""Main method to render data into the template."""
lineno = next(parser.stream).lineno
if parser.stream.skip_if('name:short'):
parser.stream.skip(1)
short = parser.parse_expression()
else:
short = nodes.Const(False)
... | python | {
"resource": ""
} |
q40321 | flatten | train | def flatten(nested, containers=(list, tuple)):
""" Flatten a nested list by yielding its scalar items.
"""
for item in nested:
if hasattr(item, "next") or isinstance(item, containers):
for subitem in flatten(item):
yield subitem
else:
yield item | python | {
"resource": ""
} |
q40322 | get_template_context_processors | train | def get_template_context_processors(exclude=(), append=(),
current={'processors': TEMPLATE_CONTEXT_PROCESSORS}):
"""
Returns TEMPLATE_CONTEXT_PROCESSORS without the processors listed in
exclude and with the processors listed in append.
The use of a mutable dict is intentional, i... | python | {
"resource": ""
} |
q40323 | get_middleware | train | def get_middleware(exclude=(), append=(),
current={'middleware': MIDDLEWARE_CLASSES}):
"""
Returns MIDDLEWARE_CLASSES without the middlewares listed in exclude and
with the middlewares listed in append.
The use of a mutable dict is intentional, in order to preserve the state of
t... | python | {
"resource": ""
} |
q40324 | get_apps | train | def get_apps(exclude=(), append=(), current={'apps': INSTALLED_APPS}):
"""
Returns INSTALLED_APPS without the apps listed in exclude and with the apps
listed in append.
The use of a mutable dict is intentional, in order to preserve the state of
the INSTALLED_APPS tuple across multiple settings file... | python | {
"resource": ""
} |
q40325 | invariants | train | def invariants(mol):
"""Generate initial atom identifiers using atomic invariants"""
atom_ids = {}
for a in mol.atoms:
components = []
components.append(a.number)
components.append(len(a.oatoms))
components.append(a.hcount)
components.append(a.charge)
componen... | python | {
"resource": ""
} |
q40326 | TransformMixin.connected_subgraphs | train | def connected_subgraphs(self, directed=True, ordered=False):
'''Generates connected components as subgraphs.
When ordered=True, subgraphs are ordered by number of vertices.
'''
num_ccs, labels = self.connected_components(directed=directed)
# check the trivial case first
if num_ccs == 1:
yi... | python | {
"resource": ""
} |
q40327 | TransformMixin.neighborhood_subgraph | train | def neighborhood_subgraph(self, start_idx, radius=1, weighted=True,
directed=True, return_mask=False):
'''Returns a subgraph containing only vertices within a given
geodesic radius of start_idx.'''
adj = self.matrix('dense', 'csr', 'csc')
dist = ssc.dijkstra(adj, directed=... | python | {
"resource": ""
} |
q40328 | TransformMixin.isograph | train | def isograph(self, min_weight=None):
'''Remove short-circuit edges using the Isograph algorithm.
min_weight : float, optional
Minimum weight of edges to consider removing. Defaults to max(MST).
From "Isograph: Neighbourhood Graph Construction Based On Geodesic Distance
For Semi-Supervise... | python | {
"resource": ""
} |
q40329 | TransformMixin.circle_tear | train | def circle_tear(self, spanning_tree='mst', cycle_len_thresh=5, spt_idx=None,
copy=True):
'''Circular graph tearing.
spanning_tree: one of {'mst', 'spt'}
cycle_len_thresh: int, length of longest allowable cycle
spt_idx: int, start vertex for shortest_path_subtree, random if None
F... | python | {
"resource": ""
} |
q40330 | fuzz_string | train | def fuzz_string(seed_str, runs=100, fuzz_factor=50):
"""A random fuzzer for a simulated text viewer application.
It takes a string as seed and generates <runs> variant of it.
:param seed_str: the string to use as seed for fuzzing.
:param runs: number of fuzzed variants to supply.
:param fuzz_facto... | python | {
"resource": ""
} |
q40331 | fuzzer | train | def fuzzer(buffer, fuzz_factor=101):
"""Fuzz given buffer.
Take a buffer of bytes, create a copy, and replace some bytes
with random values. Number of bytes to modify depends on fuzz_factor.
This code is taken from Charlie Miller's fuzzer code.
:param buffer: the data to fuzz.
:type buffer: by... | python | {
"resource": ""
} |
q40332 | number_of_bytes_to_modify | train | def number_of_bytes_to_modify(buf_len, fuzz_factor):
"""Calculate number of bytes to modify.
:param buf_len: len of data buffer to fuzz.
:param fuzz_factor: degree of fuzzing.
:return: number of bytes to change.
"""
return random.randrange(math.ceil((float(buf_len) / fuzz_factor))) + 1 | python | {
"resource": ""
} |
q40333 | FuzzExecutor._fuzz_data_file | train | def _fuzz_data_file(self, data_file):
"""Generate fuzzed variant of given file.
:param data_file: path to file to fuzz.
:type data_file: str
:return: path to fuzzed file.
:rtype: str
"""
buf = bytearray(open(os.path.abspath(data_file), 'rb').read())
fuzze... | python | {
"resource": ""
} |
q40334 | FuzzExecutor._execute | train | def _execute(self, app_, file_):
"""Run app with file as input.
:param app_: application to run.
:param file_: file to run app with.
:return: success True, else False
:rtype: bool
"""
app_name = os.path.basename(app_)
args = [app_]
args.extend(sel... | python | {
"resource": ""
} |
q40335 | FuzzExecutor.__parse_app_list | train | def __parse_app_list(app_list):
"""Parse list of apps for arguments.
:param app_list: list of apps with optional arguments.
:return: list of apps and assigned argument dict.
:rtype: [String], {String: [String]}
"""
args = {}
apps = []
for app_str in app_l... | python | {
"resource": ""
} |
q40336 | _make_tonnetz_matrix | train | def _make_tonnetz_matrix():
"""Return the tonnetz projection matrix."""
pi = np.pi
chroma = np.arange(12)
# Define each row of the transform matrix
fifth_x = r_fifth*(np.sin((7*pi/6) * chroma))
fifth_y = r_fifth*(np.cos((7*pi/6) * chroma))
minor_third_x = r_minor_thirds*(np.sin(3*pi/2 * chr... | python | {
"resource": ""
} |
q40337 | _to_tonnetz | train | def _to_tonnetz(chromagram):
"""Project a chromagram on the tonnetz.
Returned value is normalized to prevent numerical instabilities.
"""
if np.sum(np.abs(chromagram)) == 0.:
# The input is an empty chord, return zero.
return np.zeros(6)
_tonnetz = np.dot(__TONNETZ_MATRIX, c... | python | {
"resource": ""
} |
q40338 | spawn_managed_host | train | def spawn_managed_host(config_file, manager, connect_on_start=True):
"""
Spawns a managed host, if it is not already running
"""
data = manager.request_host_status(config_file)
is_running = data['started']
# Managed hosts run as persistent processes, so it may already be running
if is_run... | python | {
"resource": ""
} |
q40339 | parse_input | train | def parse_input(s):
"""Parse the given input and intelligently transform it into an absolute,
non-naive, timezone-aware datetime object for the UTC timezone.
The input can be specified as a millisecond-precision UTC timestamp (or
delta against Epoch), with or without a terminating 'L'. Alternatively, t... | python | {
"resource": ""
} |
q40340 | render_date | train | def render_date(date, tz=pytz.utc, fmt=_FULL_OUTPUT_FORMAT):
"""Format the given date for output. The local time render of the given
date is done using the given timezone."""
local = date.astimezone(tz)
ts = __date_to_millisecond_ts(date)
return fmt.format(
ts=ts,
utc=date.st... | python | {
"resource": ""
} |
q40341 | DescriptiveParser.parse | train | def parse(self, complete=True, args=None):
'''Parse a list of arguments, returning a dict
See BooleanParser.parse for `args`-related documentation.
If `complete` is True and there are values in `args` that don't have corresponding arguments,
or there are required arguments that don't h... | python | {
"resource": ""
} |
q40342 | Covariance.perturbParams | train | def perturbParams(self, pertSize=1e-3):
"""
slightly perturbs the values of the parameters
"""
params = self.getParams()
self.setParams(params+pertSize*sp.randn(params.shape[0])) | python | {
"resource": ""
} |
q40343 | Covariance.Kgrad_param_num | train | def Kgrad_param_num(self,i,h=1e-4):
"""
check discrepancies between numerical and analytical gradients
"""
params = self.getParams()
e = sp.zeros_like(params); e[i] = 1
self.setParams(params-h*e)
C_L = self.K()
self.setParams(params+h*e)
C_R = self... | python | {
"resource": ""
} |
q40344 | parallel_snr_func | train | def parallel_snr_func(num, binary_args, phenomdwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single p... | python | {
"resource": ""
} |
q40345 | parallel_ecc_snr_func | train | def parallel_ecc_snr_func(num, binary_args, eccwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with eccentric waveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a s... | python | {
"resource": ""
} |
q40346 | snr | train | def snr(*args, **kwargs):
"""Compute the SNR of binaries.
snr is a function that takes binary parameters and sensitivity curves as inputs,
and returns snr for chosen phases.
Warning: All binary parameters must be either scalar, len-1 arrays,
or arrays of the same length. All of these can be used a... | python | {
"resource": ""
} |
q40347 | InferentialParser.parse | train | def parse(self, args=None):
'''Parse a list of arguments, returning a dict.
Flags are only boolean if they are not followed by a non-flag argument.
All positional arguments not associable with a flag will be added to the return dictionary's `['_']` field.
'''
opts = dict()
... | python | {
"resource": ""
} |
q40348 | sq_dist | train | def sq_dist(X1,X2=None):
"""
computes a matrix of all pariwise squared distances
"""
if X2==None:
X2 = X1
assert X1.shape[1]==X2.shape[1], 'dimensions do not match'
n = X1.shape[0]
m = X2.shape[0]
d = X1.shape[1]
# (X1 - X2)**2 = X1**2 + X2**2 - 2X1X2
X1sq = sp.reshape((... | python | {
"resource": ""
} |
q40349 | Bond.setdbo | train | def setdbo(self, bond1, bond2, dboval):
"""Set the double bond orientation for bond1 and bond2
based on this bond"""
# this bond must be a double bond
if self.bondtype != 2:
raise FrownsError("To set double bond order, center bond must be double!")
assert dboval in [D... | python | {
"resource": ""
} |
q40350 | save_segments | train | def save_segments(outfile, boundaries, beat_intervals, labels=None):
"""Save detected segments to a .lab file.
:parameters:
- outfile : str
Path to output file
- boundaries : list of int
Beat indices of detected segment boundaries
- beat_intervals : np.ndarray ... | python | {
"resource": ""
} |
q40351 | reverse | train | def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None):
"""Wraps Django's reverse to prepend the correct locale."""
prefixer = get_url_prefix()
if prefixer:
prefix = prefix or '/'
url = django_reverse(viewname, urlconf, args, kwargs, prefix)
if prefixer:
url = pref... | python | {
"resource": ""
} |
q40352 | Prefixer.get_language | train | def get_language(self):
"""
Return a locale code we support on the site using the
user's Accept-Language header to determine which is best. This
mostly follows the RFCs but read bug 439568 for details.
"""
if 'lang' in self.request.GET:
lang = self.request.GET... | python | {
"resource": ""
} |
q40353 | Prefixer.get_best_language | train | def get_best_language(self, accept_lang):
"""Given an Accept-Language header, return the best-matching language."""
LUM = settings.LANGUAGE_URL_MAP
langs = dict(LUM.items() + settings.CANONICAL_LOCALES.items())
# Add missing short locales to the list. This will automatically map
... | python | {
"resource": ""
} |
q40354 | extensions | train | def extensions():
"""Returns list of `cython` extensions for `lazy_cythonize`."""
import numpy
from Cython.Build import cythonize
ext = [
Extension('phydmslib.numutils', ['phydmslib/numutils.pyx'],
include_dirs=[numpy.get_include()],
extra_compile_args... | python | {
"resource": ""
} |
q40355 | plot_main | train | def plot_main(pid, return_fig_ax=False):
"""Main function for creating these plots.
Reads in plot info dict from json file or dictionary in script.
Args:
return_fig_ax (bool, optional): Return figure and axes objects.
Returns:
2-element tuple containing
- **fig** (*obj*): ... | python | {
"resource": ""
} |
q40356 | execute | train | def execute(connection: connection, statement: str) -> Optional[List[Tuple[str, ...]]]:
"""Execute PGSQL statement and fetches the statement response.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
statement: str
PGSQL st... | python | {
"resource": ""
} |
q40357 | human_size | train | def human_size(size):
""" Return a human-readable representation of a byte size.
@param size: Number of bytes as an integer or string.
@return: String of length 10 with the formatted result.
"""
if isinstance(size, string_types):
size = int(size, 10)
if size < 0:
return... | python | {
"resource": ""
} |
q40358 | iso_datetime | train | def iso_datetime(timestamp=None):
""" Convert UNIX timestamp to ISO datetime string.
@param timestamp: UNIX epoch value (default: the current time).
@return: Timestamp formatted as "YYYY-mm-dd HH:MM:SS".
"""
if timestamp is None:
timestamp = time.time()
return datetime.datetime.... | python | {
"resource": ""
} |
q40359 | human_duration | train | def human_duration(time1, time2=None, precision=0, short=False):
""" Return a human-readable representation of a time delta.
@param time1: Relative time value.
@param time2: Time base (C{None} for now; 0 for a duration in C{time1}).
@param precision: How many time units to return (0 = all).... | python | {
"resource": ""
} |
q40360 | to_unicode | train | def to_unicode(text):
""" Return a decoded unicode string.
False values are returned untouched.
"""
if not text or isinstance(text, unicode if PY2 else str):
return text
try:
# Try UTF-8 first
return text.decode("UTF-8")
except UnicodeError:
try:
... | python | {
"resource": ""
} |
q40361 | to_utf8 | train | def to_utf8(text):
""" Enforce UTF8 encoding.
"""
# return empty/false stuff unaltered
if not text:
if isinstance(text, string_types):
text = ""
return text
try:
# Is it a unicode string, or pure ascii?
return text.encode("utf8")
except UnicodeDecodeE... | python | {
"resource": ""
} |
q40362 | MeanKronSum.setDesigns | train | def setDesigns(self, F, A):
""" set fixed effect designs """
F = to_list(F)
A = to_list(A)
assert len(A) == len(F), 'MeanKronSum: A and F must have same length!'
n_terms = len(F)
n_covs = 0
k = 0
l = 0
for ti in range(n_terms):
assert F... | python | {
"resource": ""
} |
q40363 | toRanks | train | def toRanks(A):
"""
converts the columns of A to ranks
"""
AA=sp.zeros_like(A)
for i in range(A.shape[1]):
AA[:,i] = st.rankdata(A[:,i])
AA=sp.array(sp.around(AA),dtype="int")-1
return AA | python | {
"resource": ""
} |
q40364 | regressOut | train | def regressOut(Y, X, return_b=False):
"""
regresses out X from Y
"""
Xd = la.pinv(X)
b = Xd.dot(Y)
Y_out = Y-X.dot(b)
if return_b:
return Y_out, b
else:
return Y_out | python | {
"resource": ""
} |
q40365 | remove_dependent_cols | train | def remove_dependent_cols(M, tol=1e-6, display=False):
"""
Returns a matrix where dependent columsn have been removed
"""
R = la.qr(M, mode='r')[0][:M.shape[1], :]
I = (abs(R.diagonal())>tol)
if sp.any(~I) and display:
print(('cols ' + str(sp.where(~I)[0]) +
' have been r... | python | {
"resource": ""
} |
q40366 | bias | train | def bias(mass, z, h=h, Om_M=Om_M, Om_L=Om_L):
"""Calculate halo bias, from Seljak & Warren 2004.
Parameters
----------
mass : ndarray or float
Halo mass to calculate bias for.
z : ndarray or float
Halo z, same type and size as mass.
h : float, optional
Hubble parameter, ... | python | {
"resource": ""
} |
q40367 | Confirmation.is_timeout | train | def is_timeout(self):
'''
Check if the lapse between initialization and now is more than ``self.timeout``.
'''
lapse = datetime.datetime.now() - self.init_time
return lapse > datetime.timedelta(seconds=self.timeout) | python | {
"resource": ""
} |
q40368 | improvise | train | def improvise(oracle, seq_len, k=1, LRS=0, weight=None, continuity=1):
""" Given an oracle and length, generate an improvised sequence of the given length.
:param oracle: an indexed vmo object
:param seq_len: the length of the returned improvisation sequence
:param k: the starting improvisation time st... | python | {
"resource": ""
} |
q40369 | _make_win | train | def _make_win(n, mono=False):
""" Generate a window for a given length.
:param n: an integer for the length of the window.
:param mono: True for a mono window, False for a stereo window.
:return: an numpy array containing the window value.
"""
if mono:
win = np.hanning(n) + 0.00001
... | python | {
"resource": ""
} |
q40370 | Walker.filter | train | def filter(self, node, condition):
"""
This method accepts a node and the condition function; a
generator will be returned to yield the nodes that got matched
by the condition.
"""
if not isinstance(node, Node):
raise TypeError('not a node')
for chil... | python | {
"resource": ""
} |
q40371 | Walker.extract | train | def extract(self, node, condition, skip=0):
"""
Extract a single node that matches the provided condition,
otherwise a TypeError is raised. An optional skip parameter can
be provided to specify how many matching nodes are to be skipped
over.
"""
for child in sel... | python | {
"resource": ""
} |
q40372 | ReprWalker.walk | train | def walk(
self, node, omit=(
'lexpos', 'lineno', 'colno', 'rowno'),
indent=0, depth=-1,
pos=False,
_level=0):
"""
Accepts the standard node argument, along with an optional omit
flag - it should be an iterable that lists out all att... | python | {
"resource": ""
} |
q40373 | _prune_edges | train | def _prune_edges(G, X, traj_lengths, pruning_thresh=0.1, verbose=False):
'''Prune edges in graph G via cosine distance with trajectory edges.'''
W = G.matrix('dense', copy=True)
degree = G.degree(kind='out', weighted=False)
i = 0
num_bad = 0
for n in traj_lengths:
s, t = np.nonzero(W[i:i+n-1])
graph... | python | {
"resource": ""
} |
q40374 | Waterfall.make_plot | train | def make_plot(self):
"""This method creates the waterfall plot.
"""
# sets levels of main contour plot
colors1 = ['None', 'darkblue', 'blue', 'deepskyblue', 'aqua',
'greenyellow', 'orange', 'red', 'darkred']
if len(self.contour_vals) > len(colors1) + 1:
... | python | {
"resource": ""
} |
q40375 | Ratio.make_plot | train | def make_plot(self):
"""Creates the ratio plot.
"""
# sets colormap for ratio comparison plot
cmap = getattr(cm, self.colormap)
# set values of ratio comparison contour
normval = 2.0
num_contours = 40 # must be even
levels = np.linspace(-normval, normva... | python | {
"resource": ""
} |
q40376 | Ratio.set_comparison | train | def set_comparison(self):
"""Defines the comparison values for the ratio.
This function is added for easier modularity.
"""
self.comp1 = self.zvals[0]
self.comp2 = self.zvals[1]
return | python | {
"resource": ""
} |
q40377 | Horizon.make_plot | train | def make_plot(self):
"""Make the horizon plot.
"""
self.get_contour_values()
# sets levels of main contour plot
colors1 = ['blue', 'green', 'red', 'purple', 'orange',
'gold', 'magenta']
# set contour value. Default is SNR_CUT.
self.snr_contou... | python | {
"resource": ""
} |
q40378 | AnalysisMixin.bandwidth | train | def bandwidth(self):
"""Computes the 'bandwidth' of a graph."""
return np.abs(np.diff(self.pairs(), axis=1)).max() | python | {
"resource": ""
} |
q40379 | AnalysisMixin.profile | train | def profile(self):
"""Measure of bandedness, also known as 'envelope size'."""
leftmost_idx = np.argmax(self.matrix('dense').astype(bool), axis=0)
return (np.arange(self.num_vertices()) - leftmost_idx).sum() | python | {
"resource": ""
} |
q40380 | AnalysisMixin.eccentricity | train | def eccentricity(self, directed=None, weighted=None):
'''Maximum distance from each vertex to any other vertex.'''
sp = self.shortest_path(directed=directed, weighted=weighted)
return sp.max(axis=0) | python | {
"resource": ""
} |
q40381 | LabelMixin.color_greedy | train | def color_greedy(self):
'''Returns a greedy vertex coloring as an array of ints.'''
n = self.num_vertices()
coloring = np.zeros(n, dtype=int)
for i, nbrs in enumerate(self.adj_list()):
nbr_colors = set(coloring[nbrs])
for c in count(1):
if c not in nbr_colors:
coloring[i] =... | python | {
"resource": ""
} |
q40382 | LabelMixin.bicolor_spectral | train | def bicolor_spectral(self):
'''Returns an approximate 2-coloring as an array of booleans.
From "A Multiscale Pyramid Transform for Graph Signals" by Shuman et al.
Note: Assumes a single connected component, and may fail otherwise.
'''
lap = self.laplacian().astype(float)
vals, vecs = eigs(lap, ... | python | {
"resource": ""
} |
q40383 | LabelMixin.classify_nearest | train | def classify_nearest(self, partial_labels):
'''Simple semi-supervised classification, by assigning unlabeled vertices
the label of nearest labeled vertex.
partial_labels: (n,) array of integer labels, -1 for unlabeled.
'''
labels = np.array(partial_labels, copy=True)
unlabeled = labels == -1
... | python | {
"resource": ""
} |
q40384 | LabelMixin.classify_lgc | train | def classify_lgc(self, partial_labels, kernel='rbf', alpha=0.2, tol=1e-3,
max_iter=30):
'''Iterative label spreading for semi-supervised classification.
partial_labels: (n,) array of integer labels, -1 for unlabeled.
kernel: one of {'none', 'rbf', 'binary'}, for reweighting edges.
al... | python | {
"resource": ""
} |
q40385 | LabelMixin.classify_harmonic | train | def classify_harmonic(self, partial_labels, use_CMN=True):
'''Harmonic function method for semi-supervised classification,
also known as the Gaussian Mean Fields algorithm.
partial_labels: (n,) array of integer labels, -1 for unlabeled.
use_CMN : when True, apply Class Mass Normalization
From "Sem... | python | {
"resource": ""
} |
q40386 | _checkParam | train | def _checkParam(param, value, paramlimits, paramtypes):
"""Checks if `value` is allowable value for `param`.
Raises except if `value` is not acceptable, otherwise
returns `None` if value is acceptable.
`paramlimits` and `paramtypes` are the `PARAMLIMITS`
and `PARAMTYPES` attributes of a `Model`.
... | python | {
"resource": ""
} |
q40387 | DiscreteGamma | train | def DiscreteGamma(alpha, beta, ncats):
"""Returns category means for discretized gamma distribution.
The distribution is evenly divided into categories, and the
mean of each category is returned.
Args:
`alpha` (`float` > 0)
Shape parameter of gamma distribution.
`beta` (`fl... | python | {
"resource": ""
} |
q40388 | ExpCM.PARAMLIMITS | train | def PARAMLIMITS(self, value):
"""Set new `PARAMLIMITS` dictionary."""
assert set(value.keys()) == set(self.PARAMLIMITS.keys()), "The \
new parameter limits are not defined for the same set \
of parameters as before."
for param in value.keys():
assert v... | python | {
"resource": ""
} |
q40389 | ExpCM._eta_from_phi | train | def _eta_from_phi(self):
"""Update `eta` using current `phi`."""
self.eta = scipy.ndarray(N_NT - 1, dtype='float')
etaprod = 1.0
for w in range(N_NT - 1):
self.eta[w] = 1.0 - self.phi[w] / etaprod
etaprod *= self.eta[w]
_checkParam('eta', self.eta, self.PA... | python | {
"resource": ""
} |
q40390 | ExpCM._update_phi | train | def _update_phi(self):
"""Update `phi` using current `eta`."""
etaprod = 1.0
for w in range(N_NT - 1):
self.phi[w] = etaprod * (1 - self.eta[w])
etaprod *= self.eta[w]
self.phi[N_NT - 1] = etaprod | python | {
"resource": ""
} |
q40391 | ExpCM._update_Qxy | train | def _update_Qxy(self):
"""Update `Qxy` using current `kappa` and `phi`."""
for w in range(N_NT):
scipy.copyto(self.Qxy, self.phi[w], where=CODON_NT_MUT[w])
self.Qxy[CODON_TRANSITION] *= self.kappa | python | {
"resource": ""
} |
q40392 | ExpCM._update_pi_vars | train | def _update_pi_vars(self):
"""Update variables that depend on `pi`.
These are `pi_codon`, `ln_pi_codon`, `piAx_piAy`, `piAx_piAy_beta`,
`ln_piAx_piAy_beta`.
Update using current `pi` and `beta`."""
with scipy.errstate(divide='raise', under='raise', over='raise',
... | python | {
"resource": ""
} |
q40393 | ExpCM._update_Frxy | train | def _update_Frxy(self):
"""Update `Frxy` from `piAx_piAy_beta`, `ln_piAx_piAy_beta`, `omega`, `beta`."""
self.Frxy.fill(1.0)
self.Frxy_no_omega.fill(1.0)
with scipy.errstate(divide='raise', under='raise', over='raise',
invalid='ignore'):
scipy.copyto(s... | python | {
"resource": ""
} |
q40394 | ExpCM._update_Prxy | train | def _update_Prxy(self):
"""Update `Prxy` using current `Frxy` and `Qxy`."""
self.Prxy = self.Frxy * self.Qxy
_fill_diagonals(self.Prxy, self._diag_indices) | python | {
"resource": ""
} |
q40395 | ExpCM._update_Prxy_diag | train | def _update_Prxy_diag(self):
"""Update `D`, `A`, `Ainv` from `Prxy`, `prx`."""
for r in range(self.nsites):
pr_half = self.prx[r]**0.5
pr_neghalf = self.prx[r]**-0.5
#symm_pr = scipy.dot(scipy.diag(pr_half), scipy.dot(self.Prxy[r], scipy.diag(pr_neghalf)))
... | python | {
"resource": ""
} |
q40396 | ExpCM._update_prx | train | def _update_prx(self):
"""Update `prx` from `phi`, `pi_codon`, and `beta`."""
qx = scipy.ones(N_CODON, dtype='float')
for j in range(3):
for w in range(N_NT):
qx[CODON_NT[j][w]] *= self.phi[w]
frx = self.pi_codon**self.beta
self.prx = frx * qx
... | python | {
"resource": ""
} |
q40397 | ExpCM.spielman_wr | train | def spielman_wr(self, norm=True):
"""Returns a list of site-specific omega values calculated from the `ExpCM`.
Args:
`norm` (bool)
If `True`, normalize the `omega_r` values by the ExpCM
gene-wide `omega`.
Returns:
... | python | {
"resource": ""
} |
q40398 | ExpCM_fitprefs.dlogprior | train | def dlogprior(self, param):
"""Value of derivative of prior depends on value of `prior`."""
assert param in self.freeparams, "Invalid param: {0}".format(param)
return self._dlogprior[param] | python | {
"resource": ""
} |
q40399 | ExpCM_empirical_phi._update_phi | train | def _update_phi(self):
"""Compute `phi`, `dphi_dbeta`, and `eta` from `g` and `frxy`."""
self.phi = self._compute_empirical_phi(self.beta)
_checkParam('phi', self.phi, self.PARAMLIMITS, self.PARAMTYPES)
self._eta_from_phi()
dbeta = 1.0e-3
self.dphi_dbeta = scipy.misc.deri... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.