Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
351,900 | def _diff_emit_update(self, new_bookmarks):
self.logger.debug("diffing %s, %s", self._bookmark_cache,
new_bookmarks)
def subdivide(level, old, new):
if len(old) == len(new) == 1:
old_entry = old.pop()
new_entry... | Diff the bookmark cache and the new bookmark state, emit signals as
needed and set the bookmark cache to the new data. |
351,901 | def _create_random_layer(self):
return RandomLayer(n_hidden=self.n_hidden,
alpha=self.alpha,
random_state=self.random_state,
activation_func=self.activation_func,
activation_args=self.activation... | Pass init params to RandomLayer |
351,902 | def params_size(num_components, component_params_size, name=None):
with tf.compat.v1.name_scope(name, ,
[num_components, component_params_size]):
num_components = tf.convert_to_tensor(
value=num_components, name=, dtype_hint=tf.int32)
component_params_size... | Number of `params` needed to create a `MixtureSameFamily` distribution.
Arguments:
num_components: Number of component distributions in the mixture
distribution.
component_params_size: Number of parameters needed to create a single
component distribution.
name: The name to use for... |
351,903 | def append_rez_path(self):
if system.rez_bin_path:
self.env.PATH.append(system.rez_bin_path) | Append rez path to $PATH. |
351,904 | def showDfs(d):
if "metadata" in d:
print("metadata")
if "paleoData" in d:
try:
for k, v in d["paleoData"].items():
print(k)
except KeyError:
pass
except AttributeError:
pass
if "chronData" in d:
try:
... | Display the available data frame names in a given data frame collection
:param dict d: Dataframe collection
:return none: |
351,905 | def get_property(self, name=None):
if (name):
return self._interface.GetProperties()[name]
else:
return self._interface.GetProperties() | Helper to get a property value by name or all
properties as a dictionary.
See also :py:meth:`set_property`
:param str name: defaults to None which means all properties
in the object's dictionary are returned as a dict.
Otherwise, the property name key is used and its va... |
351,906 | def load_module(self, mod):
try:
return sys.modules[mod]
except KeyError:
pass
lib = ExtensionImporter.extension_modules[mod]
m = imp.load_dynamic(mod, lib)
sys.modules[mod] = m
return m | Load the extension using the load_dynamic method. |
351,907 | def table(self, datatype=None, **kwargs):
if config.future_deprecations:
self.param.warning("The table method is deprecated and should no "
"longer be used. If using a HoloMap use "
"HoloMap.collapse() instead to return a Dataset... | Deprecated method to convert an MultiDimensionalMapping of
Elements to a Table. |
351,908 | def rotate(self, angle):
perp = Vector(-self.y, self.x)
angle = angle * math.pi / 180.0
c, s = math.cos(angle), math.sin(angle)
return Vector(self.x * c + perp.x * s, self.y * c + perp.y * s) | Rotates self counterclockwise by angle
(the angle must be given in a 360 degree system) |
351,909 | def shape(self):
shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)()
dim = _ctypes.c_size_t()
status_code = self._LIB.TCMPSGetFloatArrayShape(
self.handle, _ctypes.byref(shape_ptr), _ctypes.byref(dim))
assert status_code == ... | Copy the shape from TCMPS as a new numpy ndarray. |
351,910 | def metric(self, name, description, data_type, interval, keyed=False):
from .tcex_metrics_v2 import TcExMetricsV2
return TcExMetricsV2(self, name, description, data_type, interval, keyed) | Get instance of the Metrics module.
Args:
name (string): The name for the metric.
description (string): The description of the metric.
data_type (string): The type of metric: Sum, Count, Min, Max, First, Last, and Average.
interval (string): The metric interval: ... |
351,911 | async def close(self):
await self._close()
req = protocol.CloseRequest()
req.clientID = self._client_id
msg = await self._nc.request(
self._close_req_subject,
req.SerializeToString(),
self._connect_timeout,
)
res... | Close terminates a session with NATS Streaming. |
351,912 | def runExperiment5B(dirName):
resultsName = os.path.join(dirName, "sensorimotor_batch_results_more_objects.pkl")
numTrials = 10
featureRange = [10, 50, 100, 150, 500]
objectRange = [110, 130, 200, 300]
locationRange = [100]
runExperimentPool(
numSequences=[0],
numObjects=objectRa... | This runs the second experiment in the section "Simulations with Sensorimotor
Sequences". It averages over many parameter combinations. This experiment
could take several hours. You can run faster versions by reducing the number
of trials. |
351,913 | def find_files(base_dir, extensions, exclude_dirs=list()):
result = []
for root, dir_names, file_names in os.walk(base_dir):
for filename in file_names:
candidate = os.path.join(root, filename)
if should_include_file_in_search(candidate, extensions, exclude_dirs):
... | Find all files matching the given extensions.
Args:
base_dir (str): Path of base directory to search in.
extensions (list): A list of file extensions to search for.
exclude_dirs (list): A list of directories to exclude from search.
Returns:
list of paths that match the search |
351,914 | def collect(self):
instances = {}
for device in os.listdir():
instances.update(self.match_device(device, ))
for device_id in os.listdir():
instances.update(self.match_device(device, ))
metrics = {}
for device, p in instances.i... | Collect and publish disk temperatures |
351,915 | def get(self, username, width=None, height=None):
url = "/users/{username}".format(username=username)
params = {
"w": width,
"h": height
}
result = self._get(url, params=params)
return UserModel.parse(result) | Retrieve public details on a given user.
Note: Supplying the optional w or h parameters will result
in the 'custom' photo URL being added to the 'profile_image' object:
:param username [string]: The user’s username. Required.
:param width [integer]: Profile image width in pixels.
... |
351,916 | def genCubeVector(x, y, z, x_mult=1, y_mult=1, z_mult=1):
cX = (x - 1) / 2.0
cY = (y - 1) / 2.0
cZ = (z - 1) / 2.0
def vect(_x, _y, _z):
return int(math.sqrt(math.pow(_x - cX, 2 * x_mult) +
math.pow(_y - cY, 2 * y_mult) +
m... | Generates a map of vector lengths from the center point to each coordinate
x - width of matrix to generate
y - height of matrix to generate
z - depth of matrix to generate
x_mult - value to scale x-axis by
y_mult - value to scale y-axis by
z_mult - value to scale z-axis by |
351,917 | def all_subs(bounds):
idx_list = []
for i in range(len(bounds)):
this_dim = bounds[i]
lo,hi = this_dim[0],this_dim[1]
this_dim_idxs = range(lo,hi+1)
idx_list.append(this_dim_idxs)
return idx2subs(idx_list) | given a list of tuples specifying the bounds of an array, all_subs()
returns a list of all the tuples of subscripts for that array. |
351,918 | def process_msg3(fname):
with open(fname, ) as infile:
info = []
for lineno, line in enumerate(infile):
parts = line.split()
try:
var_name, desc, typ, units = parts[:4]
size_hw = parts[-1]
if in size_hw:
... | Handle information for message type 3. |
351,919 | def umount(cls, device_or_directory, cmd_timeout=None, sudo=False):
cmd = [] if sudo is False else []
cmd.extend([, device_or_directory])
subprocess.check_output(cmd, timeout=cmd_timeout) | Unmount device (or mount directory)
:param device_or_directory: device name or mount directory to unmount
:param cmd_timeout: if specified - timeout with which this unmount command should be evaluated (if \
command isn't complete within the given timeout - an exception will be raised)
:param sudo: whether to u... |
351,920 | def jpath_values(structure, jpath):
nodes_a = [structure]
nodes_b = []
chunks = jpath_parse_c(jpath)
for chnk in chunks:
for node in nodes_a:
key = chnk[]
if not isinstance(node, dict) and not isinstance(node, collections.Mapping):
... | Return all values at given JPath within given data structure.
For performance reasons this method is intentionally not written as
recursive.
:param str structure: data structure to be searched
:param str jpath: JPath to be evaluated
:return: found values as a list
:rtype: :py:class:`list` |
351,921 | def _users_from_environ(env_prefix=):
auth_string = os.environ.get(env_prefix + )
if not auth_string:
return {}
result = {}
for credentials in auth_string.split():
username, password = credentials.split(, 1)
result[username] = password
return result | Environment value via `user:password|user2:password2` |
351,922 | def init (domain, directory, loc=None):
global default_language, default_encoding, default_domain, default_directory
default_directory = directory
default_domain = domain
if os.path.isdir(directory):
for lang in os.listdir(directory):
path = os.path.join(directory, lang... | Initialize this gettext i18n module. Searches for supported languages
and installs the gettext translator class. |
351,923 | def Akers_Deans_Crosser(m, rhog, rhol, kl, mul, Cpl, D, x):
r
G = m/(pi/4*D**2)
Ge = G*((1-x) + x*(rhol/rhog)**0.5)
Ree = D*Ge/mul
Prl = mul*Cpl/kl
if Ree > 5E4:
C, n = 0.0265, 0.8
else:
C, n = 5.03, 1/3.
Nu = C*Ree**n*Prl**(1/3.)
return Nu*kl/D | r'''Calculates heat transfer coefficient for condensation
of a pure chemical inside a vertical tube or tube bundle, as presented in
[2]_ according to [1]_.
.. math::
Nu = \frac{hD_i}{k_l} = C Re_e^n Pr_l^{1/3}
C = 0.0265, n=0.8 \text{ for } Re_e > 5\times10^4
C = 5... |
351,924 | def create_packets_from_results(self, packet_name, result_set):
try:
pkt_defn = tlm.getDefaultDict()[packet_name]
except KeyError:
log.error(.format(packet_name))
return None
pkt = tlm.Packet(pkt_defn)
pkts = []
for r in result_set.g... | Generate AIT Packets from a InfluxDB query ResultSet
Extract Influx DB query results into one packet per result entry. This
assumes that telemetry data was inserted in the format generated by
:func:`InfluxDBBackend.insert`. Complex types such as CMD16 and EVR16 are
evaluated if they can... |
351,925 | def post_helper(form_tag=True, edit_mode=False):
helper = FormHelper()
helper.form_action =
helper.attrs = {: }
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
,
css_class=
),
),
]
if not edit_... | Post's form layout helper |
351,926 | def get_text_from_node(self, node, regex=None, group=1):
text = self._get_stripped_text_from_node(node)
if regex is not None:
text = self._filter_by_regex(regex, text, group)
return text | Get text from node and filter if necessary. |
351,927 | def process_document(self, doc):
segment = doc.select_segments("target_text")[0]
for e in self.e_list:
res = doc.extract(e, segment)
doc.store(res, e.name)
return list() | Add your code for processing the document |
351,928 | def ok(self, data, schema=None, envelope=None):
data = marshal(data, schema, envelope)
return self.__make_response(data) | Gets a 200 response with the specified data.
:param data: The content value.
:param schema: The schema to serialize the data.
:param envelope: The key used to envelope the data.
:return: A Flask response object. |
351,929 | def execute_transactions(conn, statements: Iterable):
with conn.cursor() as cursor:
for statement in statements:
try:
cursor.execute(statement)
conn.commit()
except psycopg2.ProgrammingError:
conn.rollback() | Execute several statements each as a single DB transaction. |
351,930 | def _create_component(cls, att, value):
if value == CPEComponent2_3_URI.VALUE_UNDEFINED:
comp = CPEComponentUndefined()
elif (value == CPEComponent2_3_URI.VALUE_ANY or
value == CPEComponent2_3_URI.VALUE_EMPTY):
comp = CPEComponentAnyValue()
elif (v... | Returns a component with value "value".
:param string att: Attribute name
:param string value: Attribute value
:returns: Component object created
:rtype: CPEComponent
:exception: ValueError - invalid value of attribute |
351,931 | def download_attachments(self):
if not self._parent.has_attachments:
log.debug(
.format(
self._parent.__class__.__name__))
return False
if not self._parent.object_id:
raise RuntimeError(
.format(
... | Downloads this message attachments into memory.
Need a call to 'attachment.save' to save them on disk.
:return: Success / Failure
:rtype: bool |
351,932 | def html(self):
return self.render(self.data, self.proj, self.obj) | Wrapper for only doing the rendering on request (drastically reduces memory) |
351,933 | def get_portchannel_info_by_intf_output_lacp_partner_oper_port(self, **kwargs):
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
output = ET.SubElement(get_portchannel_info_by_intf, "out... | Auto Generated Code |
351,934 | def _EntriesGenerator(self):
location = getattr(self.path_spec, , None)
part_index = getattr(self.path_spec, , None)
start_offset = getattr(self.path_spec, , None)
if (part_index is None and start_offset is None and
location is not None and location == self._file_system.LOCATION_ROOT)... | Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
TSKPartitionPathSpec: a path specification. |
351,935 | def siblings(client, revision, paths):
graph = Graph(client)
nodes = graph.build(paths=paths, revision=revision)
siblings_ = set(nodes)
for node in nodes:
siblings_ |= graph.siblings(node)
paths = {node.path for node in siblings_}
for path in paths:
click.echo(graph._format... | Show siblings for given paths. |
351,936 | def clear_assets(self):
if (self.get_assets_metadata().is_read_only() or
self.get_assets_metadata().is_required()):
raise errors.NoAccess()
self._my_map[] = self._assets_default | Clears the assets.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
351,937 | def plot_dense_array(
arr, length=256, ranges=None, colors=("
import numpy
from PIL import Image
from base64 import b64encode
from tempfile import TemporaryFile
from math import sqrt
from IPython.core.display import display, HTML
from functools import reduce
def unfold... | Volume renderer
Parameters
----------
arr : list of numpy.array
i.e. [array([[1,2,3], [2,3,4]]), array([[1,2,3]])]
ranges : list of tuple
ranges for x, y, and z axis
i.e. [(-100, 100), (-100, 100), (-100, 100)]
colors : list of string
colors for species
length : ... |
351,938 | def export_rule_data(variables, actions):
from . import operators
actions_data = actions.get_all_actions()
variables_data = variables.get_all_variables()
variable_type_operators = {}
for variable_class in inspect.getmembers(operators, lambda x: getattr(x, , False)):
variable_type = vari... | export_rule_data is used to export all information about the
variables, actions, and operators to the client. This will return a
dictionary with three keys:
- variables: a list of all available variables along with their label, type and options
- actions: a list of all actions along with their label and... |
351,939 | def _checkRewardsListLike(reward, n_actions, n_states):
try:
lenR = len(reward)
if lenR == n_actions:
dim1, dim2, dim3 = _checkDimensionsListLike(reward)
elif lenR == n_states:
dim1 = n_actions
dim2 = dim3 = lenR
else:
raise _error... | Check that a list-like reward input is valid. |
351,940 | def create_issue(title, body, repo, token):
s personal Github token
/https://api.github.com/repos/%s/%s/issuestitlebodyhtml_urlCannot create issue. Does your token have scope repo?Cannot create issue %s' %title)
bot.error(response.content)
sys.exit(1) | create a Github issue, given a title, body, repo, and token.
Parameters
==========
title: the issue title
body: the issue body
repo: the full name of the repo
token: the user's personal Github token |
351,941 | def list_build_records_for_set(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
content = list_build_records_for_set_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | List all build records for a BuildConfigurationSet |
351,942 | def get_queryset(self, *args, **kwargs):
qs = super(AutoPrefetchMixin, self).get_queryset(*args, **kwargs)
included_resources = get_included_resources(self.request)
for included in included_resources:
included_model = None
levels = included.split()
l... | This mixin adds automatic prefetching for OneToOne and ManyToMany fields. |
351,943 | def lower_bound(fm, nr_subs = None, nr_imgs = None, scale_factor = 1):
nr_subs_total = len(np.unique(fm.SUBJECTINDEX))
if nr_subs is None:
nr_subs = nr_subs_total - 1
assert (nr_subs < nr_subs_total)
sb_scores = []
for measure in range(len(measures.scores)):
res_dict =... | Compute the spatial bias lower bound for a fixmat.
Input:
fm : a fixmat instance
nr_subs : the number of subjects used for the prediction. Defaults
to the total number of subjects in the fixmat minus 1
nr_imgs : the number of images used for prediction. If given, the
... |
351,944 | def get_retry(codes=(), max_attempts=8, min_delay=1, log_retries=False):
max_delay = max(min_delay, 2) ** max_attempts
def _retry(func, *args, **kw):
for idx, delay in enumerate(
backoff_delays(min_delay, max_delay, jitter=True)):
try:
return func(*args,... | Decorator for retry boto3 api call on transient errors.
https://www.awsarchitectureblog.com/2015/03/backoff.html
https://en.wikipedia.org/wiki/Exponential_backoff
:param codes: A sequence of retryable error codes.
:param max_attempts: The max number of retries, by default the delay
time is ... |
351,945 | def file_encrypt( blockchain_id, hostname, recipient_blockchain_id_and_hosts, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ):
config_dir = os.path.dirname(config_path)
key_info = file_key_lookup( blockchain_id, 0, hostname, config_path=config_path, wallet_keys=w... | Encrypt a file for a set of recipients.
@recipient_blockchain_id_and_hosts must contain a list of (blockchain_id, hostname)
Return {'status': True, 'sender_key_id': ...} on success, and write ciphertext to output_path
Return {'error': ...} on error |
351,946 | def _build_ds_from_instruction(instruction, ds_from_file_fn):
examples_ds = ds_from_file_fn(instruction["filepath"])
mask_ds = _build_mask_ds(
mask_offset=instruction["mask_offset"],
mask=instruction["mask"],
)
ds = tf.data.Dataset.zip((examples_ds, mask_ds))
ds = ds.filter(lambda exa... | Map an instruction to a real datasets for one particular shard.
Args:
instruction: A `dict` of `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `fct`, function which returns the dataset associated to
the filename
Returns:
dataset: `t... |
351,947 | def asDict(self):
dct = super(RtiRegItem, self).asDict()
dct[] = self.extensions
return dct | Returns a dictionary for serialization. |
351,948 | def add_series(self, name, values=(), number_format=None):
series_data = CategorySeriesData(self, name, number_format)
self.append(series_data)
for value in values:
series_data.add_data_point(value)
return series_data | Add a series to this data set entitled *name* and having the data
points specified by *values*, an iterable of numeric values.
*number_format* specifies how the series values will be displayed,
and may be a string, e.g. '#,##0' corresponding to an Excel number
format. |
351,949 | def get_fn(callable):
if _inspect.isfunction(callable):
return callable
if _inspect.ismethod(callable):
try:
return callable.__func__
except AttributeError:
return callable.__func__
if _inspect.isclass(callable):
return callable.__init__.__func__
... | Returns the underlying function that will be called by the () operator.
* For regular functions, returns ``callable``
* For bound methods, returns ``callable.im_func``
* For unbound methods, returns ``callable.__func__``
* For classes, returns ``callable.__init__.__func__``.
* F... |
351,950 | def remove(self):
self.run_hook()
utils.rmtree(self.path)
self.run_hook() | Remove this environment |
351,951 | def _update_conda_packages():
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, ("Could not find anaconda distribution for upgrading bcbio.\n"
"Using python at %s but could not find conda." % (os.path.realpath(sys.executable)))
req_file ... | If installed in an anaconda directory, upgrade conda packages. |
351,952 | def sample(self, rgen):
x = rgen.poisson(self.lambdaParameter)
return x, self.logDensity(x) | Generates a random sample from the Poisson probability distribution and
returns its value and the log of the probability of sampling that value. |
351,953 | def get_height(self, points, only_in = True, edge=True, full=False):
p = self.get_parametric()
z = (-p[0]*points[:, 0]-p[1]*points[:, 1]-p[3])/p[2]
if only_in:
pip = self.contains(points, edge=edge)
z[pip == False] *= np.nan
... | Given a set of points, it computes the z value for the
parametric equation of the plane where the polygon belongs.
Only the two first columns of the points will be taken into
account as x and y.
By default, the points outside the object will have a NaN value
... |
351,954 | def print_tree(task, indent=, last=True):
with warnings.catch_warnings():
warnings.filterwarnings(action=, message=)
is_task_complete = task.complete()
is_complete = (bcolors.OKGREEN + if is_task_complete else bcolors.OKBLUE + ) + bcolors.ENDC
name = task.__class__.__name__
pa... | Return a string representation of the tasks, their statuses/parameters in a dependency tree format |
351,955 | def reliability_curves(self, prob_thresholds):
all_rel_curves = {}
for model_name in self.model_names:
all_rel_curves[model_name] = {}
for size_threshold in self.size_thresholds:
all_rel_curves[model_name][size_threshold] = {}
for h, hour_... | Output reliability curves for each machine learning model, size threshold, and time window.
:param prob_thresholds:
:param dilation_radius:
:return: |
351,956 | def GetDefaultContract(self):
try:
return self.GetContracts()[0]
except Exception as e:
logger.error("Could not find default contract: %s" % str(e))
raise | Get the default contract.
Returns:
contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception.
Raises:
Exception: if no default contract is found.
Note:
Prints a warning to the console if the default contract c... |
351,957 | def compress(bytes, target):
length = len(bytes)
if target > length:
raise ValueError("Fewer input bytes than requested output")
seg_size = length // target
segments = [bytes[i * seg_size:(i + 1) * seg_size]
for i in range(target)]
... | Compress a list of byte values to a fixed target length.
>>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151]
>>> HumanHasher.compress(bytes, 4)
[205, 128, 156, 96]
Attempting to compress a smaller number of bytes to a larger number is
an error:
... |
351,958 | def as_percent(self, value):
new_vec = self.copy()
new_vec.length = value * self.length
return new_vec | Return a new vector scaled by given decimal percent |
351,959 | def toy_linear_1d_classification(seed=default_seed):
def sample_class(f):
p = 1. / (1. + np.exp(-f))
c = np.random.binomial(1, p)
c = np.where(c, 1, -1)
return c
np.random.seed(seed=seed)
x1 = np.random.normal(-3, 5, 20)
x2 = np.random.normal(3, 5, 20)
X = (np.r... | Simple classification data in one dimension for illustrating models. |
351,960 | def add_episode(db, aid, episode):
values = {
: aid,
: episode.type,
: episode.number,
: episode.title,
: episode.length,
}
upsert(db, , [, , ], values) | Add an episode. |
351,961 | def meanFracdet(map_fracdet, lon_population, lat_population, radius_population):
nside_fracdet = healpy.npix2nside(len(map_fracdet))
map_fracdet_zero = np.where(map_fracdet >= 0., map_fracdet, 0.)
fracdet_population = np.empty(len(lon_population))
for ii in range(0, len(lon_population)):
fr... | Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length |
351,962 | def change(sc=None, app_name=, master=None, wait=, min_cores=None, min_ips=None, timeout=30,
refresh_rate=0.5, fail_on_timeout=False, **kwargs):
if master is None and sc is None:
raise ValueError()
if master is None:
master = sc.getConf().get(u)
if wait == :
... | Returns a new Spark Context (sc) object with added properties set
:param sc: current SparkContext if None will create a new one
:param app_name: name of new spark app
:param master: url to master, if None will get from current sc
:param wait: when to return after asking for a new sc (or max of tim... |
351,963 | def register_edited_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None,
content_types=None, state=None, run_task=None, **kwargs):
filters_set = self.filters_factory.resolve(self.edited_message_handlers,
... | Register handler for edited channel post
:param callback:
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wa... |
351,964 | def get_actions(actions):
new_actions = []
if actions:
for action in actions:
action_obj = get_action(action)
if action_obj:
new_actions.append(action_obj)
return new_actions | Get actions. |
351,965 | def restart(self):
self._assertContextManagerUsed()
self.writePIDFile()
if not self.config.restart:
raise ToilRestartException(
)
from toil.job import JobException
try:
self._jobStore.loadRootJob()
e... | Restarts a workflow that has been interrupted.
:return: The root job's return value |
351,966 | def make_structure(AA_chain,phi,psi_im1,omega=[]):
geo = geometry(AA_chain[0])
struc=initialize_res(geo)
if len(omega)==0:
for i in range(1,len(AA_chain)):
AA = AA_chain[i]
add_residue(struc, AA, phi[i-1], psi_im1[i-1])
else:
for i in range(1,len(AA_chain))... | Place a sequence of amino acids into a peptide with specified
backbone dihedral angles. The argument AA_chain holds the
sequence of amino acids to be used. The arguments phi and psi_im1 hold
lists of backbone angles, one for each amino acid, *starting from
the second amino acid in the chain*. The argume... |
351,967 | def _handle_status(self, key, value):
if key in (
"ENC_TO",
"USERID_HINT",
"GOODMDC",
"END_DECRYPTION",
"BEGIN_SIGNING",
"NO_SECKEY",
"ERROR",
"NODATA",
"CARDC... | Parse a status code from the attached GnuPG process.
:raises: :exc:`~exceptions.ValueError` if the status message is unknown. |
351,968 | def _get_container_string(cont_dict, pid):
config_str = ""
for p, directives in cont_dict.items():
container = ""
if "container" in directives:
container += directives["container"]
if "version" in directives:
conta... | Returns the nextflow containers string from a dictionary object
If the dictionary has at least on of the container directives, these
will be compiled for each process in the dictionary and returned
as a string read for injection in the nextflow config file template.
This dictionary sho... |
351,969 | def keyPressEvent(self, keyEvent):
undoObj = UndoSelfInsert(self, keyEvent.text())
self.qteUndoStack.push(undoObj) | Insert the character at the current cursor position.
This method also adds another undo-object to the undo-stack. |
351,970 | def log_call(self, cmd, callwith=subprocess.check_call,
log_level=logging.DEBUG, **kw):
logger.log(log_level, "%s> call %r", self.cwd, cmd)
ret = callwith(cmd, **kw)
if callwith == subprocess.check_output:
ret = console_to_str(ret)
return ret | Wrap a subprocess call with logging
:param meth: the calling method to use. |
351,971 | def get_col_rgba(color, transparency=None, opacity=None):
r, g, b = color.red, color.green, color.blue
r /= 65535.
g /= 65535.
b /= 65535.
if transparency is not None or opacity is None:
transparency = 0 if transparency is None else transparency
if transparency < 0 or tr... | This class converts a Gdk.Color into its r, g, b parts and adds an alpha according to needs
If both transparency and opacity is None, alpha is set to 1 => opaque
:param Gdk.Color color: Color to extract r, g and b from
:param float | None transparency: Value between 0 (opaque) and 1 (transparent) or None... |
351,972 | def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2**np.arange(3, 6)):
base_anchor = np.array([1, 1, base_size, base_size], dtype=) - 1
ratio_anchors = _ratio_enum(base_anchor, ratios)
anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales)
... | Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window. |
351,973 | def get_marginal_distribution(self, index_points=None):
with self._name_scope():
index_points = self._get_index_points(index_points)
covariance = self._compute_covariance(index_points)
loc = self._mean_fn(index_points)
if self._is_univariate_marginal(index_points):
... | Compute the marginal of this GP over function values at `index_points`.
Args:
index_points: `float` `Tensor` representing finite (batch of) vector(s) of
points in the index set over which the GP is defined. Shape has the form
`[b1, ..., bB, e, f1, ..., fF]` where `F` is the number of feature
... |
351,974 | def set_input_score_start_range(self, score):
if self.get_input_score_start_range_metadata().is_read_only():
raise errors.NoAccess()
try:
score = float(score)
except ValueError:
raise errors.InvalidArgument()
if not self._is_valid_dec... | Sets the input score start range.
arg: score (decimal): the new start range
raise: InvalidArgument - ``score`` is invalid
raise: NoAccess - ``range`` cannot be modified
*compliance: mandatory -- This method must be implemented.* |
351,975 | def set_bias(self, bias):
self.x_offset += (bias - self._bias)
self._bias = bias
self._build_cdict() | Adjusts the image bias.
Bias determines where the color changes start. At low bias, low
intensities (i.e., low pixel values) will have non-zero color
differences, while at high bias only high pixel values will have
non-zero differences
Args:
bias: float
A... |
351,976 | def code_block(
code: str = None,
path: str = None,
language_id: str = None,
title: str = None,
caption: str = None
):
environ.abort_thread()
r = _get_report()
r.append_body(render.code_block(
block=code,
path=path,
language=language_id,
... | Adds a block of syntax highlighted code to the display from either
the supplied code argument, or from the code file specified
by the path argument.
:param code:
A string containing the code to be added to the display
:param path:
A path to a file containing code to be added to the disp... |
351,977 | def _clone(self):
cls = self.__class__
obj = cls.__new__(cls)
obj.items = list(self.items)
return obj | Make a (shallow) copy of the set.
There is a 'clone protocol' that subclasses of this class
should use. To make a copy, first call your super's _clone()
method, and use the object returned as the new instance. Then
make shallow copies of the attributes defined in the subclass.
... |
351,978 | def completed_prefetch(self, blocking_wait=False, max_yield=999):
for worker, obj_id in self.completed(blocking_wait=blocking_wait):
plasma_id = ray.pyarrow.plasma.ObjectID(obj_id.binary())
(ray.worker.global_worker.raylet_client.fetch_or_reconstruct(
[obj_id], ... | Similar to completed but only returns once the object is local.
Assumes obj_id only is one id. |
351,979 | def cmddict(self):
if self._cmddict is None:
self._cmddict = cmd.getDefaultDict()
return self._cmddict | PrimitiveType base for the ComplexType |
351,980 | def basic_query(returns):
return compose(
reusable,
map_send(parse_request),
map_yield(prepare_params, snug.prefix_adder(API_PREFIX)),
map_return(loads(returns)),
oneyield,
) | decorator factory for NS queries |
351,981 | def is_closing(self) -> bool:
return self.stream.closed() or self.client_terminated or self.server_terminated | Return ``True`` if this connection is closing.
The connection is considered closing if either side has
initiated its closing handshake or if the stream has been
shut down uncleanly. |
351,982 | def archive(source, archive, path_in_arc=None, remove_source=False,
compression=zipfile.ZIP_DEFLATED, compresslevel=-1):
archive = Path(archive)
if type(source) is not list:
source_root = str(source)
source_files = [f for f in Path(source).glob() if f.is_file()]
else:
... | Archives a MRIO database as zip file
This function is a wrapper around zipfile.write,
to ease the writing of an archive and removing the source data.
Note
----
In contrast to zipfile.write, this function raises an
error if the data (path + filename) are identical in the zip archive.
Backgr... |
351,983 | def fit(self, features, class_labels):
unique_labels = sorted(np.unique(class_labels))
if len(unique_labels) != 2:
raise ValueError()
self.class_count_matrix = defaultdict(lambda: defaultdict(int))
for row_i in range(features.shape[0]):
feature_... | Constructs the MDR feature map from the provided training data.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
class_labels: array-like {n_samples}
List of true class labels
Returns
-------
self: A copy ... |
351,984 | def run(*args):
if not args:
args = sys.argv[1:]
if len(args) < 2:
print()
sys.exit(0)
os.environ.update(create_env(args[0]))
os.environ[] =
runnable_path = args[1]
if not runnable_path.startswith((, )):
runnable_path = spawn.find_executable(runnable_path... | Load given `envfile` and run `command` with `params` |
351,985 | def to_json(self, formatter=None, tool_long_names=True, **kwargs):
d = self.to_dict(tool_long_names=tool_long_names)
if formatter:
d = formatter(d)
return json.dumps(d, **kwargs) | Get a JSON representation of the workflow
:param tool_long_names: Indicates whether to use long names, such as
SplitterFromStream(element=None, use_mapping_keys_only=True)
or short names, such as
splitter_from_strea... |
351,986 | def joinMeiUyir(mei_char, uyir_char):
if not mei_char: return uyir_char
if not uyir_char: return mei_char
if not isinstance(mei_char, PYTHON3 and str or unicode):
raise ValueError(u"Passed input mei character must be unicode, not just string" % mei_char)
if not isinstance(uyir_char, P... | This function join mei character and uyir character, and retuns as
compound uyirmei unicode character.
Inputs:
mei_char : It must be unicode tamil mei char.
uyir_char : It must be unicode tamil uyir char.
Written By : Arulalan.T
Date : 22.09.2014 |
351,987 | def modify_prefix(channel, new_prefix):
gui = ui_embed.UI(
channel,
"Prefix updated",
"Modis prefix is now `{}`".format(new_prefix),
modulename=modulename
)
return gui | Creates an embed UI containing the prefix modified message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
new_prefix (str): The value of the new prefix
Returns:
embed: The created embed |
351,988 | def delete(self):
if not self.object_id:
return False
url = self.build_url(
self._endpoints.get().format(id=self.object_id))
response = self.con.delete(url)
if not response:
return False
self.object_id = None
return True | Moves this item to the Recycle Bin
:return: Success / Failure
:rtype: bool |
351,989 | def any_values(*values):
values = [_normalize(v) for v in values]
for v in zip(*values):
yield any(v) | Returns the `logical disjunction`_ of all supplied values (the result is
:data:`True` if any of the input values are currently :data:`True`). One or
more *values* can be specified. For example, to light an
:class:`~gpiozero.LED` when *any* button is pressed::
from gpiozero import LED, Button
... |
351,990 | def _response_good(self, respond):
if respond.status_code != requests.codes.ok:
log.warning(.format(
respond.status_code,
respond.url,
respond.text))
if respond.status_code in self.errorsNotRetry:
raise ApiError(usr_m... | check response
Args:
respond (str): HTTP response.
Returns:
bool: True if the response is good, else False.
Raises:
ApiError: response isn't formatted properly. |
351,991 | def save(self):
for prop in dir(self):
if getattr(self, prop) == None: continue
if not prop in self.configVars: continue
if prop == "session":
pic = pickle.dumps(getattr(self, prop).cookies)
comp = zl... | Exports all user attributes to the user's configuration and writes configuration
Saves the values for each attribute stored in User.configVars
into the user's configuration. The password is automatically
encoded and salted to prevent saving it as plaintext. The
session is pickl... |
351,992 | def gcc_checker(code, filename_suffix, arguments, working_directory):
run = run_in_subprocess(code,
filename_suffix,
arguments + [, ],
working_directory=working_directory)
def run_check():
result = run()
... | Return checker. |
351,993 | def get_resource(self, resource, **kwargs):
return resource(request=self.request, response=self.response,
path_params=self.path_params, application=self.application,
**kwargs) | Returns a new instance of the resource class passed in as resource.
This is a helper to make future-compatibility easier when new
arguments get added to the constructor.
:param resource: Resource class to instantiate. Gets called with the
named arguments as required for... |
351,994 | def _verify_client(self, low):
if not in low or low.get() not in self.saltclients:
self.set_status(400)
self.write("400 Invalid Client: Client not found in salt clients")
self.finish()
return False
return True | Verify that the client is in fact one we have |
351,995 | def get(self, pos):
latitude = int(round(pos[]))
search_set = self.bins[latitude]
i = 1
if latitude - i >= -90:
search_set += self.bins[latitude-i]
if latitude + i <= 90:
search_set += self.bins[latitude+i]
while len(search_set) == 0 and i... | Get the closest dataset. |
351,996 | def class_name_for_data_type(data_type, ns=None):
assert is_user_defined_type(data_type) or is_alias(data_type), \
% type(data_type)
name = fmt_class(data_type.name)
if ns:
return prefix_with_ns_if_necessary(name, data_type.namespace, ns)
return name | Returns the name of the Python class that maps to a user-defined type.
The name is identical to the name in the spec.
If ``ns`` is set to a Namespace and the namespace of `data_type` does
not match, then a namespace prefix is added to the returned name.
For example, ``foreign_ns.TypeName``. |
351,997 | def _typecheck_fsnative(path):
if not isinstance(path, fsnative_type):
return False
if PY3 or is_win:
if u"\x00" in path:
return False
if is_unix:
try:
path.encode(_encoding, "surrogateescape")
except UnicodeEncodeError:
... | Args:
path (object)
Returns:
bool: if path is a fsnative |
351,998 | def total_number(slug, kind=):
return TabPost.select().join(
TabPost2Tag,
on=(TabPost.uid == TabPost2Tag.post_id)
).where(
(TabPost2Tag.tag_id == slug) & (TabPost.kind == kind)
).count() | Return the number of certian slug. |
351,999 | def interleave_planes(ipixels, apixels, ipsize, apsize):
warnings.warn(,
DeprecationWarning)
newi = MergedPlanes([ipixels], ipsize, [apixels], apsize)
return next(newi) | Interleave (colour) planes, e.g. RGB + A = RGBA.
Return an array of pixels consisting of the `ipsize` elements of
data from each pixel in `ipixels` followed by the `apsize` elements
of data from each pixel in `apixels`. Conventionally `ipixels`
and `apixels` are byte arrays so the sizes are bytes, but... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.