Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
371,400 | def address_offset(self):
if self.inst.is_array:
if self.current_idx is None:
raise ValueError("Index of array element must be known to derive address")
idx = 0
... | Byte address offset of this node relative to it's parent
If this node is an array, it's index must be known
Raises
------
ValueError
If this property is referenced on a node whose array index is not
fully defined |
371,401 | def oauth_login(self, provider, id_column, id, attrs, defaults, redirect_url=None):
user = self.query.filter(**dict([(id_column, id)])).first()
if not redirect_url:
redirect_url = request.args.get() or url_for(self.options["redirect_after_login"])
if self.logged_in():
... | Execute a login via oauth. If no user exists, oauth_signup() will be called |
371,402 | def log(cls, event=None, actor=None, data=None):
from cloud_inquisitor.log import auditlog
auditlog(event=event, actor=actor, data=data) | Generate and insert a new event
Args:
event (str): Action performed
actor (str): Actor (user or subsystem) triggering the event
data (dict): Any extra data necessary for describing the event
Returns:
`None` |
371,403 | def request(self):
headers = {: }
if self.api_key:
headers[] = self.api_key
return requests,headers
else:
if self.token:
return OAuth2Session(self.client_id, token=self.token),headers
else:
... | Returns an OAuth2 Session to be used to make requests.
Returns None if a token hasn't yet been received. |
371,404 | def push(package, is_public=False, is_team=False, reupload=False, hash=None):
team, owner, pkg, subpath = parse_package(package, allow_subpath=True)
_check_team_id(team)
session = _get_session(team)
store, pkgroot = PackageStore.find_package(team, owner, pkg, pkghash=hash)
if pkgroot is None:
... | Push a Quilt data package to the server |
371,405 | def _parse_status(self, output):
parsed = self._parse_machine_readable_output(output)
statuses = []
for target, tuples in itertools.groupby(parsed, lambda tup: tup[1]):
info = {kind: data for timestamp, _, kind, data in tuples}
... | Unit testing is so much easier when Vagrant is removed from the
equation. |
371,406 | def find_genome_length(self):
for sample in self.metadata:
sample[self.analysistype].genome_length = sum(sample[self.analysistype].contig_lengths) | Determine the total length of all the contigs for each strain |
371,407 | def _set_formatter(self):
if hasattr(self._config, "formatter") and self._config.formatter == "json":
self._formatter = "json"
else:
self._formatter = "text" | Inspects config and sets the name of the formatter to either "json" or "text"
as instance attr. If not present in config, default is "text" |
371,408 | def set_nest_transactions_with_savepoints(self, nest_transactions_with_savepoints):
if self._transaction_nesting_level > 0:
raise DBALConnectionError.may_not_alter_nested_transaction_with_savepoints_in_transaction()
if not self._platform.is_savepoints_supported():
raise ... | Sets if nested transactions should use savepoints.
:param nest_transactions_with_savepoints: `True` or `False` |
371,409 | def _run_runner(self):
import salt.minion
ret = {}
low = {: self.opts[]}
try:
async_pub = self._gen_async_pub()
self.jid = async_pub[]
fun_args = salt.utils.args.parse_input(
self.opts[],
n... | Actually execute specific runner
:return: |
371,410 | def convert_all(cls, records):
out = ["<collection>"]
for rec in records:
conversion = cls(rec)
out.append(conversion.convert())
out.append("</collection>")
return "\n".join(out) | Convert the list of bibrecs into one MARCXML.
>>> from harvestingkit.bibrecord import BibRecordPackage
>>> from harvestingkit.inspire_cds_package import Inspire2CDS
>>> bibrecs = BibRecordPackage("inspire.xml")
>>> bibrecs.parse()
>>> xml = Inspire2CDS.convert_all(bibrecs.get_re... |
371,411 | def varify_user_lock(repository_path, session_token):
with open(cpjoin(repository_path, ), ) as fd2:
content = fd2.read()
if len(content) == 0: return False
try: res = json.loads(content)
except ValueError: return False
return res[] == session_token and int(time.time())... | Verify that a returning user has a valid token and their lock has not expired |
371,412 | def is_pickle_file(abspath):
abspath = abspath.lower()
fname, ext = os.path.splitext(abspath)
if ext in [".pickle", ".pk", ".p"]:
is_pickle = True
elif ext == ".gz":
is_pickle = False
elif ext == ".tmp":
return is_pickle_file(fname)
else:
raise PickleExtError... | Parse file extension.
- *.pickle: uncompressed, utf-8 encode pickle file
- *.gz: compressed, utf-8 encode pickle file |
371,413 | def cmd_log(self, reopen=False, rotate=False):
cmd = b
if reopen:
cmd += b
if rotate:
cmd += b
return self.send_command(cmd) | Allows managing of uWSGI log related stuff
:param bool reopen: Reopen log file. Could be required after third party rotation.
:param bool rotate: Trigger built-in log rotation. |
371,414 | def _which_display(self, log: str, output: str) -> HTML:
lines = re.split(r, log)
i = 0
elog = []
for line in lines:
i += 1
e = []
if line.startswith():
logger.debug("In ERROR Condition")
e = lines[(max(i - 15, ... | Determines if the log or lst should be returned as the results for the cell based on parsing the log
looking for errors and the presence of lst output.
:param log: str log from code submission
:param output: None or str lst output if there was any
:return: The correct results based on l... |
371,415 | def hdf5_cache(filepath=None, parent=None, group=None, names=None, typed=False,
hashed_key=False, **h5dcreate_kwargs):
if filepath is None:
import tempfile
filepath = tempfile.mktemp(prefix=, suffix=)
atexit.register(os.remove, filepath)
h5dcreate_kwargs.s... | HDF5 cache decorator.
Parameters
----------
filepath : string, optional
Path to HDF5 file. If None a temporary file name will be used.
parent : string, optional
Path to group within HDF5 file to use as parent. If None the root
group will be used.
group : string, optional
... |
371,416 | def _read(self, source):
if source.startswith() or source.startswith():
source = url_content(source, cache_duration=self._cache_duration, from_cache_on_error=True)
return super(RemoteConfig, self)._read(source) | Reads and parses the config source
:param file/str source: Config source URL (http/https), or string, file name, or file pointer. |
371,417 | def _star_comparison(filter_value, tested_value):
if not is_string(tested_value):
return False
parts = filter_value.split("*")
i = 0
last_part = len(parts) - 1
idx = 0
for part in parts:
idx = tested_value.find(part, idx)
if idx == -1:
... | Tests a filter containing a joker |
371,418 | def get_spaces(self):
self.spaces = []
for resource in self._get_spaces()[]:
self.spaces.append(resource[][])
return self.spaces | Return a flat list of the names for spaces in the organization. |
371,419 | def serialize(self, pid, record, links_factory=None):
return simpledc.tostring(
self.transform_record(pid, record, links_factory)) | Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links. |
371,420 | def _swap_on_miss(partition_result):
before, item, after = partition_result
return (before, item, after) if item else (after, item, before) | Given a partition_dict result, if the partition missed, swap
the before and after. |
371,421 | def _symbol_extract(self, regex, plus = True, brackets=False):
charplus = self.pos[1] + (1 if plus else -1)
consider = self.current_line[:charplus][::-1]
if brackets==True:
rightb = []
lastchar = None
for i in range(len... | Extracts a symbol or full symbol from the current line,
optionally including the character under the cursor.
:arg regex: the compiled regular expression to use for extraction.
:arg plus: when true, the character under the cursor *is* included.
:arg brackets: when true, matching pairs o... |
371,422 | def compute(self):
self._compute_primary_smooths()
self._smooth_the_residuals()
self._select_best_smooth_at_each_point()
self._enhance_bass()
self._smooth_best_span_estimates()
self._apply_best_spans_to_primaries()
self._smooth_interpolated_smooth()
... | Run the SuperSmoother. |
371,423 | def smooth_magseries_savgol(mags, windowsize, polyorder=2):
smoothed = savgol_filter(mags, windowsize, polyorder)
return smoothed | This smooths the magseries with a Savitsky-Golay filter.
Parameters
----------
mags : np.array
The input mags/flux time-series to smooth.
windowsize : int
This is a odd integer containing the smoothing window size.
polyorder : int
This is an integer containing the polynom... |
371,424 | def lxc_path(cls, *join_paths):
response = subwrap.run([, ])
output = response.std_out
lxc_path = output.splitlines()[0]
lxc_path = lxc_path.strip()
return os.path.join(lxc_path, *join_paths) | Returns the LXC path (default on ubuntu is /var/lib/lxc) |
371,425 | def get_member_named(self, name):
result = None
members = self.members
if len(name) > 5 and name[-5] == :
potential_discriminator = name[-4:]
result = utils.get(members, name=name[:-5], discrimina... | Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. "Jake#0001"
or "Jake" will both do the lookup. However the former will give a more
precise result. Note that the discriminator must have all 4 digits
for this to wor... |
371,426 | def _css_helper(self):
entries = [entry for entry in self._plugin_manager.call_hook("css") if entry is not None]
entries += self._get_ctx()["css"]
entries = ["<link href= rel=>" for entry in entries]
return "\n".join(entries) | Add CSS links for the current page and for the plugins |
371,427 | def get_argparser():
parser = argparse.ArgumentParser("twarc")
parser.add_argument(, choices=commands)
parser.add_argument(, nargs=, default=None)
parser.add_argument("--log", dest="log",
default="twarc.log", help="log file")
parser.add_argument("--consumer_key",
... | Get the command line argument parser. |
371,428 | def set_window_class(self, window, name, class_):
_libxdo.xdo_set_window_class(self._xdo, window, name, class_) | Change the window's classname and or class.
:param name: The new class name. If ``None``, no change.
:param class_: The new class. If ``None``, no change. |
371,429 | def _prepare_args(log_likelihood_fn, state,
log_likelihood=None, description=):
state_parts = list(state) if mcmc_util.is_list_like(state) else [state]
state_parts = [tf.convert_to_tensor(s, name=)
for s in state_parts]
log_likelihood = _maybe_call_fn(
log_likelihood_f... | Processes input args to meet list-like assumptions. |
371,430 | def yieldOutput(self):
width = self.__width
if width:
num_cols = len(width)
fmt = [ % -w for w in width]
if width[-1] > 0:
fmt[-1] =
fmt = self.__sep.join(fmt)
for row in self.__cols:
row.extend( [] * (... | Generate the text output for the table.
@rtype: generator of str
@return: Text output. |
371,431 | def execute_lines(self, lines):
self.shell.execute_lines(to_text_string(lines))
self.shell.setFocus() | Execute lines and give focus to shell |
371,432 | def to_glyphs_guidelines(self, ufo_obj, glyphs_obj):
if not ufo_obj.guidelines:
return
for guideline in ufo_obj.guidelines:
new_guideline = self.glyphs_module.GSGuideLine()
name = guideline.name
if name is not None and name.endswith(LOCKED_NAME_SUFFIX):
... | Set guidelines. |
371,433 | def notify(self, msgtype, method, params):
self.dispatch.call(method, params) | Handle an incoming notify request. |
371,434 | def _send_delete_request(self, path, headers):
r = requests.delete(self.endpoint + path, headers=headers)
return r.text | Sends the DELETE request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict headers: A dict of headers to send with the request.
:rtype: str
:returns: The body of the response. |
371,435 | def format_value(value):
if isinstance(value, basestring):
value = value.replace(, )
value = u.format(value)
elif isinstance(value, bool):
value = str(value)
elif isinstance(value, int):
value = "{0}i".format(value)
elif isinstance(value, float):
value = str(... | Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted
(e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i.
If they do not they will be written as floats.
Floats are numeric values that are not followed by a trailing i. (e.g. 1, 1.0, -... |
371,436 | def create_ustar_header(self, info, encoding, errors):
info["magic"] = POSIX_MAGIC
if len(info["linkname"]) > LENGTH_LINK:
raise ValueError("linkname is too long")
if len(info["name"]) > LENGTH_NAME:
info["prefix"], info["name"] = self._posix_split_name(info["n... | Return the object as a ustar header block. |
371,437 | def visit_BoolOp(self, node):
self.generic_visit(node)
[self.combine(node, value) for value in node.values] | Merge BoolOp operand type.
BoolOp are "and" and "or" and may return any of these results so all
operands should have the combinable type. |
371,438 | def send(self):
if not self.from_email:
self.from_email = getattr(settings, , settings.DEFAULT_FROM_EMAIL)
MessageClass = message_class_for(self.drip_model.message_class)
count = 0
for user in self.get_queryset():
message_instance = MessageClass(self, u... | Send the message to each user on the queryset.
Create SentDrip for each user that gets a message.
Returns count of created SentDrips. |
371,439 | def gpg_fetch_key( key_url, key_id=None, config_dir=None ):
dat = None
from_blockstack = False
if not from_blockstack and key_id is None:
log.error( "No key ID given for key located at %s" % key_url )
return None
if key_id is not None:
rc... | Fetch a GPG public key from the given URL.
Supports anything urllib2 supports.
If the URL has no scheme, then assume it's a PGP key server, and use GPG to go get it.
The key is not accepted into any keyrings.
Return the key data on success. If key_id is given, verify the key matches.
Return None on... |
371,440 | def extract_arguments(text):
regexp = re.compile("/\w*(@\w*)*\s*([\s\S]*)",re.IGNORECASE)
result = regexp.match(text)
return result.group(2) if is_command(text) else None | Returns the argument after the command.
Examples:
extract_arguments("/get name"): 'name'
extract_arguments("/get"): ''
extract_arguments("/get@botName name"): 'name'
:param text: String to extract the arguments from a command
:return: the arguments if `text` is a command (according to ... |
371,441 | def rotate_scale(im, angle, scale, borderValue=0, interp=cv2.INTER_CUBIC):
im = np.asarray(im, dtype=np.float32)
rows, cols = im.shape
M = cv2.getRotationMatrix2D(
(cols / 2, rows / 2), -angle * 180 / np.pi, 1 / scale)
im = cv2.warpAffine(im, M, (cols, rows),
borderM... | Rotates and scales the image
Parameters
----------
im: 2d array
The image
angle: number
The angle, in radians, to rotate
scale: positive number
The scale factor
borderValue: number, default 0
The value for the pixels outside the border (default 0)
Returns
... |
371,442 | def get_packages(self, show):
if show == or show == "all":
all_packages = []
for package in self.environment:
for i in range(len(self.environment[package])):
if self.environment[package][i]:
all_pack... | Return list of Distributions filtered by active status or all
@param show: Type of package(s) to show; active, non-active or all
@type show: string: "active", "non-active", "all"
@returns: list of pkg_resources Distribution objects |
371,443 | def phase_estimation(U: np.ndarray, accuracy: int, reg_offset: int = 0) -> Program:
assert isinstance(accuracy, int)
rows, cols = U.shape
m = int(log2(rows))
output_qubits = range(0, accuracy)
U_qubits = range(accuracy, accuracy + m)
p = Program()
ro = p.declare(, , len(output_qubits))
... | Generate a circuit for quantum phase estimation.
:param U: A unitary matrix.
:param accuracy: Number of bits of accuracy desired.
:param reg_offset: Where to start writing measurements (default 0).
:return: A Quil program to perform phase estimation. |
371,444 | def _deshuffle_field(self, *args):
ip = self._invpermutation
fields = []
for arg in args:
fields.append( arg[ip] )
if len(fields) == 1:
return fields[0]
else:
return fields | Return to original ordering |
371,445 | def _run_atexit():
global _atexit
for callback, args, kwargs in reversed(_atexit):
callback(*args, **kwargs)
del _atexit[:] | Hook frameworks must invoke this after the main hook body has
successfully completed. Do not invoke it if the hook fails. |
371,446 | def create(self, model_name):
body = {: model_name}
parent = + self._project_id
return self._api.projects().models().create(body=body, parent=parent).execute() | Create a model.
Args:
model_name: the short name of the model, such as "iris".
Returns:
If successful, returns informaiton of the model, such as
{u'regions': [u'us-central1'], u'name': u'projects/myproject/models/mymodel'}
Raises:
If the model creation failed. |
371,447 | async def has_started(self):
timeout = False
auth_in_progress = False
if self._handler._connection.cbs:
timeout, auth_in_progress = await self._handler._auth.handle_token_async()
if timeout:
raise EventHubError("Authorization timeout.")
i... | Whether the handler has completed all start up processes such as
establishing the connection, session, link and authentication, and
is not ready to process messages.
**This function is now deprecated and will be removed in v2.0+.**
:rtype: bool |
371,448 | def is_less_than(self, other):
try:
unittest_case.assertTrue(self._subject < other)
except self._catch as err:
raise self._error_factory(_format("Expected {} to be less than {}", self._subject, other))
return ChainInspector(self._subject) | Ensures :attr:`subject` is less than *other*. |
371,449 | def _parse_entry(self, dom):
entry = {}
for tag in self._cap_tags:
if tag == :
try:
geotypes = []
return entry | Sigh.... |
371,450 | def list_tasks(collector):
print("Usage: aws_syncr <environment> <task>")
print("")
print("Available environments to choose from are")
print("-----------------------------------------")
print("")
for environment in os.listdir(collector.configuration_folder):
location = os.path.join(... | List the available_tasks |
371,451 | def fix_windows_stdout_stderr():
if hasattr(sys, "frozen") and sys.platform == "win32":
try:
sys.stdout.write("\n")
sys.stdout.flush()
except:
class DummyStream(object):
def __init__(self): pass
def write(self, data): pass
... | Processes can't write to stdout/stderr on frozen windows apps because they do not exist here
if process tries it anyway we get a nasty dialog window popping up, so we redirect the streams to a dummy
see https://github.com/jopohl/urh/issues/370 |
371,452 | def file_hash(fname):
chunksize = 65536
hasher = hashlib.sha256()
with open(fname, "rb") as fin:
buff = fin.read(chunksize)
while buff:
hasher.update(buff)
buff = fin.read(chunksize)
return hasher.hexdigest() | Calculate the SHA256 hash of a given file.
Useful for checking if a file has changed or been corrupted.
Parameters
----------
fname : str
The name of the file.
Returns
-------
hash : str
The hash of the file.
Examples
--------
>>> fname = "test-file-for-hash.... |
371,453 | def new_multidigraph(self, name, data=None, **attr):
self._init_graph(name, )
mdg = MultiDiGraph(self, name, data, **attr)
self._graph_objs[name] = mdg
return mdg | Return a new instance of type MultiDiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state |
371,454 | def _set_raw_return(self, sep):
raw =
if self.dst.style[] == :
raw +=
spaces = * 4
with_space = lambda s: .join([self.docs[][] + spaces + l.lstrip() if i > 0 else l for i, l in enumerate(s.splitlines())])
raw += self.dst.numpydoc.get_key_sectio... | Set the output raw return section
:param sep: the separator of current style |
371,455 | def save(self, obj, run_id):
id_code = self.generate_save_identifier(obj, run_id)
self.store.save(obj, id_code) | Save a workflow
obj - instance of a workflow to save
run_id - unique id to give the run |
371,456 | def similar_movies(self, **kwargs):
path = self._get_id_path()
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the similar movies for a specific movie id.
Args:
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representatio... |
371,457 | def create_from_root(self, root_source):
root_dto = ObjectRoot()
root_dto.configuration = root_source.configuration
root_dto.versions = [Version(x) for x in root_source.versions.values()]
for version in sorted(root_source.versions.values()):
hydrator = Hydrator(ve... | Return a populated Object Root from dictionnary datas |
371,458 | def create(self, request):
if self.readonly:
return HTTPMethodNotAllowed(headers={: })
collection = loads(request.body, object_hook=GeoJSON.to_instance)
if not isinstance(collection, FeatureCollection):
return HTTPBadRequest()
session = self.Session()
... | Read the GeoJSON feature collection from the request body and
create new objects in the database. |
371,459 | def is_valid(self):
for lineedit in self.lineedits:
if lineedit in self.validate_data and lineedit.isEnabled():
validator, invalid_msg = self.validate_data[lineedit]
text = to_text_string(lineedit.text())
if not validator(text):
... | Return True if all widget contents are valid |
371,460 | def guess_codec(file, errors="strict", require_char=False):
gedcom_char_to_codec = {
: ,
}
bom_codec = check_bom(file)
bom_size = file.tell()
codec = bom_codec or
while True:
line = file.readline()
if not line:
raise IOError("... | Look at file contents and guess its correct encoding.
File must be open in binary mode and positioned at offset 0. If BOM
record is present then it is assumed to be UTF-8 or UTF-16 encoded
file. GEDCOM header is searched for CHAR record and encoding name
is extracted from it, if BOM record is present t... |
371,461 | def _percentile(N, percent, key=lambda x:x):
if not N:
return None
k = (len(N)-1) * percent
f = math.floor(k)
c = math.ceil(k)
if f == c:
return key(N[int(k)])
d0 = key(N[int(f)]) * (c-k)
d1 = key(N[int(c)]) * (k-f)
return d0+d1 | Find the percentile of a list of values.
@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - optional key function to compute value from each element of N.
@return - the percentile of the values |
371,462 | def argument(self) -> bool:
next = self.peek()
if next == "";{+'" if quoted else "")) | Parse statement argument.
Return ``True`` if the argument is followed by block of substatements. |
371,463 | def load_bernoulli_mnist_dataset(directory, split_name):
amat_file = download(directory, FILE_TEMPLATE.format(split=split_name))
dataset = tf.data.TextLineDataset(amat_file)
str_to_arr = lambda string: np.array([c == b"1" for c in string.split()])
def _parser(s):
booltensor = tf.compat.v1.py_func(str_to... | Returns Hugo Larochelle's binary static MNIST tf.data.Dataset. |
371,464 | def lowpass(ts, cutoff_hz, order=3):
orig_ndim = ts.ndim
if ts.ndim is 1:
ts = ts[:, np.newaxis]
channels = ts.shape[1]
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
nyq = 0.5 * fs
cutoff = cutoff_hz/nyq
b, a = signal.butter(order, cutoff, btype=)
if not np.all(np.abs(... | forward-backward butterworth low-pass filter |
371,465 | def supercell_composite(mucape, effective_storm_helicity, effective_shear):
r
effective_shear = np.clip(atleast_1d(effective_shear), None, 20 * units())
effective_shear[effective_shear < 10 * units()] = 0 * units()
effective_shear = effective_shear / (20 * units())
return ((mucape / (1000 * units()... | r"""Calculate the supercell composite parameter.
The supercell composite parameter is designed to identify
environments favorable for the development of supercells,
and is calculated using the formula developed by
[Thompson2004]_:
.. math:: \text{SCP} = \frac{\text{MUCAPE}}{1000 \text{J/kg}} *
... |
371,466 | def sleep(self, ms=1):
self.scheduled.add(ms, getcurrent())
self.loop.switch() | Pauses the current green thread for *ms* milliseconds::
p = h.pipe()
@h.spawn
def _():
p.send('1')
h.sleep(50)
p.send('2')
p.recv() # returns '1'
p.recv() # returns '2' after 50 ms |
371,467 | def save_log_to_html(self):
html = html_header()
html += (
% resources_path())
html += (
% self.tr())
for item in self.dynamic_messages_log:
html += "%s\n" % item.to_html()
html += html_footer()
if self.log_... | Helper to write the log out as an html file. |
371,468 | def instantiate(self, params):
try:
self.send(self.Meta.collection_endpoint, "POST", json=params)
except CartoRateLimitException as e:
raise e
except Exception as e:
raise CartoException(e) | Allows you to fetch the map tiles of a created map
:param params: The json with the styling info for the named map
:type params: dict
:return:
:raise: CartoException |
371,469 | def get_movielens(variant="20m"):
filename = "movielens_%s.hdf5" % variant
path = os.path.join(_download.LOCAL_CACHE_DIR, filename)
if not os.path.isfile(path):
log.info("Downloading dataset to ", path)
_download.download_file(URL_BASE + filename, path)
else:
log.info("Usin... | Gets movielens datasets
Parameters
---------
variant : string
Which version of the movielens dataset to download. Should be one of '20m', '10m',
'1m' or '100k'.
Returns
-------
movies : ndarray
An array of the movie titles.
ratings : csr_matrix
A sparse matr... |
371,470 | def infer_gtr(self, print_raw=False, marginal=False, normalized_rate=True,
fixed_pi=None, pc=5.0, **kwargs):
if marginal:
_ml_anc = self._ml_anc_marginal
else:
_ml_anc = self._ml_anc_joint
self.logger("TreeAnc.infer_gtr: infe... | Calculates a GTR model given the multiple sequence alignment and the tree.
It performs ancestral sequence inferrence (joint or marginal), followed by
the branch lengths optimization. Then, the numbers of mutations are counted
in the optimal tree and related to the time within the mutation happen... |
371,471 | def smoothed_joint(seg0, seg1, maxjointsize=3, tightness=1.99):
assert seg0.end == seg1.start
assert 0 < maxjointsize
assert 0 < tightness < 2
q = seg0.end
try: v = seg0.unit_tangent(1)
except: v = seg0.unit_tangent(1 - 1e-4)
try: w = seg1.unit_tangent(0)
except: w = seg1.unit_tan... | See Andy's notes on
Smoothing Bezier Paths for an explanation of the method.
Input: two segments seg0, seg1 such that seg0.end==seg1.start, and
jointsize, a positive number
Output: seg0_trimmed, elbow, seg1_trimmed, where elbow is a cubic bezier
object that smoothly connects seg0_trimmed and se... |
371,472 | def team(self, team_id):
json = None
if int(team_id) > 0:
url = self._build_url(, str(team_id))
json = self._json(self._get(url), 200)
return Team(json, self._session) if json else None | Returns Team object with information about team specified by
``team_id``.
:param int team_id: (required), unique id for the team
:returns: :class:`Team <Team>` |
371,473 | def greedy_mapping(self, reference, hypothesis, uem=None):
if uem:
reference, hypothesis = self.uemify(reference, hypothesis, uem=uem)
return self.mapper_(hypothesis, reference) | Greedy label mapping
Parameters
----------
reference : Annotation
hypothesis : Annotation
Reference and hypothesis diarization
uem : Timeline
Evaluation map
Returns
-------
mapping : dict
Mapping between hypothesis (ke... |
371,474 | def slice_by_size(seq, size):
filling = null
for it in zip(*(itertools_chain(seq, [filling] * size),) * size):
if filling in it:
it = tuple(i for i in it if i is not filling)
if it:
yield it | Slice a sequence into chunks, return as a generation of chunks with `size`. |
371,475 | def _save_params(self):
self.model.save_params_to_file(self.current_params_fname)
utils.cleanup_params_files(self.model.output_dir, self.max_params_files_to_keep, self.state.checkpoint,
self.state.best_checkpoint, self.keep_initializations) | Saves model parameters at current checkpoint and optionally cleans up older parameter files to save disk space. |
371,476 | def remove_from_model(self, remove_orphans=False):
self._model.remove_reactions([self], remove_orphans=remove_orphans) | Removes the reaction from a model.
This removes all associations between a reaction the associated
model, metabolites and genes.
The change is reverted upon exit when using the model as a context.
Parameters
----------
remove_orphans : bool
Remove orphaned ... |
371,477 | def get_alarms_list(self, num_items=100, params=None):
if params and set(params.keys()) - VALID_ALARM_PARAMS:
self.log.error("Invalid alarm query parameters: {set(params.keys()) - VALID_ALARM_PARAMS}")
return None
return self._retrieve_items(item_type="alarms", num_items... | Get alarms as list of dictionaries
:param int num_items: Max items to retrieve
:param dict params: Additional params dictionary according to:
https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/alarms
:returns list: list of alarms |
371,478 | def chatToId(url):
match = re.search(r"conversations/([0-9]+:[^/]+)", url)
return match.group(1) if match else None | Extract the conversation ID from a conversation URL.
Matches addresses containing ``conversations/<chat>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier |
371,479 | def generic_filename(path):
for sep in common_path_separators:
if sep in path:
_, path = path.rsplit(sep, 1)
return path | Extract filename of given path os-indepently, taking care of known path
separators.
:param path: path
:return: filename
:rtype: str or unicode (depending on given path) |
371,480 | def parse(self, lines):
state = 0
entry = Entry()
for line in lines:
if not line:
if state == 1:
entry = Entry()
state = 0
elif state == 2:
self._... | Parse the input lines from a robots.txt file.
We allow that a user-agent: line is not preceded by
one or more blank lines. |
371,481 | def edit(text, pos, key):
if key in _key_bindings:
return _key_bindings[key](text, pos)
elif len(key) == 1:
return text[:pos] + key + text[pos:], pos + 1
else:
return text, pos | Process a key input in the context of a line, and return the
resulting text and cursor position.
`text' and `key' must be of type str or unicode, and `pos' must be
an int in the range [0, len(text)].
If `key' is in keys(), the corresponding command is executed on the
line. Otherwise, if `key' is a... |
371,482 | def _save_results(self, zipdata, outdir, module, gmt, rank_metric, permutation_type):
res = OrderedDict()
for gs, gseale, ind, RES in zipdata:
rdict = OrderedDict()
rdict[] = gseale[0]
rdict[] = gseale[1]
rdict[] = gseale[2]
rdict[] =... | reformat gsea results, and save to txt |
371,483 | def delay_1(year):
months = trunc(((235 * year) - 234) / 19)
parts = 12084 + (13753 * months)
day = trunc((months * 29) + parts / 25920)
if ((3 * (day + 1)) % 7) < 3:
day += 1
return day | Test for delay of start of new year and to avoid |
371,484 | def get_auth(self, username, password, authoritative_source, auth_options=None):
if auth_options is None:
auth_options = {}
if (authoritative_source is None):
raise AuthError("Missing authoritative_source.")
rem = list()
for key in se... | Returns an authentication object.
Examines the auth backend given after the '@' in the username and
returns a suitable instance of a subclass of the BaseAuth class.
* `username` [string]
Username to authenticate as.
* `password` [string]
... |
371,485 | def _gen_pool_xml(name,
ptype,
target=None,
permissions=None,
source_devices=None,
source_dir=None,
source_adapter=None,
source_hosts=None,
source_auth=None,
... | Generate the XML string to define a libvirt storage pool |
371,486 | def gss(args):
p = OptionParser(gss.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(p.print_help())
fastafile, mappingfile = args
seen = defaultdict(int)
clone = defaultdict(set)
plateMapping = DictFile(mappingfile)
fw = open("MetaData.txt", "w")
... | %prog gss fastafile plateMapping
Generate sequence files and metadata templates suited for gss submission.
The FASTA file is assumed to be exported from the JCVI data delivery folder
which looks like:
>1127963806024 /library_name=SIL1T054-B-01-120KB /clear_start=0
/clear_end=839 /primer_id=1049000... |
371,487 | def subrouters(self):
yield from filter(lambda mw: isinstance(mw.func, Router), self.mw_list) | Generator of sub-routers (middleware inheriting from Router)
contained within this router. |
371,488 | def blackbox_network():
num_nodes = 6
num_states = 2 ** num_nodes
tpm = np.zeros((num_states, num_nodes))
for index, previous_state in enumerate(all_states(num_nodes)):
current_state = [0 for i in range(num_nodes)]
if previous_state[5] == 1:
current_state[0] = 1
... | A micro-network to demonstrate blackboxing.
Diagram::
+----------+
+-------------------->+ A (COPY) + <---------------+
| +----------+ |
| +----------+ |
| +---------... |
371,489 | def BVirial_Pitzer_Curl(T, Tc, Pc, omega, order=0):
r
Tr = T/Tc
if order == 0:
B0 = 0.1445 - 0.33/Tr - 0.1385/Tr**2 - 0.0121/Tr**3
B1 = 0.073 + 0.46/Tr - 0.5/Tr**2 - 0.097/Tr**3 - 0.0073/Tr**8
elif order == 1:
B0 = Tc*(3300*T**2 + 2770*T*Tc + 363*Tc**2)/(10000*T**4)
B1 = ... | r'''Calculates the second virial coefficient using the model in [1]_.
Designed for simple calculations.
.. math::
B_r=B^{(0)}+\omega B^{(1)}
B^{(0)}=0.1445-0.33/T_r-0.1385/T_r^2-0.0121/T_r^3
B^{(1)} = 0.073+0.46/T_r-0.5/T_r^2 -0.097/T_r^3 - 0.0073/T_r^8
Parameters
----------
... |
371,490 | def send_subscribe(self, dup, topics):
pkt = MqttPkt()
pktlen = 2 + sum([2+len(topic)+1 for (topic, qos) in topics])
pkt.command = NC.CMD_SUBSCRIBE | (dup << 3) | (1 << 1)
pkt.remaining_length = pktlen
ret = pkt.alloc()
if ret != NC.ERR_SUCCESS:... | Send subscribe COMMAND to server. |
371,491 | def stop_all(self):
if self.aotask is not None:
self.aotask.stop()
self.aitask.stop()
self.daq_lock.release()
self.aitask = None
self.aotask = None | Halts both the analog output and input tasks |
371,492 | def do_results(args):
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames[]
samples = filenames[]
if not exists(srcfile):
logger.warning("Couldnt find %s; skipping..."%samples)
return
logger.info("Writing %s..."%srcfile)
from ug... | Write the results output file |
371,493 | def duplicate_nodes(self):
if len(self.geometry) == 0:
return []
mesh_hash = {k: int(m.identifier_md5, 16)
for k, m in self.geometry.items()}
node_names = np.array(self.graph.nodes_geometry)
node_geom = np.ar... | Return a sequence of node keys of identical meshes.
Will combine meshes duplicated by copying in space with different keys in
self.geometry, as well as meshes repeated by self.nodes.
Returns
-----------
duplicates: (m) sequence of keys to self.nodes that represent
... |
371,494 | def simOnePeriod(self):
self.getMortality()
if self.read_shocks:
self.readShocks()
else:
self.getShocks()
self.getStates()
self.getPostStates()
self.t_age = self.t_age + 1
self.t_cycle = self.t_c... | Simulates one period for this type. Calls the methods getMortality(), getShocks() or
readShocks, getStates(), getControls(), and getPostStates(). These should be defined for
AgentType subclasses, except getMortality (define its components simDeath and simBirth
instead) and readShocks.
... |
371,495 | def copy(self):
ret = super().copy()
for cmd in self.commands:
ret.add_command(cmd.copy())
return ret | Creates a copy of this :class:`Group`. |
371,496 | def plot_ts(fignum, dates, ts):
vertical_plot_init(fignum, 10, 3)
TS, Chrons = pmag.get_ts(ts)
p = 1
X, Y = [], []
for d in TS:
if d <= dates[1]:
if d >= dates[0]:
if len(X) == 0:
ind = TS.index(d)
X.append(TS[ind - 1])... | plot the geomagnetic polarity time scale
Parameters
__________
fignum : matplotlib figure number
dates : bounding dates for plot
ts : time scale ck95, gts04, or gts12 |
371,497 | def rgb_view(qimage, byteorder = ):
if byteorder is None:
byteorder = _sys.byteorder
bytes = byte_view(qimage, byteorder)
if bytes.shape[2] != 4:
raise ValueError("For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)")
if byteorder == :
... | Returns RGB view of a given 32-bit color QImage_'s memory.
Similarly to byte_view(), the result is a 3D numpy.uint8 array,
but reduced to the rgb dimensions (without alpha), and reordered
(using negative strides in the last dimension) to have the usual
[R,G,B] order. The image must have 32 bit pixel si... |
371,498 | def normalize_fragment(text, encoding=):
path = percent_encode(text, encoding=encoding, encode_set=FRAGMENT_ENCODE_SET)
return uppercase_percent_encoding(path) | Normalize a fragment.
Percent-encodes unacceptable characters and ensures percent-encoding is
uppercase. |
371,499 | def milestone(self, extra_params=None):
if self.get(, None):
milestones = self.space.milestones(id=self[], extra_params=extra_params)
if milestones:
return milestones[0] | The Milestone that the Ticket is a part of |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.