content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def command_error_handler(e, cmd_descr, use_logger=False, warn_only=False,
exit_val=exitvals['startup']['num']):
"""
Handle external-command-related exceptions with various options.
If it returns, returns False.
Parameters:
cmd_descr: a string describing the command, us... | 5,312,100 |
def UniBLAST(code,Verbose=False):
"""
Input
------
Uniprot Code
UniBLAST(code)
e.g. UniBLAST('O00238')
Description
-----------
Outputs a Fasta sequence and
Runs blasp looking through pdb database with the Uniprot code
Output
------
- UniproID.fasta FAS... | 5,312,101 |
def emb_computation_loop(split, set_loader, stat_file):
"""Computes the embeddings and saves the in a stat file"""
# Extract embeddings (skip if already done)
if not os.path.isfile(stat_file):
embeddings = numpy.empty(
shape=[0, params["emb_dim"]], dtype=numpy.float64
)
m... | 5,312,102 |
def register(*ids):
"""Register termination function class for environments with given ids."""
def librarian(cls):
for id_ in ids:
TERMINATIONS[id_] = cls
_raylab_registry.register(RAYLAB_TERMINATION, id_, cls)
return cls
return librarian | 5,312,103 |
def output_todays_games(games_dict, key_list, sport_name):
"""
output today's games in ascending order by their start times
:param games_dict: the dictionary of game times to game descriptions
:param key_list: list of gametime keys sorted in ascending order
:param sport_name: game type string used ... | 5,312,104 |
def process_sdk_options(parser, options, app_dir):
"""Handles values of options added by 'add_sdk_options'.
Modifies global process state by configuring logging and path to GAE SDK.
Args:
parser: OptionParser instance to use to report errors.
options: parsed options, as returned by parser.parse_args.
... | 5,312,105 |
def IsProjectAddressOnToLine(project_addr, to_addrs):
"""Return True if an email was explicitly sent directly to us."""
return project_addr in to_addrs | 5,312,106 |
def FID3_factual(instance, rule_list, threshold=0.01):
"""Returns the factual extracted for the Fuzzy ID3
tree in this package
Parameters
----------
instance : dict, {feature: {set_1: pert_1, set_2: pert_2, ...}, ...}
Fuzzy representation of the instance with all the features and pertenence... | 5,312,107 |
def percent_decode(s, encoding='utf-8', decodable=None, errors='replace'):
"""
[*** Experimental API ***] Reverses the percent-encoding of the given
string.
Similar to urllib.parse.unquote()
By default, all percent-encoded sequences are decoded, but if a byte
string is given via the 'decodable... | 5,312,108 |
def get_card_key(word_type: WordType, russian: AccentedText,
english: AccentedText) -> tuple:
"""
Get the key that identifies a card.
"""
return (word_type,
AccentedText(russian).text.lower(),
AccentedText(english).text.lower()) | 5,312,109 |
def parse_text_content(html: str) -> list:
"""
获取每个查询结果显示的数据量,然后通过每页20条的数据转换成共计多少页。
:return:
"""
html = etree.HTML(html)
need_content = html.xpath('//*[@id="__next"]/div[1]/div/div[1]/section[1]/article/p')
return need_content | 5,312,110 |
def tarako_failed(review):
"""Remove the tarako tag from the app."""
tag = Tag(tag_text='tarako')
tag.remove_tag(review.app)
WebappIndexer.index_ids([review.app.pk])
send_tarako_mail(review) | 5,312,111 |
def create_input(config=None, src_data=None, tgt_data=None, src_pos_dict=None):
"""
:return:
"""
assert src_data.shape[0] == tgt_data.shape[0]
n_datapoints = src_data.shape[0]
sequence_length = config['sequence_length']
data = []
close_price_idx = src_pos_dict['close_price']
for i i... | 5,312,112 |
def std_histogrammed_function(t, y, **kwargs):
"""Compute standard deviation of data *y* in bins along *t*.
Returns the standard deviation-regularised function *F* and the centers of the bins.
.. SeeAlso:: :func:`regularized_function` with *func* = :func:`numpy.std`
"""
return apply_histogrammed_f... | 5,312,113 |
def _crown_div(out_bound, lhs, rhs):
"""Backward propagation of LinearBounds through an addition.
This is a linear operation only in the case where this is a division by a
constant.
Args:
out_bound: CrownBackwardBound, linear function of network outputs bounds
with regards to the results of the divi... | 5,312,114 |
def test_sidebar_disabled(sphinx_build_factory):
"""The sidebar is shrunk when no sidebars specified in html_sidebars."""
confoverrides = {"html_sidebars.page1": ""}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("page1.html")
ass... | 5,312,115 |
def cartesian_to_polar(x, y, vx, vy, THRESH=0.0001):
"""
Converts 2d cartesian position and velocity coordinates to polar coordinates
Args:
x, y, vx, vy : floats - position and velocity components in cartesian respectively
THRESH : float - minimum value of rho to return non-zero values
Ret... | 5,312,116 |
def load(lib, IM_VERSION, IM_QUANTUM_DEPTH, IM_HDRI):
"""Define Pixel Wand methods. The ImageMagick version is given as
a second argument for comparison. This will quick to determine which
methods are available from the library, and can be implemented as::
if IM_VERSION < 0x700:
# ... d... | 5,312,117 |
def processing(channel):
"""
获取代理,缓存1小时
:param channel: nn-国内高匿/nt-国内普通/wn-国内https/wt-国内http
:return:
"""
if len(settings.CACHE['proxies']['items']) == 0 or int(time.time()) > settings.CACHE['proxies']['update'] + 60 * 60 * 0.5:
items_http = []
items_https = []
headers =... | 5,312,118 |
def _to_voxel_coordinates(streamline, lin_T, offset):
"""Applies a mapping from streamline coordinates to voxel_coordinates,
raises an error for negative voxel values."""
inds = np.dot(streamline, lin_T)
inds += offset
if inds.min().round(decimals=6) < 0:
raise IndexError('streamline has poi... | 5,312,119 |
def check_if_branch_exist(db, root_hash, key_prefix):
"""
Given a key prefix, return whether this prefix is
the prefix of an existing key in the trie.
"""
validate_is_bytes(key_prefix)
return _check_if_branch_exist(db, root_hash, encode_to_bin(key_prefix)) | 5,312,120 |
def main():
"""
TODO:
"""
read_dictionary()
create_boggle()
find(matrix[0][0],matrix,1,matrix[0][0]) | 5,312,121 |
def add_trace(rule, mbox_response, request_type, request_detail, tracer):
"""
:param rule: (target_decisioning_engine.types.decisioning_artifact.Rule) rule
:param mbox_response: (delivery_api_client.Model.mbox_response.MboxResponse) mbox response
:param request_type: ( "mbox"|"view"|"pageLoad") request ... | 5,312,122 |
def _create_upload_object_for_filer_file(sender, instance, created, **kwargs):
"""
When file is uploaded from django admin, creates a new upload object with file_path
"""
if kwargs['raw']:
# https://github.com/django/django/commit/18a2fb19074ce6789639b62710c279a711dabf97
return
if s... | 5,312,123 |
def _get_axis_labels(axes: List["CalibratedAxis"]) -> List[str]:
"""Get the axes labels from a List of 'CalibratedAxis'.
Extract the axis labels from a List of 'CalibratedAxis'.
:param axes: A List of 'CalibratedAxis'.
:return: A list of the axis labels.
"""
return [str((axes[idx].type().getLa... | 5,312,124 |
def test_parse_bind_volume():
"""test that parse_bind_volume meets docker API requirements."""
# two-field version
mapping = bindit.docker.parse_bind_volume(f"{SOURCE_ABSTRACT}:{DEST_ABSTRACT}")
assert list(mapping.keys())[0] == SOURCE_ABSTRACT
assert list(mapping.values())[0] == DEST_ABSTRACT
#... | 5,312,125 |
def decryptprivatekey_cmd(key, address, salt, n, password):
"""
decrypt privatekey
"""
if key == '' and address == '' and salt == '' or n == 0 and password == '':
print('Usage: punica tool decryptprivatekey [OPTIONS]')
print('')
print(' ', 'decrypt privatekey')
print()
... | 5,312,126 |
async def show():
"""
Dumps shits table for test
:return:
"""
cur = current_app.db.cursor()
cur.execute('''SELECT * FROM shits''')
return await make_response(json.dumps(cur.fetchall())) | 5,312,127 |
def psql_insert_copy(table, conn, keys, data_iter):
"""
Utility function for converting table object to csv and then to write those rows to a postgre database.
"""
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
output = StringIO()
writer = csv.writer(output... | 5,312,128 |
def set_filter(info_dict, norm=False, norm_val=0.95):
"""
Compute the transmittance of the filter with respect to wavelength
Parameters
----------
info_dict: dictionary
wavelength : array
wavelengths in angstrom
norm: boolean
enables to normalise the values to 'norm_val' ... | 5,312,129 |
def create_app(config_name):
"""
application factory function
:param config_name:
:return:
"""
app = Flask(__name__)
app.config.from_object(config_options[config_name])
# initialising bootstrap
bootstrap.init_app(app)
# initialising db model
db.init_app(app)
# initialisin... | 5,312,130 |
def delete(db_user: User) -> None:
"""
Delete the user and all data connected to them.
:param db_user: The user which gets deleted.
:return: Returns nothing, this function is one big side-effect.
"""
anonym_uid = DBDiscussionSession.query(User).filter_by(nickname=nick_of_anonymous_user).first()... | 5,312,131 |
def queue_with_dlx(ch, q_name):
"""creates pair queue+dead_letters_queue"""
q_dlx_name = 'dlx_' + q_name
ch.queue_declare(queue=q_name, durable=True,
arguments={'x-dead-letter-exchange': '',
'x-dead-letter-routing-key': q_dlx_name,
... | 5,312,132 |
def convert_to_tensor_v1(value,
dtype=None,
name=None,
preferred_dtype=None,
dtype_hint=None):
"""Converts the given `value` to a `Tensor`.
This function converts Python objects of various types to `Tensor`
object... | 5,312,133 |
def simulate(rate, bdepth, policy, dset_mr, rsz_is=(1e5, 1e2)):
"""Simulate policy on a single camera."""
qpm = ut.getqpm(rate, bdepth)
rsz_is = (int(rsz_is[0]), int(rsz_is[1]))
return _simulate(qpm, policy, dset_mr, rsz_is) | 5,312,134 |
def CreateUser():
"""Route for checking if user exists."""
profile = check_if_user_profile(users.get_current_user().user_id())
return str(profile) | 5,312,135 |
def process_file(file_url: str) -> Tuple[str, Tuple[str, ...]]:
"""Process file with download, cache and upgrade."""
_, file_ext = os.path.splitext(file_url)
folder_hash = md5(file_url.encode('utf-8')).hexdigest()
path = f"/notebooks/{folder_hash}"
original = f"original{file_ext}"
converted = ... | 5,312,136 |
def is_list(string):
"""
Checks to see if a string contains a list in the form [A, B]
:param string: string to evaluate
:return: Boolean
"""
if string:
if '[' == string[0] and ']' == string[-1] and ',' in string:
return True
return False | 5,312,137 |
def load(input_file):
"""
Loads a pcap file
"""
header = pcap.read_pcap_header(input_file)
return header | 5,312,138 |
def personal_wiki_pages(request):
"""
List personal wiki pages.
"""
username = request.user.username
if request.cloud_mode and request.user.org is not None:
org_id = request.user.org.org_id
joined_groups = seaserv.get_org_groups_by_user(org_id, username)
else:
joined_gr... | 5,312,139 |
def parse_args():
"""This function parses and return arguments passed in """
descr = 'Plot the Bifurcation Diagram of Logistic, Cubic, and Sine Maps'
examples = '''
%(prog)s -r 1:4
%(prog)s -r 4:6.5 --map=cubic
%(prog)s --map=sine -s 200 -n 200
%(prog)s -r 3.:4. -s 500 -n 600
%... | 5,312,140 |
def plot_p_vs_median(df, text, file_path):
"""plot p_values vs median correlation scores for each MOA for all doses"""
plt.rcParams.update({'font.size': 14})
plt.figure(figsize=(12,8))
plt.xlabel("Median scores of pairwise correlation btw cpds")
plt.ylabel("Non-parametric P-values")
plt.title("... | 5,312,141 |
def get_random_mac_address():
"""Generate and return a MAC address in the format of WINDOWS"""
# get the hexdigits uppercased
uppercased_hexdigits = ''.join(set(string.hexdigits.upper()))
# 2nd character must be 2, 4, A, or E
return random.choice(uppercased_hexdigits) + random.choice("24AE") + "".jo... | 5,312,142 |
def test_move_and_copy_loads():
"""Call some functions that load arguments via custom type casters and
count the number of moves/copies."""
cstats = m.move_and_copy_cstats()
c_m, c_mc, c_c = (
cstats["MoveOnlyInt"],
cstats["MoveOrCopyInt"],
cstats["CopyOnlyInt"],
)
asse... | 5,312,143 |
def remove_fragments(mol):
"""Filters out fragments.
A predefined list contains numerous known fragments which can be
filtered out.
Parameters
----------
mol: rdkit.Chem.Mol
A molecule with various fragments.
Returns
-------
mol: rdkit.Chem.Mol
Returns a molecule f... | 5,312,144 |
def mooring_horizontal_volume_transport(od):
"""
Compute horizontal volume flux through a mooring array section (in/outflow).
If the array is closed, transport at the first mooring is not computed.
Otherwise, transport at both the first and last mooring is not computed.
Transport can be comput... | 5,312,145 |
def _cast_list(definition: dict, value: list) -> list:
"""
Convert a list botocore type into formatted values recursively casting its items.
:param definition:
Specification definition for the associated value to cast.
:param value:
A loaded value to be cast into its boto client respons... | 5,312,146 |
def demo_hello():
"""Example with simple swagger definition
This is the most simple swagger definition example.
---
tags:
- demo
# tags: [demo1, demo3]
parameters:
- name: username
in: query
type: string
required: true
- name: age
in: query
... | 5,312,147 |
def do_extract(
installer: str,
*,
output_dir: typing.Optional[str],
verbose: bool,
unzip: bool,
name_encoding: str,
offset: typing.Optional[int],
) -> None:
"""Extract all files from an installer,
including the directory structure."""
if output_dir is None:
output_dir = os.path.basename(installer) + ".ex... | 5,312,148 |
def test_docker_builder_build(recipes_fixture):
"""
Tests just the build_recipe method of a RecipeBuilder object.
"""
docker_builder = docker_utils.RecipeBuilder(use_host_conda_bld=True)
pkgs = recipes_fixture.pkgs['one']
docker_builder.build_recipe(
recipes_fixture.recipe_dirs['one'], b... | 5,312,149 |
def get_signed_node(node, sign, reverse):
"""Given sign and direction, return a node
Assign the correct sign to the source node:
If search is downstream, source is the first node and the search must
always start with + as node sign. The leaf node sign (i.e. the end of
the path) in this case will th... | 5,312,150 |
def isChinese(word):
"""判断是否为中文"""
for uchar in word:
if not '\u4e00' <= uchar <= '\u9fa5': # 遇到非中文
return False
return True | 5,312,151 |
def TempPath(**kwargs):
"""Wrapper around tempfile.NamedTemporaryFile which returns a path object
Unlike tempfile.NamedTemporaryFile, the FileNotFoundError exception is not
raised if the file is deleted before the context closes.
:rtype: pathlib.Path
"""
with tempfile.NamedTemporaryFile(**kwar... | 5,312,152 |
async def serve(
ssl_context: Optional[ssl.SSLContext],
keys: Optional[Sequence[ServerSecretPermanentKey]],
paths: Optional['Paths'] = None,
host: Optional[str] = None,
port: int = 8765,
loop: Optional[asyncio.AbstractEventLoop] = None,
event_callbacks: Optional[M... | 5,312,153 |
def ll_dist(lon1, lat1, lon2, lat2):
"""
Return distance between a pair of lat, long points.
"""
# functions based on radians
lat1, lat2, dlon, dlat = map(radians, [lat1, lat2, (lon2 - lon1), (lat2 - lat1)])
a = sin(dlat / 2.0) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2.0) ** 2
return R_EA... | 5,312,154 |
def goIsoStack():
"""
****** beginning of SEG-Y file info ******
file name = /Users/amunoz/Home/data/bp/sgy/iso/FD_Model_PSTM_STK.sgy
byte order = BIG_ENDIAN
number of bytes = 61018624
number of traces = 12596
format = 1 (4-byte IBM floating point)
units for spatial coordinates: m (will be converted to ... | 5,312,155 |
def game(request, *, window_codename):
"""Display problems"""
# Process request
superuser = request.user.is_superuser
team = request.user.competitor.team
try:
window = queries.get_window(window_codename)
except models.Window.DoesNotExist:
raise Http404()
# Initialize contex... | 5,312,156 |
def delete_tracker_object(container_path, obj):
"""
Delete zero-byte tracker object from gsexpiring volume.
Called by:
- file_connector.swift.obj.expirer.ObjectExpirer.pop_queue()
- file_connector.swift.common.DiskDir.DiskDir.delete_object()
"""
tracker_object_path = os.path.join(con... | 5,312,157 |
def to_video_labels(label=None, frames=None, warn_unsupported=True):
"""Converts the given labels to ``eta.core.video.VideoLabels`` format.
Args:
label (None): video-level labels provided as a
:class:`fiftyone.core.labels.Label` instance or dict mapping field
names to :class:`fi... | 5,312,158 |
def info(obj):
""" Prints information about the object """
lines = ['Info for {0}'.format(obj.name()), 'Attributes:']
# Get the name of all attributed
for a in obj.listAttr():
lines.append(' ' + a.name())
result = '\n'.join(lines)
print result | 5,312,159 |
def api_create_user():
"""Creates a new user.
Example Request:
HTTP POST /api/v1/users/create
{
"username": "johndoe",
"password": "Password1",
"email": "johndoe@example.com",
"first_name": "John"
}
Example Response:
{
... | 5,312,160 |
def comparaison(donnee, precision, separateur=","):
"""
Compare notre algorithme et celui de scikit-learn.
Parameters
----------
donnee : tuple
tuple contenant : (nom du dataset, chemin dataset, chemin datatest).
separateur : string, optional
string contenant le séparateur utili... | 5,312,161 |
def plot_activity(preds, sort_map_list, label_list, window_size=2, active_length_cutoff=3, disable_inactive=True,
start=None, end=None, step=10, ax=None, fig=None, cbar=False, legend=True):
"""Visualize the progression of an outbreak through time. Apply activity cutoffs based on time and similar
... | 5,312,162 |
def make_events_query_from_filter(event_filter):
"""Return start and stop row for filtering and a query.
Query is based on the selected parameter.
:param event_filter: storage.EventFilter object.
"""
q = {}
ts_range = make_timestamp_range(event_filter.start_time,
... | 5,312,163 |
def jpeg_next_marker(fh):
"""Scans to the start of the next valid-looking marker. Return
value is the marker id.
TODO use fh.read instead of read_exactly
"""
# Find 0xff byte. We should already be on it.
try:
byte = read_exactly(fh, 1)
while ord3(byte) != 0xff:
# log... | 5,312,164 |
def data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_cep_list_connection_end_pointconnection_end_point_uuid_otsi_connection_end_point_spec_otsi_termination_selected_central_frequency_get(uuid, node_uuid, owned_node_edge_point_uuid, connection_end_point_uuid): # n... | 5,312,165 |
async def test_in_channel_config(
cluster_id, bind_count, attrs, opp, zigpy_device_mock, zha_gateway
):
"""Test ZHA core channel configuration for input clusters."""
zigpy_dev = zigpy_device_mock(
{1: {"in_clusters": [cluster_id], "out_clusters": [], "device_type": 0x1234}},
"00:11:22:33:44:... | 5,312,166 |
def get_edge_trace(
g: nx.Graph,
edge_colours: Optional[List[str]] = None,
) -> List[go.Scatter]:
"""Gets edge traces from PPI graph. Returns a list of traces enabling edge colours to be set individually.
:param g: _description_
:type g: nx.Graph
:return: _description_
:rtype: List[go.Scatt... | 5,312,167 |
def matmul_A_BT(a, b):
"""
Computes A * B.T, dealing automatically with sparsity and data modes.
:param a: Tensor or SparseTensor with rank 2 or 3.
:param b: Tensor or SparseTensor with rank 2 or 3.
:return: Tensor or SparseTensor with rank = max(rank(a), rank(b)).
"""
mode = modes.autodetec... | 5,312,168 |
def entries_to_labels_scores(entries):
"""
Convert entries to labels and scores for barplot.
NOTE The labels only exist to discern entries: the actual labels are
set in set_label_legends.
"""
nicknames = [entry['algo-nickname'] for entry in entries]
scores = []
colors = []
for entr... | 5,312,169 |
def test_get_aws_secrets_from_file(filename, expected_keys):
"""Test that reading secrets from files works."""
keys = get_aws_secrets_from_file(get_resource_path(filename))
assert keys == expected_keys | 5,312,170 |
def guessarraytype (arr, makeintfloats=False):
"""
guess the underlying datatype (out of 'i8', 'f4', 'a20') of an iterable
of strings. If the iterable contains strings that are guessed to be of
different types, the most 'general' type will be returned, where we mean
('i8', 'f4', 'a20') are assumed ... | 5,312,171 |
def get_current_system_datetime(device):
""" Returns current time of system
Args:
device ('obj'): device to use
Returns:
current time ('str')
Raises:
None
"""
log.info("Getting current system time")
try:
out = device.parse("show cloc... | 5,312,172 |
def cmd_openfile(pid,abs_filename,line_no=1,column_no=1):
"""ファイルをコンパイルする
abs_filename - ファイル名の絶対パス
(Ex.) c:/project/my_app/src/main.cpp
"""
dte = get_dte_obj(pid)
if not dte:
_vs_msg("Not found process")
return False
abs_filename = _to_unicode(abs... | 5,312,173 |
def optimize(s, probability, loBound, hiBound):
""" Optimiere auf die max. mögliche Entnahme bei einer vorgegebenen Fehlerquote
Returns:
widthdrawal: max. mögliche prozentuale Entnahme
"""
n_ret_months = s.simulation['n_ret_years'] * 12
accuracy = 0.01 # Genauigkeit der Optimierung
... | 5,312,174 |
def torch_data_loader(
features: np.ndarray,
labels: np.ndarray,
batch_size: int,
shuffle: bool = None,
num_workers: int = 0
) -> Tuple[torch.utils.data.DataLoader]:
"""
Creates the data loader for the train and test dataset.
Parameters
---------
features: numpy.ndarray
... | 5,312,175 |
def delete_row_col(np_arr, row, col):
"""Removes the specified row and col from a Numpy array.
A new np array is returned, so this does not affect the input array."""
return np.delete(np.delete(np_arr, row, 0), col, 1) | 5,312,176 |
def make_3d(adata,
time_var='Metadata_Time',
tree_var='Metadata_Trace_Tree',
use_rep=None,
n_pcs=50):
"""Return three dimensional representation of data.
Args:
time_var (str): Variable in .obs with timesteps
tree_var (str): Variable in .obs with t... | 5,312,177 |
def _natural_key(x):
""" Splits a string into characters and digits. This helps in sorting file
names in a 'natural' way.
"""
return [int(c) if c.isdigit() else c.lower() for c in re.split("(\d+)", x)] | 5,312,178 |
def get_location_1(box_2d, dimension, rotation_x, rotation_y, rotation_z, proj_matrix):
"""
方法1 2Dbbox中心与3Dbbox中心重合
只存在一个中心点间的对应关系。难以约束。
若是将Z的值替换成真实值,效果还行。Z方向的值与XY相比差距太大。
"""
R = get_R(rotation_x, rotation_y)
# format 2d corners
xmin = box_2d[0]
ymin = box_2d[1]
xmax = box_2d[2]... | 5,312,179 |
def find_file(directory: str, search_file: str) -> str:
"""Finds relative path of file in given directory and its subdirectories.
Args:
directory (str): Directory to search in.
search_file (str): File to search in directory.
Returns:
str: Path to file.
"""
paths = []
... | 5,312,180 |
def get_smoothing_kernel(x, y, smoothing_length):
""" x = x - xj, y = y - yj"""
r_xy_2 = x + y
q_xy_2 = r_xy_2 / smoothing_length
return get_dimensionless_2D_kernel(q_xy_2) | 5,312,181 |
def evolve_population(population: list, generation: int) -> list:
"""
This evolves an existing population by doubling them (binary fission), then introducing random mutation to
each member of the population.
:param generation: Helps determine the starting point of the numbering system so the bacteria ha... | 5,312,182 |
def create_siamese_trainer(
model,
optimizer,
loss_fn,
device=None,
non_blocking=False,
prepare_batch=_prepare_batch,
output_transform=output_transform_trainer,
):
"""Factory function for creating an ignite trainer Engine for a siamese architecture.
Args:
model: siamese networ... | 5,312,183 |
def handle_methods(
request,
GET=None,
POST=None,
PUT=None,
PATCH=None,
DELETE=None,
args=[],
kwargs={},
):
"""
REST Method Handler.
Return the view handleMethods(request)
Add all allowed methods with their responses. These can either be a Django HttpResponse,
or a c... | 5,312,184 |
def replace_io(monkeypatch):
"""For all tests, mock paths to the "outside" world"""
Annotation = DictMock()
_trigger_event = MagicMock()
_api_error = MagicMock()
monkeypatch.setattr(api, 'Annotation', Annotation)
monkeypatch.setattr(api, '_trigger_event', _trigger_event)
monkeypatch.setattr(... | 5,312,185 |
def compute_bounding_box(points, convex_hull=None,
given_angles=None, max_error=None):
"""
Computes the minimum area oriented bounding box of a set of points.
Parameters
----------
points : (Mx2) array
The coordinates of the points.
convex_hull : scipy.spatial.C... | 5,312,186 |
def parse_outputs_from_args(args: argparse.Namespace) -> Tuple[List[str], List[int]]:
"""Get a list of outputs specified in the args."""
name_and_port = [output.split(':') for output in re.split(', |,', args.output_layers)]
try:
return [name for name, _ in name_and_port], [int(port) for _, port in n... | 5,312,187 |
def n_pitches_used(tensor):
"""Return the number of unique pitches used per bar."""
if tensor.get_shape().ndims != 5:
raise ValueError("Input tensor must have 5 dimensions.")
return tf.reduce_mean(tf.reduce_sum(tf.count_nonzero(tensor, 3), 2), [0, 1]) | 5,312,188 |
def survey():
"""Survey home page."""
N_SIMULATION_PERIODS = get_n_periods()
db = get_db()
user_data = db.execute(
"SELECT * FROM user WHERE id = ?",
(session["user_id"],)
).fetchone()
user_stage = user_data['current_stage']
simulation_period = user_data['simulation_period']
... | 5,312,189 |
def ReadXTrace(trace_filename):
"""
Returns the trace for this XTrace dataset.
@param trace_filename: location of file to read into XTrace object
"""
# maximum size for strings
max_bytes = 32
max_function_bytes = 64
# open the file
with open(trace_filename, 'rb') as fd:
# cr... | 5,312,190 |
def to_vue_plotly(data: np.ndarray | pd.DataFrame, names: list = None) -> dict:
"""Takes data (dataframe or numpy array) and transforms it to form, that vue-plotly understand.
Links to vue-plotly:
https://www.npmjs.com/package/vue-plotly
https://www.npmjs.com/package/@rleys/vue-plotly - fork for vue ... | 5,312,191 |
def count_anchors(anchor_file, out_file):
"""Counts the number of occurrences anchor-entity pairs"""
sf_dict = {}
in_file = open(anchor_file)
i = 0
for line in in_file:
i += 1
cols = line.strip().split("\t")
if (len(cols) < 4) or (cols[2].strip().lower() == ""):
c... | 5,312,192 |
def get_model_name(file_path, sheet_name):
"""
Return the model name, which is assumed to be in the first row, second column of the sheet_name.
Args:
file_path: path to file containing the model
sheet_name: sheet_name: name of the excel sheet where the model name is, should be 'general'
... | 5,312,193 |
def duplicate_ticket_view(request, uuid):
"""
Create duplicate of a given ticket (found by uuid) i
The result is a new ticket, which has the same connection and validity_period
Does not allow duplicating shared tickets.
Does not allow to duplicate if you are not the author of ticket.
"""
t... | 5,312,194 |
def _projected_velocities_from_cog(beta: float, cog_speed: float) -> Tuple[float, float]:
"""
Computes the projected velocities at the rear axle using the Bicycle kinematic model using COG data
:param beta: [rad] the angle from rear axle to COG at instantaneous center of rotation
:param cog_speed: [m/s]... | 5,312,195 |
def prime_factors(a:int) -> List[int]:
"""
Returns the prime factors of a number.
Parameters:
a (int): the number to return the prime factors of
Returns:
(list[int]): an unsorted list of the prime factors of a
"""
# prime numbers only have itself as a prime factor
if ... | 5,312,196 |
def add_ngram(sequences, token_indice, ngram_range=2):
"""
Augment the input list of list (sequences) by appending n-grams values.
Example: adding bi-gram
>>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]]
>>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017}
>>> add_ngram(sequences, token_in... | 5,312,197 |
def get_sea_surface_height_trend_image():
"""generate bathymetry image for a certain timespan (begin_date, end_date) and a dataset {jetski | vaklodingen | kustlidar}"""
r = request.get_json()
image = ee.Image('users/fbaart/ssh-trend-map')
image = image.visualize(**{'bands': ['time'], 'min': -0.03, 'ma... | 5,312,198 |
def run_test_practice_problem3a():
""" Tests the practice_problem3a function. """
# ------------------------------------------------------------------
# 6 tests.
# They use the imported simple_testing (st) module.
# Each test is a SimpleTestCase with 3 arguments:
# -- the function to... | 5,312,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.