content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def check_sanitization(mol):
"""
Given a rdkit.Chem.rdchem.Mol this script will sanitize the molecule.
It will be done using a series of try/except statements so that if it fails it will return a None
rather than causing the outer script to fail.
Nitrogen Fixing step occurs here to correct for a co... | 5014508cbde6ea1a89beeca106f0adeae1422817 | 3,627,112 |
from typing import Union
import re
def extract_msg(log: str, replica_name: str) -> Union[str, None]:
"""
Extracts a message from a single log
Parameters
----------
log
full log string
replica_name
identity name of replica
Returns
-------
msg
message sent f... | da17f008af059d70cc4cc969bc03aa34ed846e0f | 3,627,114 |
def LF_report_is_short_demo(x):
"""
Checks if report is short.
"""
return NORMAL if len(x.text) < 280 else ABSTAIN | 525fdbdf910c21d28824a4bf371dec069e9a7abb | 3,627,116 |
from typing import Optional
def binarize_swf(
scores: SlidingWindowFeature,
onset: float = 0.5,
offset: float = 0.5,
initial_state: Optional[bool] = None,
):
"""(Batch) hysteresis thresholding
Parameters
----------
scores : SlidingWindowFeature
(num_chunks, num_frames, num_cla... | 3e578608501887943e0918b13fc6dcc10585685e | 3,627,117 |
import torch
import time
def train_pytorch_ch7(optimizer_fn, optimizer_hyperparams, features, labels,
batch_size=10, num_epochs=2):
"""
The training function of chapter7, but this is the pytorch library version
Parameters
----------
optimizer_fn : [function]
the opti... | 4b60531b47fc58df0c61bd36cdb77ac8a137ba76 | 3,627,119 |
def ProcessOptionInfileParameters(ParamsOptionName, ParamsOptionValue, InfileName = None, OutfileName = None):
"""Process parameters for reading input files and return a map containing
processed parameter names and values.
Arguments:
ParamsOptionName (str): Command line input parameters option ... | ece155282aef5c7ba365ce54c529998590146043 | 3,627,120 |
from typing import Tuple
def computeD1D2(current: float, volatility: float, ttm: float, strike: float,
rf: float) -> Tuple[float, float]:
"""Helper function to compute the risk-adjusted priors of exercising the
option contract, and keeping the underlying asset. This is used in the
computat... | 76dc53df4bde1c2974749bf10f007ba3c8e748ff | 3,627,123 |
def control_event(data_byte1, data_byte2=0, channel=1):
"""Return a MIDI control event with the given data bytes."""
data_byte1 = muser.utils.key_check(data_byte1, CONTROL_BYTES, 'upper')
return (STATUS_BYTES['CONTROL'] + channel - 1, data_byte1, data_byte2) | 5195d1236f1cd4441281777ab1a50591b3b9fbe0 | 3,627,124 |
def create_noise_mask(mean, variance, threshold=25):
"""Creates a binary data mask based on quartile
thresholds from two mean and variance arrays.
Parameters
----------
mean : numpy array
Array containing pixel mean values.
variance : numpy array
Array containing pixel variance... | 40dc9907e0a65a28cdf81a3b76e11754d15257fe | 3,627,125 |
def initialCondition1D(u, a):
"""
use this function only if initial condition != 0 is needed ?????
"""
nx = u.size
ul = np.zeros(nx)
ul[1:nx-1] = u[1:nx-1]+0.5*a[1:nx-1]**2*(u[2:]-2*u[1:nx-1]+u[0:nx-2])
return ul | 8047a95fe733867e4dcf1c30acdb130fdc4ff9f6 | 3,627,126 |
def learnability_objective_function(throughput, delay):
"""Objective function used in https://cs.stanford.edu/~keithw/www/Learnability-SIGCOMM2014.pdf
throughput: Mbps
delay: ms
"""
score = np.log(throughput) - np.log(delay)
# print(throughput, delay, score)
score = score.replace([np.inf, -n... | 9646af095668bf0c449f2ec05319c1cc35d59d39 | 3,627,127 |
def partition_graph(graph, partitions):
"""
Create a new graph based on `graph`, where nodes are aggregated based on
`partitions`, similar to :func:`~networkx.algorithms.minors.quotient_graph`,
except that it only accepts pre-made partitions, and edges are not given
a 'weight' attribute. Much fast t... | 98aae7e3c3354a04b30c005c6e0183676f983234 | 3,627,128 |
import logging
def __misc_badbarcode():
"""DEPRECATED: setting badbarcode boolean. Use /misc/itemattr instead.
Gets or Sets the barcode-okayness of a SKU.
This will return the barcode state of a SKU in a GET message, and will set the barcode state of a SKU in a POST message.
:param int sku: The... | dcc02a80348cc327e3705c8392724eecc6243610 | 3,627,129 |
def lzip(*args):
"""
this function emulates the python2 behavior of zip (saving parentheses in py3)
"""
return list(zip(*args)) | 92aa6dea9d4058e68764b24eb63737a2ec59a835 | 3,627,130 |
def sanitize_url(url: str) -> str:
"""
This function strips to the protocol, e.g., http, from urls.
This ensures that URLs can be compared, even with different protocols, for example, if both http and https are used.
"""
prefixes = ["https", "http", "ftp"]
for prefix in prefixes:
if url... | 9c61a9844cfd6f96e158a9f663357a7a3056abf0 | 3,627,131 |
from typing import Dict
from typing import Union
def trimming_parameters(
library_type: LibraryType,
trimming_min_length: int
) -> Dict[str, Union[str, int]]:
"""
Derive trimming parameters based on the library type, and minimum allowed trim length.
:param library_type: The LibraryType (e... | 9eb891eb685a0163c7df0d3d8946606ad54ea11d | 3,627,132 |
def make_nn(output_size, hidden_sizes):
"""
Creates a fully connected neural network.
Params:
output_size: output dimensionality
hidden_sizes: list of hidden layer sizes. List length is the number of hidden layers.
"""
NNLayers = [tf.keras.layers.Dense(h, activation=tf.nn.relu,... | 66945e649f8dba407e72fb9790eb2f23d052d6fb | 3,627,133 |
def image_to_world(bbox, size):
"""Function generator to create functions for converting from image coordinates to world coordinates"""
px_per_unit = (float(size[0])/bbox.width, float(size[1]/bbox.height))
return lambda x,y: (x/px_per_unit[0] + bbox.xmin, (size[1]-y)/px_per_unit[1] + bbox.ymin) | 35fcfbf8e76e0ec627da9bf32a797afdae11fe17 | 3,627,134 |
def error_func(A, b, x, x_star, fold=50):
"""Calculate errors ||Ax_1-b||-||Ax_star-b||, where x1 \in x.
Param:
A: n*d np.ndarray, coefficient in ||Ax-b||
b: n*1 np.ndarray, coefficient in ||Ax-b||
x: tuple, (x_linBoost, x_inverse, x_cholesky)
x_star: d*1 np.ndarray, x* by lstsq()... | 59a6aae4566fcb8406b5e495727550790f9958ff | 3,627,135 |
def git_reset_all():
"""Function that unstages all files in repo for commit.
Returns
-------
out : str
Output string from stdout if success, stderr if failure
err : int
Error code if failure, 0 otherwise.
"""
command = 'git reset HEAD'
name = 'git_reset_all'
return ... | 6b3aea4d7cde04cbe5b81ccc58c2dc2bf2f6d1bc | 3,627,136 |
def find_kern_timing(df_trace):
"""
find the h2d start and end for the current stream
"""
kern_begin = 0
kern_end = 0
for index, row in df_trace.iterrows():
if row['api_type'] == 'kern':
kern_begin = row.start
kern_end = row.end
break;
return kern... | 2e121e7a9f7ae19f7f9588b0105f282c59f125ba | 3,627,137 |
def Get(SyslogSource, WorkspaceID):
"""
Get the syslog conf for specified workspace from the machine
"""
if conf_path == oms_syslog_ng_conf_path:
NewSource = ReadSyslogNGConf(SyslogSource, WorkspaceID)
else:
NewSource = ReadSyslogConf(SyslogSource, WorkspaceID)
for d in NewSourc... | e8b6613e821336644cdfe9c4091e914f9ec1c8ac | 3,627,138 |
def partie_reelle(c : Complexe) -> float:
"""Renvoie la partie réelle du nombre complexe c.
"""
re, _ = c
return re | 555ded6a3814002a7ddc1c74467a9002a2bb341d | 3,627,139 |
from bs4 import BeautifulSoup
import re
def get_event_data(url: str) -> dict:
"""connpassイベントページより追加情報を取得する。
Parameters
----------
url : str
connpassイベントのurl。
Returns
-------
event_dict : dict[str, Any]
イベント情報dict。
"""
try:
html = urlopen(url)
... | bbb95eba99c57c07c4067f47cf47d69f6260d45b | 3,627,141 |
def overlap_branches(targetbranch: dict, sourcebranch: dict) -> dict:
"""
Overlaps to dictionaries with each other. This method does apply changes
to the given dictionary instances.
Examples:
>>> overlap_branches(
... {"a": 1, "b": {"de": "ep"}},
... {"b": {"de": {"eper"... | a11b54b72d4a7d79d0bfaa13ed6c351dd84ce45f | 3,627,142 |
def get_dependencies(node, skip_sources=False):
"""Return a list of dependencies for node."""
if skip_sources:
return [
get_path(src_file(child))
for child in filter_ninja_nodes(node.children())
if child not in node.sources
]
return [get_path(src_file(chil... | 2f5589f99e240b1e0c3dfed1106275e6725eae2e | 3,627,143 |
def depolarizing_channel_3q(q, p, system, ancillae):
"""Returns a QuantumCircuit implementing depolarizing channel on q[system]
Args:
q (QuantumRegister): the register to use for the circuit
p (float): the probability for the channel between 0 and 1
system (int): index of the system qub... | 154e129dd6865dccff0a172df43f52df11df0004 | 3,627,144 |
def resample_30s(annot):
"""resample_30s: to resample annot dataframe when durations are multiple
of 30s
Parameters:
-----------
annot : pandas dataframe
the dataframe of annotations
Returns:
--------
annot : pandas dataframe
the resampled dataframe of annotations
"... | 761ba6d624f7911873f3a980925c81ef6d0266dc | 3,627,145 |
def jamoToHang(jamo: str):
"""자소 단위(초, 중, 종성)를 한글로 결합하는 모듈입니다.
@status `Accepted` \\
@params `"ㅇㅏㄴㄴㅕㅇㅎㅏ_ㅅㅔ_ㅇㅛ_"` \\
@returns `"안녕하세요"` """
result, index = "", 0
while index < len(jamo):
try:
initial = chosung.index(jamo[index]) * 21 * 28
midial = jungsung.i... | 875d189f8547b637a13eb7b7eeba584044fbe484 | 3,627,146 |
def calc_Vs30(profile, option_for_profile_shallower_than_30m=1, verbose=False):
"""
Calculate Vs30 from the given Vs profile, where Vs30 is the reciprocal of
the weighted average travel time from Z meters deep to the ground surface.
Parameters
----------
profile : numpy.ndarray
Vs profi... | 3d66287836eec960b494617cb652478327ab0067 | 3,627,147 |
import torch
from typing import Optional
from typing import Dict
from typing import Any
def prepare_model(
model: torch.nn.Module,
move_to_device: bool = True,
wrap_ddp: bool = True,
ddp_kwargs: Optional[Dict[str, Any]] = None,
) -> torch.nn.Module:
"""Prepares the model for distributed execution.... | 28b1b9f3140c4782e3e6eb9fd1345c3bdec7b88f | 3,627,148 |
def make_legend_labels(dskeys=[], tbkeys=[], sckeys=[], bmkeys=[], plkeys=[],
dskey=None, tbkey=None, sckey=None, bmkey=None, plkey=None):
"""
@param dskeys : all datafile or examiner keys
@param tbkeys : all table keys
@param sckeys : all subchannel keys
@param bmkeys : all beam keys
@pa... | a8b17916f896b7d8526c5ab7ae3cf4a7435627e2 | 3,627,149 |
def get_parameter_change(old_params, new_params, ord='inf'):
"""Measure the change in parameters.
Parameters
----------
old_params : list
The old parameters as a list of ndarrays, typically from
session.run(var_list)
new_params : list
The old parameters as a list of ndarrays... | dc2f15c53b1c65acdfb60d25fd70f9c21f046b70 | 3,627,151 |
def get_image_dir():
"""Return the `image_dir` set in the current context."""
return get_data_context().image_dir | 44557bc421ba14212c089970dcc7f33978ac83fe | 3,627,152 |
import collections
def get_interface_config_vlan():
"""
Return the interface configuration parameters for all IP static
addressing.
"""
parameters = collections.OrderedDict()
parameters['VLAN'] = 'yes'
return parameters | 61ef6affba231af19e4030c54bfcaaaa15a6438f | 3,627,153 |
def parsear_ruta(linea):
"""
Lee una linea del archivo de rutas, separa los campos, y devuelve un objeto Ruta armado apropiadamente.
Si hay un error al aplicar split, y hay menos campos de los esperados, devuelve None.
Si algun valor no tiene el formato apropiado (documentado en la clase) devuelve None.
Si la ciud... | 934122d266fa799e79812613cbb539bd8ebd501d | 3,627,155 |
def split_channel_groups(data,meta):
"""
With respect to the sensor site, a different number of channels is given.
In both sites the first 160 channels contain the meg data.
params:
-------
data: array w/ shape (160+type2channels+type3channels,time_samples)
meta:
returns:
... | 399bd66b6aa7681ac67db73c6c68aae1b5f7ba72 | 3,627,156 |
from .core import read_byte_data
def _read_header_byte_data(header_structure):
""" Reads the byte data from the data file for a PDS4 Header.
Determines, from the structure's meta data, the relevant start and stop bytes in the data file prior to
reading.
Parameters
----------
header_structure... | 7115d8ecdb4ef511fd0a7b0d74e0f8484673aaf7 | 3,627,157 |
import numbers
def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance
Parameters
----------
seed : None | int | instance of RandomState
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance s... | dbb76ad1094b2d4cb2acb7d0fb7d59290ed6fd78 | 3,627,158 |
def normalize_string(value):
""" Normalize a string value. """
if isinstance(value, bytes):
value = value.decode()
if isinstance(value, str):
return value.strip()
raise ValueError("Cannot convert {} to string".format(value)) | 86d8134f8f83384d83da45ed6cb82841301e2e52 | 3,627,160 |
def _is_test_env(env_config: tox.config.TestenvConfig) -> bool:
"""Check if it is a test environment.
Tox creates environments for provisioning (`.tox`) and for isolated build
(`.packaging`) in addition to the usual test environments. And in hooks
such as `tox_testenv_create` it is not clear if the env... | bf2d9ebdc3e8d3428a5bbc0d27abd0ecc10ca6be | 3,627,161 |
def latest_version():
"""Return the latest version of Windows git available for download."""
soup = get_soup('https://git-scm.com/download/win')
if soup:
tag = soup.find('a', string='Click here to download manually')
if tag:
return downloadable_version(tag.attrs['href'])
retu... | 35563a0da6eb42e619609dd8d646a7bd5033b5da | 3,627,162 |
from datetime import datetime
def get_interval_date_list_by_freq_code(start_date, end_date, freq_code):
"""
:param freq_code: D, W, M
"""
end_date_list = get_end_date_list_by_freq_code(start_date, end_date, freq_code)
start_date = start_date
interval_date_list = []
for end_date in end_da... | 34ce484294f62ef6e7f0726e73f0c502f2c56f01 | 3,627,163 |
def _rotate_move(move, axis, n=1):
"""Rotate a move clockwise about an axis
The axis of rotation should correspond to a primitive rotation operation of
a cube Face.
"""
if n == 0:
return move
table = {
Face.U: {
'U': 'U',
'D': 'D',
'U\'': ... | 12554560bc9f2b65c101ace74b179cb252bdb62b | 3,627,165 |
def mapAddress(name):
"""Given a register name, return the address of that register.
Passes integers through unaffected.
"""
if type(name) == type(''):
return globals()['RCPOD_REG_' + name.upper()]
return name | 21f2f9a085d259d5fd46b258cc3ee0298fdda158 | 3,627,166 |
def list_index(ls, indices):
"""numpy-style creation of new list based on a list of elements and another
list of indices
Parameters
----------
ls: list
List of elements
indices: list
List of indices
Returns
-------
list
"""
return [ls[i] for i in indices] | 7e5e35674f48208ae3e0befbf05b2a2e608bcdf0 | 3,627,167 |
def create_seed_population(cities, howmany):
"""Create a seed file with tours generated by the nearest-neighbour
algorithm.
"""
attr = OrderedIndividual.get_attributes()
attr['osi.num_genes'] = len(cities) - 1
tours = generate_nntours(cities, howmany)
pop = []
for i in range(len(tours))... | 1b5338f687c0780b85c6788fe9891a10c9ee9633 | 3,627,168 |
import io
import re
def copyright_present(f):
"""
Check if file already has copyright header.
Args:
f - Path to file
"""
with io.open(f, "r", encoding="utf-8") as fh:
return re.search('Copyright', fh.read()) | afbffde0ab51984dab40d296f8ad9ca29829aef1 | 3,627,169 |
import math
def calc_LFC(in_file_2, bin_list):
"""
Mods the count to L2FC in each bin
"""
#for itereating through the bin list
bin_no=0
header_line = True
with open(in_file_2, 'r') as f:
for bin_count in f:
if header_line:
header_line = False
... | 379035fa4972c956d9734b958f3e81a3792c96d6 | 3,627,170 |
def parse_value(named_reg_value):
"""
Convert the value returned from EnumValue to a (name, value) tuple using the value classes.
"""
name, value, value_type = named_reg_value
value_class = REG_VALUE_TYPE_MAP[value_type]
return name, value_class(value) | 9e77edad1cee75973ea06c0cb2bfe6ec217abc2e | 3,627,171 |
def construct_model_vector(df, n):
"""
Convert a dataframe to an array of numpy vectors which are of the form
[(1-hot encoding of position), (game stats for n games leading up to this
one for a given player)]. If there are p positions and s stats this
vector will be of dimension p + s * n.
... | 019c5072a536e6910b2ef2a3ec9ae3682d949f10 | 3,627,172 |
import yaml
def parse_json(file_handle):
"""Parse a repeats file in the .json format
Args:
file_handle(iterable(str))
Returns:
repeat_info(dict)
"""
repeat_info = {}
try:
raw_info = yaml.safe_load(file_handle)
except yaml.YAMLError as err:
raise SyntaxErro... | 889c99594c7d92dd278caefc2af2e71fdfb0354b | 3,627,174 |
def get_value(obj, expr):
"""
Extracts value from object or expression.
"""
if isinstance(expr, F):
expr = getattr(obj, expr.name)
elif hasattr(expr, 'value'):
expr = expr.value
return expr | 9413f762e6ed19895bbbfda8da5f258bba387c80 | 3,627,175 |
from inspect import ismethod
from typing import Iterable
def _get_common_evented_attributes(
layers: Iterable[Layer],
exclude: set[str] = {'thumbnail', 'status', 'name', 'data'},
with_private=False,
) -> set[str]:
"""Get the set of common, non-private evented attributes in ``layers``.
Not all lay... | 33ce31cd98659f295f45e33788cfa69510ddb640 | 3,627,176 |
def farthest_from_point(point, point_set):
"""
find the farthest point in point_set from point and return its coordinate and its distance squared to point_set
"""
record = []
for i in point_set:
distance = euclidean_distance_square(point, i)
record.append([i, distance])
# create ... | a2105d7e96e6289f9d67aff08d3fc1934fa05a0b | 3,627,177 |
def get_subtypes():
"""Get all available subtypes"""
subtypes = []
for subtype in Subtype:
subtypes.append(subtype.value)
return subtypes | 61b858731812e1e8fe67c4a09d9bcde2cbe6c596 | 3,627,179 |
def clean_dict(dictionary: dict) -> dict:
"""Recursively removes `None` values from `dictionary`
Args:
dictionary (dict): subject dictionary
Returns:
dict: dictionary without None values
"""
for key, value in list(dictionary.items()):
if isinstance(value, dict):
... | 3968b6d354116cca299a01bf2c61d7b2d9610da9 | 3,627,180 |
def create_emoticon_stream(table, n_hours=None):
"""Creates a twitter stream object that will insert queries into
object and will terminate in n_hours
Parameters:
-----------
table: connection to mongodb table
n_hours: number of hours to run before termination, default = None
Returns:
... | 62b1eb58a81d0ce7d2e752368c3b7a969b87736d | 3,627,181 |
def tag_tranfsers(df):
"""Tag txns with description indicating tranfser payment."""
df = df.copy()
tfr_strings = [' ft', ' trf', 'xfer', 'transfer']
exclude = ['fee', 'interest']
mask = (df.transaction_description.str.contains('|'.join(tfr_strings))
& ~df.transaction_description.str.cont... | 4fdfd775ec423418370776c34fac809a513f91b5 | 3,627,182 |
from typing import Optional
from typing import Tuple
from typing import List
from typing import Dict
def calc_box(
df: dd.DataFrame,
bins: int,
ngroups: int = 10,
largest: bool = True,
dtype: Optional[DTypeDef] = None,
) -> Tuple[pd.DataFrame, List[str], List[float], Optional[Dict[str, int]]]:
... | 2ad140d7897c1a12c72a4084837fde01667b0eda | 3,627,183 |
def remove_dead_exceptions(graph):
"""Exceptions can be removed if they are unreachable"""
def issubclassofmember(cls, seq):
for member in seq:
if member and issubclass(cls, member):
return True
return False
for block in list(graph.iterblocks()):
if not b... | fc0c810eef726f0979678e3003051c99775a981d | 3,627,184 |
def borda_matrix(lTuple):
"""
Function to use the Borda count election
to integrate the rankings from different miRNA
coefficients.
Args:
lTuple list List of tuples with the correlation matrix, an the
name of the analysis (df,"value_name")
Returns:
... | 405ff7c469b9fc4026de899ab7a46e959c2280cc | 3,627,185 |
def _ImportModuleHookBySuffix(name, package=None):
"""Callback when a module is imported through importlib.import_module."""
_IncrementNestLevel()
try:
# Really import modules.
module = _real_import_module(name, package)
finally:
if name.startswith('.'):
if package:
name = _ResolveRel... | 1d9b11cec308e1a74c2aaac138c5cb3edefce62b | 3,627,187 |
import copy
def from_fake(dbc_db,
signals_properties,
file_hash_blf=("00000000000000000000000000000000"
"00000000000000000000000000000000"),
file_hash_mat=("00000000000000000000000000000000"
"00000000000000000000000000... | c7fb3f188893f6f52f9624c6a051a060bb189fad | 3,627,188 |
def frozen(request: HttpRequest):
""" Заглушка для редиректа со страниц с замороженным функционалом """
context = {'title': _('Frozen feature')}
return render(request, template_name='core/frozen.html', context=context) | bb745cb5af702af074423f048e29a60664b7dda4 | 3,627,189 |
def zero_intensity_flag(row, name_group):
"""Check if the mean intensity of certain group of samples is zero. If zero, then
the metabolite is not existed in that material.
# Arguments:
row: certain row of peak table (pandas dataframe).
name_group: name of the group.
# Returns:
... | f71b9906032c61988ff3eeccd57fb228d1049526 | 3,627,191 |
def ComputeCountryTimeSeriesWaterChange(country_id, feature = None, zoom = 1):
"""Returns a series of water change over time for the country."""
collection = ee.ImageCollection('JRC/GSW1_0/YearlyHistory')
collection = collection.select('waterClass')
scale = REDUCTION_SCALE_METERS
if feature is None:
fea... | 57c20c4b02b66afe6ba8d05ce15f1a4259818a91 | 3,627,192 |
import time
def get_largest_component(G, strongly=False):
"""
Return the largest weakly or strongly connected component from a directed
graph.
Parameters
----------
G : networkx multidigraph
strongly : bool
if True, return the largest strongly instead of weakly connected
c... | 67fe084033c54babc2ee5301ad97a9d00bab77d9 | 3,627,195 |
def _argmin(t: 'Tensor', axis=None, isnew: bool = True) -> 'Tensor':
"""
Also see:
--------
:param t:
:param axis:
:param isnew:
:return:
"""
data = t.data.argmin(axis = axis)
requires_grad = t.requires_grad
if isnew:
requires_grad = False
if requires_grad:
... | 19dd2e9ed604f4296f08381d5b80affb9472fc2c | 3,627,197 |
def new_measure_get_activity_activity(data: dict) -> MeasureGetActivityActivity:
"""Create GetActivityActivity from json."""
timezone = timezone_or_raise(data.get("timezone"))
return MeasureGetActivityActivity(
date=arrow_or_raise(data.get("date")).replace(tzinfo=timezone),
timezone=timezon... | dc77b0bc1528a409064626fd2f9c1527058d37a2 | 3,627,198 |
def have_same_SNP_order(dict_A, dict_B):
"""
Checks if two dictionaries have the same SNP order.
"""
have_same_order = [k for k in dict_A.keys() if k != "ext"] == [k for k in dict_B.keys() if k != "ext"]
return have_same_order | b885dee561e9a61bb50e814401ee088593c2517b | 3,627,200 |
def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
"""random_forest(评估算法性能,返回模型得分)
Args:
train 训练数据集
test 测试数据集
max_depth 决策树深度不能太深,不然容易导致过拟合
min_size 叶子节点的大小
sample_size 训练数据集的样本比例
n_trees... | 92c8fd7337286bf59d501f6e6fd393700791eb7e | 3,627,201 |
def define_plot_id(plot_name, plot_center):
"""Define plot id, keeping track of coordinates."""
plot_id = f"{plot_name}_X{int(plot_center[0])}_Y{int(plot_center[1])}"
return plot_id | 8f239a121598157c620ee8eef902e1d89218d01e | 3,627,202 |
def build_mask_trace(ytrace, subarray='SUBSTRIP256', halfwidth=30,
extend_below=False, extend_above=False):
"""Mask out the trace in a given subarray based on the y-positions provided.
A band of pixels around the trace position of width = 2*halfwidth will be masked.
Optionally extend_ab... | ac6e5ab113384f03b009cdce71dee197244562ab | 3,627,203 |
import json
def load_data():
"""記録データを返します"""
try:
# json モジュールでデータベースファイルを開きます
database = json.load(open(DATA_FILE, mode="r", encoding="utf-8"))
except FileNotFoundError:
database = []
return database | 6fa14606b90708c528d0f9c6993c024fa37bd804 | 3,627,204 |
from typing import Optional
def get_pattern(prefix: str) -> Optional[str]:
"""Get the pattern for the given prefix, if it's available.
:param prefix: The prefix to look up, which is normalized with :func:`normalize_prefix`
before lookup in the Bioregistry
:returns: The pattern for the prefix, if ... | 90387677f46dfda678a22d66d6fb21cecd3267c1 | 3,627,205 |
def decompressStreamToBytes(inputStream: IOBase) -> int:
"""Compresses `inputStream` into `outputStream`. Processes the whole data."""
with BytesIO() as outputStream:
decompressStreamToStream(inputStream, outputStream)
return outputStream.getvalue() | 60b03d617c9ee61198a694a4417edc835e5aff1a | 3,627,206 |
import requests
def request(url):
"""
Sends a request to a url
:param url:
"""
if not connected_to_internet():
raise ConnectionError(
"You need to have an internet connection to send requests."
)
response = requests.get(url)
if response.ok:
return res... | 61805332c73b619bc387b450a904434d1a3dc56e | 3,627,207 |
from typing import List
def pil_grid(images: List[Image.Image], max_horiz: int) -> Image.Image:
"""
Automatically creates a mosaic from a list of PIL images.
:param images: List of images in PIL form.
:param max_horiz: Maximum number of images in the column.
:return: Mosaic-like image.
"""
... | e452dd2a69540a400395e898fb2731932d451f80 | 3,627,208 |
def rd_current(phi, T):
"""
Thermionic emission current density based on Richardson-Dushman
Args:
phi: Work function (eV)
T: Temperature (K)
Returns:
Current density in J/cm**2
"""
A = 4 * np.pi * m_e * k ** 2 * e / h ** 3
return A * T ** 2 * np.exp(-phi / (k_ev * ... | 9e73560f0386b979b78872600b050f38fc842617 | 3,627,209 |
import requests
def get_default_session() -> requests.Session:
"""
get the default session used in online-judge-tools
:note: cookie is not saved to disk by default. check :py:func:`with_cookiejar`
"""
global _default_session
if _default_session is None:
_default_session = _new_sessio... | e00d2cafa9d22e842e891f771e041b5876ba4d65 | 3,627,211 |
def find_nearest(array, value):
"""
Find the nearest element in array to value.
Parameters
----------
array : np.ndarray-like
The array to search in.
value : float
The value to search.
Returns
-------
value : float
The closest value in array.
idx : int
... | 14b75a0ec20503de5711fffc5b9b7821ceb5d2b9 | 3,627,212 |
import logging
def service_remove(service_id: str):
"""
Stops and removes a service. This can also be done with Service.remove().
@param service_id: the ID of the service you want to remove.
@return: boolean value of success status
"""
try:
client.service.get(service_id).remove()
... | 0999add7b20d81723e2813ad01217a3ed8d1484b | 3,627,214 |
def mock_badvector_problem():
"""Mocks noisy DataFrames for testing vectorization"""
feat_df, _, combined_df = mock_problem()
# Feature columns are numeric, but we want to assign bad non-numeric values to test our pre-processing.
# To be able to do this, we need to set the datatype to np.object.
fo... | ed47ae7fb177b83c28dfa1fea84fab44bf19ba82 | 3,627,217 |
def name_parts(author):
"""
Given the name of an author, break it in to first, middle, last and assign a
case number to the type of name information we have
Case 0 last name only
Case 1 last name, first initial
Case 2 last name, first name
Case 3 last name, first initial, middle initial
... | 5ea03725bf124c226e42ef546f070f0423000e28 | 3,627,218 |
def _parse_header(header) -> dict:
"""
Parses the route duration, links (fare and map data), and misc. data
:param header: Element tree containing the header
"""
header, misc = header.find('td/table')
duration, links = header.findall('td')
return {
'duration': _parse_duration(dur... | f93e9b68c53bb0b9710ae62f0a7f9abc78811158 | 3,627,219 |
def get_version():
"""
Return package version as listed in `__version__` in `init.py`.
"""
return moni.VERSION | 036ba335168de6fcbff5f5f1e5dea205017f2a2f | 3,627,220 |
def calculate_mean(i, peaklocationstart, peaklocationend):
"""
This function is for calculating the mean over the specified area and returns this mean.
"""
length = peaklocationend - peaklocationstart
mean = 0
if i:
for interval in i:
if interval[0] < peaklocationstart and in... | fe57d6ab202c9c7da9894fd0d5aaab2a18ff113e | 3,627,221 |
def swag(print_swag=True):
"""Swag!"""
output = ("""
( ( (
)⧹ ))⧹ ) . ) ( )⧹ ) ( (
(()/(()/` ) /( )⧹ (()/(( )⧹))( .
/(_)/(_)( )(_)) (((_) /(_))⧹ ((_)()⧹ )
(_))(_))(_(_()) )⧹___(_))((_)_(())⧹_)()
| _ |_ _|_ _| (/ __| _ | __⧹ ⧹((_)/ /
| _/| ... | c75d804e331f61ca4b779a7a05bd0d42298b0dec | 3,627,222 |
import random
def create_conn_matrix(name, width, n_neighbors=3, n_states=2, is_sparse=True):
"""
Creates a random square matrix with Gaussian distribution according to
parameters for evodynamic.connection.WeightedConnection.
Parameters
----------
name : str
Name of the Tensor.
width : int
... | ba73809fbc7bd9dc1aa4c118b5d36134e66c6bfc | 3,627,223 |
def noticeOnFinish(filepath=success_audio):
"""
decorator function, when the fun finishes, noticeOnfinish() will play an audio in wav format(default is success_audio)
:param filepath: wav audio path
:return:
"""
def decorator(fun):
def wrapper(*args, **kwargs):
check_file_ty... | a23d4975983b8fe9851a423a37fc9d5b41cd3a27 | 3,627,224 |
def lista_clientes(request):
""" Página com a lista de clientes """
# Pega informações da URL
codigo = request.GET.get('search_cod_client', '')
nome = request.GET.get('search_name_client', '')
deletado = request.GET.get('deleted', False)
page = int(request.GET.get('page', 1))
# Filtra list... | 3e2c9c4e74ff00de78e13fb47641e1881c1e0abe | 3,627,231 |
def collection_getter (getter, *args, **kwargs):
"""Adds variables to relevant collections."""
var = getter(*args, **kwargs)
name = kwargs['name']
trainable = kwargs['trainable']
if trainable:
if 'kernel' in name:
tf.add_to_collection(tf.GraphKeys.WEIGHTS, var)
if 'bia... | 6876a19a24b609f3128e2fac9dfcb1cf7601bb9f | 3,627,234 |
def E_edgePair(mesh, edgePair, width, height, edge_len):
"""
Compute the energy coefficient matrix over a single edge pair.
Inputs:
mesh - the model in OBJ format
edgePair - the edgePair of the model in (fi, (fv0, fv1)) format
width, height - texture's dimensions
edge_len - ... | 24ec14ecb9d2c66465f79f484f6f8707c4863f0f | 3,627,235 |
def getComponentReadingClassByType(componentType):
"""Given the path mapping of a point, get the class that it belongs to"""
componentClass = None
if componentType == "AHU":
componentClass = AHUReading
elif componentType == "VFD":
componentClass = VFDReading
elif componentType == "Filter":
componentClass =... | fab2a51067a28fa2672afda01b8eedb07a589764 | 3,627,236 |
def from_rotation_matrix(mtr):
"""
See
http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
"""
mtr = tf.convert_to_tensor(mtr)
def m(j, i):
shape = mtr.shape.as_list()
begin = [0 for _ in range(len(shape))]
begin[-2] = j
begin[-1... | e1b7f4391ec2b401b80eeb43c3cdfdc4e050a2e2 | 3,627,237 |
import json
def findSimilarVectors(single_id):
"""
Return a list of _id's that are most similar to the original id
"""
topic_result, distances = nearestNeighbors.similar_from_id(single_id, 5)
topic_result = json.dumps(topic_result, default = json_util.default)
print(topic_result)
return to... | 3b350333fac9bd8f64755af4782b35d5f925cf7a | 3,627,238 |
def set_sleep(sleep=False):
"""When the option 'sleep' is True, after plotting the computation is paused for 0.01 secs. Optionally, the sleeping time (in secs) can be fixed if a the number is passed (eg: sleep=0.001). The default value is False."""
if sleep==False and type(sleep)==bool:
h.sleep=None
... | 0ce62689b8f181663067adb06497fc9f346f2f4d | 3,627,239 |
def format_msg(fmt, use_color=False):
"""Replace $RESET and $BOLD with corresponding ANSI entries"""
if use_color:
return fmt.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
else:
return fmt.replace("$RESET", "").replace("$BOLD", "") | eb07a2871d8b14c19452aa29853c5f4ee72fd8f2 | 3,627,240 |
def add_week_course_activity(course_id: int, weektime_id: int, cur_week: int ,course_stage2: bool):
"""
添加每周的课程活动
"""
course = Course.objects.get(id=course_id)
examine_teacher = NaturalPerson.objects.get_teacher(
get_setting("course/audit_teacher"))
# 当前课程在学期已举办的活动
conducted_num = Ac... | 1ed5ac73a3efebd826a57d5aa757335313eaa0a3 | 3,627,241 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.