text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def console_rect(
con: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
clr: bool,
flag: int = BKGND_DEFAULT,
) -> None:
"""Draw a the background color on a rect optionally clearing the text.
If clr is True the affected tiles are changed to space character.
.. deprecated::... | 0.002288 |
def location(self):
"""
Returns a ``string`` constant to indicate whether the game was played
at the team's home venue, the opponent's venue, or at a neutral site.
"""
if self._location == '':
return HOME
if self._location == 'N':
return NEUTRAL
... | 0.005333 |
def find_initial_offset(self, pyramids=6):
"""Estimate time offset
This sets and returns the initial time offset estimation.
Parameters
---------------
pyramids : int
Number of pyramids to use for ZNCC calculations.
If initial estimation ... | 0.008214 |
def query(query, use_sudo=True, **kwargs):
"""
Run a MySQL query.
"""
func = use_sudo and run_as_root or run
user = kwargs.get('mysql_user') or env.get('mysql_user')
password = kwargs.get('mysql_password') or env.get('mysql_password')
options = [
'--batch',
'--raw',
... | 0.001548 |
def from_json(data):
"""Decode event encoded as JSON by processor"""
parsed_data = json.loads(data)
trigger = TriggerInfo(
parsed_data['trigger']['class'],
parsed_data['trigger']['kind'],
)
# extract content type, needed to decode body
content_ty... | 0.002674 |
def _authenticate_gssapi(credentials, sock_info):
"""Authenticate using GSSAPI.
"""
if not HAVE_KERBEROS:
raise ConfigurationError('The "kerberos" module must be '
'installed to use GSSAPI authentication.')
try:
username = credentials.username
pa... | 0.000202 |
def _zdt_to_nanos(self, zdt):
"""Extracts nanoseconds from a ZonedDateTime"""
instant = zdt.toInstant()
return instant.getNano() + instant.getEpochSecond() * 1000000000 | 0.010417 |
def bindata(data, maxbins = 30, reduction = 0.1):
'''
data must be numeric list with a len above 20
This function counts the number of data points in a reduced array
'''
tole = 0.01
N = len(data)
assert N > 20
vmin = min(data)
vmax = max(data)
DV = vmax - vmin
tol = tole*DV
vmax += t... | 0.016645 |
def _add_json_binary_field(b, serialized, field):
'''' Set the given field to the given val (bytes) in the serialized
dictionary.
If the value isn't valid utf-8, we base64 encode it and use field+"64"
as the field name.
'''
try:
val = b.decode('utf-8')
serialized[field] = val
... | 0.002294 |
def export_disks(
self,
standalone=True,
dst_dir=None,
compress=False,
collect_only=False,
with_threads=True,
*args,
**kwargs
):
"""
Thin method that just uses the provider
"""
return self.provider.export_disks(
... | 0.007143 |
def setup_a_alpha_and_derivatives(self, i, T=None):
r'''Sets `a`, `m`, and `Tc` for a specific component before the
pure-species EOS's `a_alpha_and_derivatives` method is called. Both are
called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''
self.a, self.m, self.Tc = sel... | 0.011331 |
def set_config(**kwargs):
"""Set up the configure of profiler (only accepts keyword arguments).
Parameters
----------
filename : string,
output file for profile data
profile_all : boolean,
all profile types enabled
profile_symbolic : boolean,
whether to profile symbolic ... | 0.002122 |
def observeInBackground(self, seconds=None):
""" As Region.observe(), but runs in a background process, allowing the rest
of your script to continue.
Note that the subprocess operates on *copies* of the usual objects, not the original
Region object itself for example. If your event hand... | 0.010014 |
def create_otu_table(output_fp, deblurred_list,
outputfasta_fp=None, minreads=0):
"""Create a biom table out of all files in a directory
Parameters
----------
output_fp : string
filepath to output BIOM table
deblurred_list : list of (str, str)
list of file names... | 0.00075 |
def combine_commands(*commands):
"""Return a Command that combines several commands."""
class CombinedCommand(Command):
def initialize_options(self):
self.commands = []
for C in commands:
self.commands.append(C(self.distribution))
for c in self.comma... | 0.001709 |
def destroy(self):
""" Cleanup the activty lifecycle listener """
if self.widget:
self.set_active(False)
super(AndroidBarcodeView, self).destroy() | 0.010989 |
def send_request(self, ssl_client: SslClient) -> str:
"""Send an HTTP GET to the server and return the HTTP status code.
"""
try:
ssl_client.write(HttpRequestGenerator.get_request(self._hostname))
# Parse the response and print the Location header
http_respon... | 0.003518 |
def render_asset(self, name):
"""
Render all includes in asset by names
:type name: str|unicode
:rtype: str|unicode
"""
result = ""
if self.has_asset(name):
asset = self.get_asset(name)
if asset.files:
for f in asset.files:... | 0.005 |
def check_candidate(a, d, n, s):
"""Part of the Miller-Rabin primality test in is_prime()."""
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True | 0.003984 |
def load_html_metadata(filename):
""" Get metadata from html file """
parser = MetaParser()
data = open(filename, 'r').read()
if 'pycbc-meta' in data:
print("LOADING HTML FILE %s" % filename)
parser.feed(data)
cp = ConfigParser.ConfigParser(parser.metadata)
cp.add_section(os.path.ba... | 0.002849 |
def to_rectified(self, x, y):
"""
Convert the input (x, y) positions from the original
(unrectified) image to the rectified image.
Parameters
----------
x, y: float or array-like of float
The zero-index pixel coordinates in the original
(unrectif... | 0.003401 |
def SETNAE(cpu, dest):
"""
Sets byte if not above or equal.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0)) | 0.008929 |
def mobilized(normal_fn):
"""
Replace a view function with a normal and mobile view.
For example::
def view():
...
@mobilized(view)
def view():
...
The second function is the mobile version of view. The original
function is overwritten, and the de... | 0.001227 |
def post(self, user_ids=None, usernames=None, status=None):
"""
:param user_ids: list of int of the user_ids to return
:param usernames: list of str of the usernames to return
:param status: str of the status
:return: list of User
"""
return self.conn... | 0.003711 |
def name(self):
"""str: name of the file entry, which does not include the full path.
Raises:
BackEndError: if pytsk3 returns a non UTF-8 formatted name.
"""
if self._name is None:
# If pytsk3.FS_Info.open() was used file.info has an attribute name
# (pytsk3.TSK_FS_FILE) that contains... | 0.010504 |
def sub_chars(string):
"""
Strips illegal characters from a string. Used to sanitize input essays.
Removes all non-punctuation, digit, or letter characters.
Returns sanitized string.
string - string
"""
#Define replacement patterns
sub_pat = r"[^A-Za-z\.\?!,';:]"
char_pat = r"\."
... | 0.00454 |
def __readData(self, targetPath, start, end):
''' read data '''
ret = []
if not path.exists(targetPath):
LOG.error("Target file doesn't exist: %s" % path.abspath(targetPath) )
return ret
with ExcelLib(fileName = targetPath, mode = ExcelLib.READ_MODE) as ex... | 0.017751 |
def _set_priority_mapping_table(self, v, load=False):
"""
Setter method for priority_mapping_table, mapped from YANG variable /policy_map/class/priority_mapping_table (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_priority_mapping_table is considered as a pr... | 0.005808 |
def CopyToDateTimeString(cls, time_elements_tuple, fraction_of_second):
"""Copies the time elements and fraction of second to a string.
Args:
time_elements_tuple (tuple[int, int, int, int, int, int]):
time elements, contains year, month, day of month, hours, minutes and
seconds.
... | 0.001988 |
def _get_manifest_list(self, image):
"""try to figure out manifest list"""
if image in self.manifest_list_cache:
return self.manifest_list_cache[image]
manifest_list = get_manifest_list(image, image.registry,
insecure=self.parent_registry_in... | 0.00412 |
def mach2cas(M, h):
""" Mach to CAS conversion """
tas = mach2tas(M, h)
cas = tas2cas(tas, h)
return cas | 0.008333 |
def _get_existing_conf(config):
"""
Read existing local.conf and strip out service id and client secret
:param config: Location of config files
:param lines of existing config (excluding service id and client secret)
"""
try:
with open(os.path.join(config, 'local.conf'), 'r') as f:
... | 0.003854 |
def get_property_id_from_set_topic(self, topic):
"""Return the property id from topic as integer"""
topic = topic.decode()
return int(topic.split("/")[-3].split("_")[-1]) | 0.010309 |
def show_stack(name=None, profile=None):
'''
Return details about a specific stack (heat stack-show)
name
Name of the stack
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' heat.show_stack name=mystack profile=openstack1
'''
h_client = _auth(... | 0.000836 |
def handlePosition(self, msg):
""" handle positions changes """
# log handler msg
self.log_msg("position", msg)
# contract identifier
contract_tuple = self.contract_to_tuple(msg.contract)
contractString = self.contractString(contract_tuple)
# try creating the c... | 0.002237 |
def retrieve_keys(bucket, key, prefix='', postfix='', delim='/',
directories=False, recursive=False):
"""
Retrieve keys from a bucket
"""
if key and prefix:
assert key.endswith(delim)
key += prefix
# check whether key is a directory
... | 0.006993 |
def get_property(obj, name):
"""
Recursively gets value of object or its subobjects property specified by its name.
The object can be a user defined object, map or array.
The property name correspondently must be object property, map key or array index.
:param obj: an object to... | 0.010782 |
def keys(self, *args, **kwargs):
"""
Show the available formatoptions in this project
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
... | 0.003636 |
def _set_book_view(self, session):
"""Sets the underlying book view to match current view"""
if self._book_view == COMPARATIVE:
try:
session.use_comparative_book_view()
except AttributeError:
pass
else:
try:
sess... | 0.004963 |
def use_pickle():
"""Revert to using stdlib pickle.
Reverts custom serialization enabled by use_dill|cloudpickle.
"""
from . import serialize
serialize.pickle = serialize._stdlib_pickle
# restore special function handling
can_map[FunctionType] = _original_can_map[FunctionType] | 0.003257 |
def re_raise(self):
""" Raise this exception with the original traceback """
if self.exc_info is not None:
six.reraise(type(self), self, self.exc_info[2])
else:
raise self | 0.009132 |
def by_bounding_box(self, tl_lat, tl_long, br_lat, br_long, term=None, num_biz_requested=None, category=None):
"""
Perform a Yelp Review Search based on a map bounding box.
Args:
tl_lat - bounding box top left latitude
tl_long - bounding box top left longitude
... | 0.025664 |
def update_cache(self):
"""Reset the lal cache. This can be used to update the cache if the
result may change due to more files being added to the filesystem,
for example.
"""
cache = locations_to_cache(self.frame_src, latest=True)
stream = lalframe.FrStreamCacheOpen(cach... | 0.005698 |
def get_current_user_info(anchore_auth):
"""
Return the metadata about the current user as supplied by the anchore.io service. Includes permissions and tier access.
:return: Dict of user metadata
"""
user_url = anchore_auth['client_info_url'] + '/' + anchore_auth['username']
user_timeout = 60
... | 0.006289 |
def matches_requirement(req, wheels):
"""List of wheels matching a requirement.
:param req: The requirement to satisfy
:param wheels: List of wheels to search.
"""
try:
from pkg_resources import Distribution, Requirement
except ImportError:
raise RuntimeError("Cannot use require... | 0.003263 |
def sparse_clip_norm(parameters, max_norm, norm_type=2) -> float:
"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Supports sparse gradients.
Parameters
---... | 0.000583 |
def encoder(f, blocksize, seed=None, c=sampler.DEFAULT_C, delta=sampler.DEFAULT_DELTA):
"""Generates an infinite sequence of blocks to transmit
to the receiver
"""
# Generate seed if not provided
if seed is None:
seed = randint(0, 1 << 31 - 1)
# get file blocks
filesize, blocks = _... | 0.00464 |
def load(self, path):
"""Load a set of constructs into the CLIPS data base.
Constructs can be in text or binary format.
The Python equivalent of the CLIPS load command.
"""
try:
self._load_binary(path)
except CLIPSError:
self._load_text(path) | 0.006309 |
def as_dict(self):
"""
Json-serializable dict representation.
"""
d = MSONable.as_dict(self)
d["translation_vector"] = self.translation_vector.tolist()
return d | 0.009615 |
def parse_usage(machine, usage, date, machine_name, log_type):
"""
Parses usage
"""
assert machine.name == machine_name
year, month, day = date.split('-')
date = datetime.date(int(year), int(month), int(day))
return parse_logs(usage, date, machine_name, log_type) | 0.003413 |
def _kl_sample(a, b, name='kl_sample'):
"""Batched KL divergence `KL(a || b)` for Sample distributions.
We can leverage the fact that:
```
KL(Sample(a) || Sample(b)) = sum(KL(a || b))
```
where the sum is over the `sample_shape` dims.
Args:
a: Instance of `Sample` distribution.
b: Instance of ... | 0.008197 |
def from_config(cls, cp, **kwargs):
r"""Initializes an instance of this class from the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
\**kwargs :
All additional keyword arguments are passed to the class. Any... | 0.002123 |
def _set_options(self, qobj_config=None, backend_options=None):
"""Set the backend options for all experiments in a qobj"""
# Reset default options
self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"]
self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"]
... | 0.002567 |
def _generate_struct_class_repr(self, data_type):
"""
Generates something like:
def __repr__(self):
return 'Employee(first_name={!r}, last_name={!r}, age={!r})'.format(
self._first_name_value,
self._last_name_value,
... | 0.002591 |
def in_git_clone():
"""Returns `True` if the current directory is a git repository
Logic is 'borrowed' from :func:`git.repo.fun.is_git_dir`
"""
gitdir = '.git'
return os.path.isdir(gitdir) and (
os.path.isdir(os.path.join(gitdir, 'objects')) and
os.path.isdir(os.path.join(gitdir, 'r... | 0.002571 |
async def _await_all(self):
"""Async component of _run"""
delay = 0.0
# we run a top-level nursery that automatically reaps/cancels for us
async with trio.open_nursery() as nursery:
while self.running.is_set():
await self._start_payloads(nursery=nursery)
... | 0.004032 |
def check_lat_extents(self, ds):
'''
Check that the values of geospatial_lat_min/geospatial_lat_max
approximately match the data.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
if not (hasattr(ds, 'geospatial_lat_min') or hasattr(ds, 'geospatial_lat_max')):
... | 0.005409 |
def search_references(
self, reference_set_id, accession=None, md5checksum=None):
"""
Returns an iterator over the References fulfilling the specified
conditions from the specified Dataset.
:param str reference_set_id: The ReferenceSet to search.
:param str accession... | 0.001783 |
def on_message(self):
# type: () -> Callable
"""Decorator.
Decorator to handle all messages that have been subscribed and that
are not handled via the `on_message` decorator.
**Note:** Unlike as written in the paho mqtt documentation this
callback will not be called if ... | 0.00358 |
def sort(self):
"""
Sort the families by template name.
.. rubric:: Example
>>> party = Party(families=[Family(template=Template(name='b')),
... Family(template=Template(name='a'))])
>>> party[0]
Family of 0 detections from template b
... | 0.004149 |
def extend(self, other):
"""
Return a new HyperparameterDefaults instance containing the
hyperparameters from the current instance combined with
those from other.
It is an error if self and other have any hyperparameters in
common.
"""
overlap = [key for ... | 0.003328 |
def enable() -> None:
"""Patch ``sys.stdout`` to use ``DebugPrint``."""
if not isinstance(sys.stdout, DebugPrint):
sys.stdout = DebugPrint(sys.stdout) | 0.011236 |
def avoid_dead_links(root, machine, wrap_around=False):
"""Modify a RoutingTree to route-around dead links in a Machine.
Uses A* to reconnect disconnected branches of the tree (due to dead links
in the machine).
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingT... | 0.000273 |
def _update_object(object_key: str, event: Event):
"""Update the events list and events data for the object.
- Adds the event Id to the list of events for the object.
- Adds the event data to the hash of object event data keyed by event
id.
Args:
object_key (str): Key of the object being... | 0.001393 |
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
) | 0.01 |
def extract_parameters(pil, keys=None):
"""Extract and return parameter names and values from a pil object
Parameters
----------
pil : `Pil` object
keys : list
List of parameter names, if None, extact all parameters
Returns
-------
out_dict : dict
Dictionary with par... | 0.001761 |
def initialize_plugin(self):
"""
Initialize plugin: connect signals, setup actions, etc.
It must be run at the end of __init__
"""
self.create_toggle_view_action()
self.plugin_actions = self.get_plugin_actions() + [MENU_SEPARATOR,
... | 0.002561 |
def get_port_channel_detail_output_lacp_aggr_member_sync(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel_deta... | 0.003252 |
def get_setup_version(reponame):
"""Use autover to get up to date version."""
# importing self into setup.py is unorthodox, but param has no
# required dependencies outside of python
from param.version import Version
return Version.setup_version(os.path.dirname(__file__),reponame,archive_commit="$Fo... | 0.012121 |
async def api_call(self, path, body=None, full_url=False):
"""Make the actual call to the HMIP server.
Throws `HmipWrongHttpStatusError` or `HmipConnectionError` if connection has failed or
response is not correct."""
result = None
if not full_url:
path = self... | 0.003238 |
def bookmark_list():
"""
Executor for `globus bookmark list`
"""
client = get_client()
bookmark_iterator = client.bookmark_list()
def get_ep_name(item):
ep_id = item["endpoint_id"]
try:
ep_doc = client.get_endpoint(ep_id)
return display_name_or_cname(ep_... | 0.001186 |
def get_transition(self, frame_idx, env_idx):
""" Single transition with given index """
past_frame, future_frame = self.get_frame_with_future(frame_idx, env_idx)
data_dict = {
'observations': past_frame,
'observations_next': future_frame,
'actions': self.act... | 0.004839 |
def __updateNavButtons(self):
"""
Updates the navigation buttons that might be on the device screen.
"""
navButtons = None
for v in self.views:
if v.getId() == 'com.android.systemui:id/nav_buttons':
navButtons = v
break
if navB... | 0.006865 |
def add_unit(unit,**kwargs):
"""
Add the unit defined into the object "unit" to the DB
If unit["project_id"] is None it means that the unit is global, otherwise is property of a project
If the unit exists emits an exception
A minimal example:
.. code-block:: python
... | 0.004961 |
def sympy_to_py(func, args):
"""
Turn a symbolic expression into a Python lambda function,
which has the names of the variables and parameters as it's argument names.
:param func: sympy expression
:param args: variables and parameters in this model
:return: lambda function to be used for numeri... | 0.000425 |
def generate_unicode_table():
"""Generate the Unicode table for the given Python version."""
uver = get_unicodedata()
fail = False
path = os.path.join(os.path.dirname(__file__), 'tools')
fp, pathname, desc = imp.find_module('unipropgen', [path])
try:
unipropgen = imp.load_module('unipro... | 0.001414 |
def plot_root_to_tip(self, add_internal=False, label=True, ax=None):
"""
Plot root-to-tip regression
Parameters
----------
add_internal : bool
If true, plot inte`rnal node positions
label : bool
If true, label the plots
ax : matplotlib axe... | 0.004054 |
def is_bridge(self):
"""bool: Is this zone a bridge?"""
# Since this does not change over time (?) check whether we already
# know the answer. If so, there is no need to go further
if self._is_bridge is not None:
return self._is_bridge
# if not, we have to get it from... | 0.003883 |
def load_more_data(self, value, rows=False, columns=False):
"""Load more rows and columns to display."""
try:
if rows and value == self.verticalScrollBar().maximum():
self.model().fetch_more(rows=rows)
self.sig_fetch_more_rows.emit()
if colum... | 0.00314 |
def reserve_free_tcp_port(self):
"""
Reserve free TCP port to be used by Cloud SQL Proxy
"""
self.reserved_tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.reserved_tcp_socket.bind(('127.0.0.1', 0))
self.sql_proxy_tcp_port = self.reserved_tcp_socket.get... | 0.009009 |
def collect_and_report(self):
"""
Target function for the metric reporting thread. This is a simple loop to
collect and report entity data every 1 second.
"""
logger.debug("Metric reporting thread is now alive")
def metric_work():
self.process()
... | 0.006885 |
def get(self, bucket=None, key=None, version_id=None, upload_id=None,
uploads=None, download=None):
"""Get object or list parts of a multpart upload.
:param bucket: The bucket (instance or id) to get the object from.
(Default: ``None``)
:param key: The file key. (Default... | 0.003155 |
def time_average_vel(self, depth):
"""Calculate the time-average velocity.
Parameters
----------
depth: float
Depth over which the average velocity is computed.
Returns
-------
avg_vel: float
Time averaged velocity.
"""
de... | 0.00443 |
def _get_children_by_tag_name(node, name):
"""Retrieve all children from node 'node' with name 'name'."""
try:
return [child for child in node.childNodes if child.nodeName == name]
except TypeError:
return [] | 0.004237 |
def _addrs2nodes(addrs, G):
"""Map agent addresses to nodes in the graph.
"""
for i, n in enumerate(G.nodes()):
G.node[n]['addr'] = addrs[i] | 0.00625 |
def send(self, message):
"""Publish a command string to the gateway via MQTT."""
if not message:
return
topic, payload, qos = self._parse_message_to_mqtt(message)
try:
_LOGGER.debug('Publishing %s', message.strip())
self._pub_callback(topic, payload, q... | 0.004132 |
def pluck_each(records, columns):
"""Return the records with the selected columns
:param records: a list of dictionaries
:param columns: a list or a tuple
:returns: a list of dictionaries with the selected columns
>>> movies = [
... {'title': 'The Holy Grail', 'year': 1975, 'budget': 4E5, 'tot... | 0.006329 |
def SelectPoint():
"""
Opens an eDNA point picker, where the user can select a single tag.
:return: selected tag name
"""
# Define all required variables in the correct ctypes format
pszPoint = create_string_buffer(20)
nPoint = c_ushort(20)
# Opens the point picker
dna_dll... | 0.002315 |
def _16bit_oper(op1, op2=None, reversed=False):
''' Returns pop sequence for 16 bits operands
1st operand in HL, 2nd operand in DE
For subtraction, division, etc. you can swap operators extraction order
by setting reversed to True
'''
output = []
if op1 is not None:
op1 = str(op1) ... | 0.000461 |
def transform(self, data):
"""
:param data: DataFrame with column to encode
:return: encoded Series
"""
with timer('transform %s' % self.name, logging.DEBUG):
transformed = super(Token, self).transform(self.tokenize(data))
return transformed.reshape((len(d... | 0.005747 |
def lsr_pairwise_dense(comp_mat, alpha=0.0, initial_params=None):
"""Compute the LSR estimate of model parameters given dense data.
This function implements the Luce Spectral Ranking inference algorithm
[MG15]_ for dense pairwise-comparison data.
The data is described by a pairwise-comparison matrix `... | 0.000565 |
def insertMenuBefore(self, before_menu, new_menu):
"""
Insert a menu after another menu in the menubar
@type: before_menu QMenu instance or title string of menu
@param before_menu: menu which should be after the newly inserted menu
@rtype: QAction instance
@return: actio... | 0.002762 |
def publish_article(article, language, changed_by=None):
"""
Publish an article. This sets `article.published` to `True`
and calls article.publish() which does the actual publishing.
"""
article = article.reload()
# get username
if changed_by:
username = changed_by.get_username()
... | 0.002212 |
def simulate(args):
"""
%prog simulate run_dir 1 300
Simulate BAMs with varying inserts with dwgsim. The above command will
simulate between 1 to 300 CAGs in the HD region, in a directory called
`run_dir`.
"""
p = OptionParser(simulate.__doc__)
p.add_option("--method", choices=("wgsim",... | 0.000848 |
def shannon_entropy(pvec, base=2):
"""
Compute the Shannon entropy of a probability vector.
The shannon entropy of a probability vector pv is defined as
$H(pv) = - \\sum_j pv[j] log_b (pv[j])$ where $0 log_b 0 = 0$.
Args:
pvec (array_like): a probability vector.
base (int): the bas... | 0.001295 |
def get_spark_context(conf=None):
"""
Get the current active spark context and create one if no active instance
:param conf: combining bigdl configs into spark conf
:return: SparkContext
"""
if hasattr(SparkContext, "getOrCreate"):
with SparkContext._lock:
if SparkContext._ac... | 0.001098 |
def fromstring(data) -> 'Obj':
'''
Args:
data (str): The obj file content.
Returns:
Obj: The object.
Examples:
.. code-block:: python
import ModernGL
from ModernGL.ext import obj
... | 0.002401 |
def _verify_names(sampler, var_names, arg_names):
"""Make sure var_names and arg_names are assigned reasonably.
This is meant to run before loading emcee objects into InferenceData.
In case var_names or arg_names is None, will provide defaults. If they are
not None, it verifies there are the right numb... | 0.002142 |
def _save_image(image, filename, return_img=None):
"""Internal helper for saving a NumPy image array"""
if not image.size:
raise Exception('Empty image. Have you run plot() first?')
# write screenshot to file
if isinstance(filename, str):
if isinstance(vtki.FIGU... | 0.005102 |
def validate(self):
""" validate: Makes sure single selection question is valid
Args: None
Returns: boolean indicating if single selection question is valid
"""
try:
assert self.question_type == exercises.SINGLE_SELECTION, "Assumption Failed: Question should b... | 0.006902 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.