content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def checksum2(path):
"""Calculate the checksum of a TSV.
The checksum of a TSV is calculated as the sum of the division between the
only two numbers in each row that evenly divide each other.
Arguments
---------
path : str
Path to a TSV file.
Returns
-------
The checksum o... | 5,323,900 |
def load_config(config_file_path):
"""
Load the config ini, parse settings to WORC
Args:
config_file_path (String): path of the .ini config file
Returns:
settings_dict (dict): dict with the loaded settings
"""
settings = configparser.ConfigParser()
settings.read(config_fil... | 5,323,901 |
def preinit_js9():
"""Pre-initialization, when Javascript is not available yet. Determines paths and starts helper processs"""
global radiopadre_kernel
import radiopadre_kernel
import iglesia
global JS9_HELPER_PORT, JS9_DIR
JS9_DIR = iglesia.JS9_DIR
JS9_HELPER_PORT = iglesia.JS9HELPER_PORT
... | 5,323,902 |
def find_toplevel() -> pathlib.Path:
"""Get the toplevel git directory."""
return pathlib.Path(cmd_output(["rev-parse", "--show-toplevel"]).strip()) | 5,323,903 |
def db20(value):
"""Convert voltage-like value to dB."""
return 20 * log10(np.abs(value)) | 5,323,904 |
def construct_class_by_name(*args, class_name: str = None, **kwargs) -> Any:
"""Finds the python class with the given name and constructs it with the given arguments."""
return call_func_by_name(*args, func_name=class_name, **kwargs) | 5,323,905 |
def simple_file_scan(reader, bucket_name, region_name, file_name):
""" Does an initial scan of the file, figuring out the file row count and which rows are too long/short
Args:
reader: the csv reader
bucket_name: the bucket to pull from
region_name: the region to pull fr... | 5,323,906 |
def delete_lblannots(ibs, lblannot_rowid_list):
"""deletes lblannots from the database"""
if ut.VERBOSE:
logger.info('[ibs] deleting %d lblannots' % len(lblannot_rowid_list))
ibs.db.delete_rowids(const.LBLANNOT_TABLE, lblannot_rowid_list) | 5,323,907 |
def random_plane(model: typing.Union[torch.nn.Module, ModelWrapper], metric: Metric, distance=1, steps=20,
normalization='filter', deepcopy_model=False) -> np.ndarray:
"""
Returns the computed value of the evaluation function applied to the model or agent along a planar
subspace of the para... | 5,323,908 |
def _solarize_impl(pil_img, level):
"""Applies PIL Solarize to `pil_img`.
Translate the image in the vertical direction by `level`
number of pixels.
Args:
pil_img: Image in PIL object.
level: Strength of the operation specified as an Integer from
[0, `PARAMETER_MAX`].
Returns:
A PIL Ima... | 5,323,909 |
def detect_area(hsv_img,lower_color,upper_color,marker_id,min_size,draw=False):
"""Detects the contour of an object containing a marker based on color
It always returns the smallest contour which still contains the marker
The contour is detected using an image with hsv color space to be robust under di... | 5,323,910 |
def payment_callback():
"""通用支付页面回调"""
data = request.params
sn = data['sn']
result = data['result']
is_success = result == 'SUCCESS'
handle = get_pay_notify_handle(TransactionType.PAYMENT, NotifyType.Pay.SYNC)
if handle:
# 是否成功,订单号,_数据
return handle(is_success, sn)
if ... | 5,323,911 |
def get_users_name(path):
"""
登録されているユーザ情報の回収
Parameters
----------
path : str
homeディレクトリまでのパス
Returns
-------
name_dict : dict
登録ユーザ情報の辞書
"""
path_db = os.path.join(path, 'data', 'list.db')
name_list = []
with sqlite3.connect(path_db) as conn:
c... | 5,323,912 |
def get_rest_parameter_state(parameter_parsing_states):
"""
Gets the rest parameter from the given content if there is any.
Parameters
----------
parameter_parsing_states `list` of ``ParameterParsingStateBase``
The created parameter parser state instances.
Returns
-------
p... | 5,323,913 |
def random_user_id() -> str:
"""Return random user id as string."""
return generate_random_id() | 5,323,914 |
def import_plugin(name):
"""Tries to import given module"""
path = os.path.join(BASE_PATH, "backends", "plugins", name + ".py")
try:
with open(path, 'rb') as f:
try:
plugin = imp.load_module(
"p_" + name, f, name + '.py',
('.py', 'r... | 5,323,915 |
def batch_answer_same_question(question: str, contexts: List[str]) -> List[str]:
"""Answers the question with the given contexts (local mode).
:param question: The question to answer.
:type question: str
:param contexts: The contexts to answer the question with.
:type contexts: List[str]
:retur... | 5,323,916 |
def test_delete_invite_timestamp_issue(client: flask.testing.FlaskClient) -> None:
"""Test that the delete_invite cronjob deletes invites with '0000-00-00 00:00:00' timestamp."""
assert len(db.session.query(models.Invite).all()) == 2
invites = db.session.query(models.Invite).all()
for invite in invites:... | 5,323,917 |
def rename13(dirs=None, basis_dir=None):
"""
Renames all ``*.13`` files in ``dirs`` to ``fort.13``
:param list dirs: list of directory names
"""
files = []
if dirs is None and basis_dir is None:
files = glob.glob(os.path.join('landuse_*', '*.13'))
elif dirs is None and basis_dir:
... | 5,323,918 |
def ObitHelp (Task):
"""
Give Help for OBIT task Task
* Task = ObitTask name to give (e.g. "Feather")
"""
################################################################
t=ObitTask(Task)
t.help()
# end ObitHelp | 5,323,919 |
def run_cross_validation_v2(n_folds: int = 10) -> None:
""" V2 of Function to derive a keras solution with cross-validation for selected drivers
Args:
n_folds: Number of cross-validation folds
"""
np.random.seed(2016)
warnings.filterwarnings("ignore")
use_cache = 1
# input i... | 5,323,920 |
def add_watch(expr): #py:add_watch
"""
Adds a valid Python expression (given as a string) to
the watch list.
"""
RUR.add_watch(expr) | 5,323,921 |
def calculate_log_probs(conditioners, joint_dists):
"""
Calculates the marginal log probabilities of each feature's values and also the conditional
log probabilities for the predecessors given in the predecessor map.
"""
log_marginals = [
N.log(joint_dists[f,f])
for f in xrange(len(condi... | 5,323,922 |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv:
argv = sys.argv
# setup command line parser
parser = E.OptionParser(
version="%prog version: $Id$",
usage=globals()["__doc__"])
parser.add_option... | 5,323,923 |
def validate_response_code(response, expected_res):
""" Function to validate work order response.
Input Parameters : response, check_result
Returns : err_cd"""
# check expected key of test case
check_result = {"error": {"code": 5}}
check_result_key = list(check_result.keys())[0]
# ch... | 5,323,924 |
def _calc_density(x: np.ndarray, y: np.ndarray):
"""\
Function to calculate the density of cells in an embedding.
"""
from scipy.stats import gaussian_kde
# Calculate the point density
xy = np.vstack([x, y])
z = gaussian_kde(xy)(xy)
min_z = np.min(z)
max_z = np.max(z)
# Scale ... | 5,323,925 |
def gen_layer_code(graph, sub_layers, sub_layers_name, different_attrs=dict()):
""" 根据sub_layers生成对应的Module代码。
Args:
graph (x2paddle.core.program.PaddleGraph): 整个Paddle图。
sub_layers (dict): 子图的id和其对应layer组成的字典。
sub_layers_name (str): 子图的名字。
different_attrs (dict/list): 属性字典/列表,这... | 5,323,926 |
def savetable_S4(filename, time, wavelength, bin_width, lcdata, lcerr):
"""Saves data in an event as .txt using astropy
Parameters
----------
event : An Event instance.
Description
-----------
Saves data stored in an event object as an table
Returns
-------
.txt file
R... | 5,323,927 |
def test_CreativeProject_integration_ask_tell_one_loop_kwarg_response_works(covars, model_type, train_X, train_Y,
covars_proposed_iter, covars_sampled_iter,
response_sampled_iter, kwarg_re... | 5,323,928 |
def test_create_user_missing_role(mocker: Any, get_user_by_email_failure_fixture: Any, get_role_fixture: Any) -> None:
"""Check if create user method raises exception when role does not exists."""
email = 'test@mail.com'
password = 'medtagger'
first_name = 'First'
last_name = 'Last'
with pytest... | 5,323,929 |
def read_all_files(filenames):
"""Read all files into a StringIO buffer."""
return io.StringIO('\n'.join(open(f).read() for f in filenames)) | 5,323,930 |
def run(r_srffile, sim_id=0):
"""
Creates a SRF plot from an SRF file
"""
install = InstallCfg.getInstance()
a_outdir = os.path.join(install.A_OUT_DATA_DIR, str(sim_id))
a_tmpdir = os.path.join(install.A_TMP_DATA_DIR, str(sim_id))
srf2xyz_bin = os.path.join(install.A_GP_BIN_DIR, "srf2xyz")
... | 5,323,931 |
def calculate_distance(geojson, unit: Unit = Unit.meters) -> Optional[float]:
"""
Calculate distance of LineString or MultiLineString GeoJSON.
Raises geojson_length.exc.GeojsonLengthException if input GeoJSON is invalid.
:param geojson: GeoJSON feature of type LineString or MultiLineString
:param un... | 5,323,932 |
def weighted_mse_loss(y_true, y_pred):
"""
apply weights on heatmap mse loss to only pick valid keypoint heatmap
since y_true would be gt_heatmap with shape
(batch_size, heatmap_size[0], heatmap_size[1], num_keypoints)
we sum up the heatmap for each keypoints and check. Sum for invalid
keypoint... | 5,323,933 |
def p_marketprices(
i: pd.DatetimeIndex,
avg: float = 100,
year_amp: float = 0.30,
week_amp: float = 0.05,
peak_amp: float = 0.30,
has_unit: bool = True,
) -> pd.Series:
"""Create a more or less realistic-looking forward price curve timeseries.
Parameters
----------
i : pd.Datet... | 5,323,934 |
def read_flow(fn):
""" Read .flo file in Middlebury format"""
# Code adapted from:
# http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
# WARNING: this will work on little-endian architectures (eg Intel x86) only!
with open(fn, 'rb') as f:
... | 5,323,935 |
def enable_debugging(enable: bool = True, enable_sql: bool = True) -> None:
"""
enables Pony's debugging as well as other logging in this module
"""
if enable:
pass
if enable_sql:
orm.set_sql_debug(debug=True, show_values=True) | 5,323,936 |
def run_rotors(run_tors_names, const_names):
""" a
"""
info_message(
'Running hindered rotor scans for the following rotors...',
newline=1)
for names in run_tors_names:
info_message(names)
if const_names is not None:
if set(list(chain(*run_tors_names))) == set(const_n... | 5,323,937 |
def test_parse_VisitError_raises_original_exception(
version_selector: VersionSelector, handled_exception
):
"""
Ensures that custom errors such as ``ParseFailure`` and ``InvalidExpression`` are
re-raised as the root exception from containing ``VisitErrors`` when applying the
``SemselTransformer``.
... | 5,323,938 |
def p_boolean_expression(p):
"""boolean_expression: expression""" | 5,323,939 |
def sma(grp_df: pd.DataFrame, cols: List[str], windows: List[int]) -> pd.DataFrame:
"""
Calculate the simple moving average.
Parameters:
-------
grp_df: pd.DataFrame
The grouped dataframe.
col: str
window: list
List of windows to take simple moving average.
"""
for w... | 5,323,940 |
def add_anchor_tag(anchor_id, header):
"""
Add anchor tag to header.
Input and output will look like below.
Input:
## Task 02 - Do something
Output:
## <a id="task02"></a> Task 02 - Do something [^](#toc)
"""
anchor = ANCHOR.format(anchor_id)
# Replace the first space w... | 5,323,941 |
def check_unused_samples(loaded_csv_dict, loaded_img_dict):
"""Checks whether any samples loaded from a sample_info.csv file do not
match any samples loaded from a project folder. Prints a warning if
true.
Parameters
----------
loaded_csv_dict : dict{str: float}
A dict with values... | 5,323,942 |
def create_async_executor(query: Query) -> Callable:
"""Create async executor for query.
Arguments:
query: query for which executor should be created.
Returns:
Created async executor.
"""
executor = _OPERATION_TO_EXECUTOR[query.operation_type]
return partial(executor, query) | 5,323,943 |
def batch_write_coverage(bed_fname, bam_fname, out_fname, by_count, processes):
"""Run coverage on one sample, write to file."""
cnarr = coverage.do_coverage(bed_fname, bam_fname, by_count, 0, processes)
tabio.write(cnarr, out_fname)
return out_fname | 5,323,944 |
def splitTargets(targetStr):
""" break cmdargs into parts consisting of:
1) cmdargs are already stripped of their first arg
2) list of targets, including their number. Target examples:
* staff
* staff 2
* staff #2
* player
* player #3
"""
... | 5,323,945 |
def get_model():
"""
Epoch 50/50
3530/3530 [==============================] - 10s - loss: 8.5420e-04 - acc: 1.0000 - val_loss: 0.3877 - val_acc: 0.9083
1471/1471 [==============================] - 1s
Train score: 0.00226768349974
Train accuracy: 1.0
"""
model=Sequential()... | 5,323,946 |
def path_inside_dir(path, directory):
"""
Returns True if the specified @path is inside @directory,
performing component-wide comparison. Otherwise returns False.
"""
return ((directory == "" and path != "")
or path.rstrip("/").startswith(directory.rstrip("/") + "/")) | 5,323,947 |
def register_routes(app: 'Application', routes_table):
"""Add routes handlers of the server."""
for method, path, handler, name in routes_table:
app.router.add_route(method, path, handler, name=name) | 5,323,948 |
def tfi_chain(qubits, boundary_condition="closed", data_dir=None):
"""1D Transverse field Ising-model quantum data set.
$$
H = - \sum_{i} \sigma_i^z \sigma_{i+1}^z - g\sigma_i^x
$$
Contains 81 circuit parameterizations corresponding to
the ground states of the 1D TFI chain for g in [0.2,1.8].
... | 5,323,949 |
def generateObjectsIntroductionInfo(typeMode):
"""
generates gaps between introduction days based on either pareto or exponential distribution
"""
global NUM_OF_OBJECTS
global numOfObjectsIntroduced
tempNumOfObjectsIntroduced = []
while sum(tempNumOfObjectsIntroduced) < NUM_OF_OBJECTS:
... | 5,323,950 |
def _process(response):
"""Dummy post-processing after http request"""
pass | 5,323,951 |
def save_pca(result={}, sample_ids=[], output_fn=None, max_size=10):
"""Save PCA."""
data = {
"flot": {
"data": result["coordinates"],
"xlabel": "PC 1",
"ylabel": "PC 2",
"sample_ids": sample_ids,
},
"zero_gene_symbols": result["skipped_gen... | 5,323,952 |
def generate_sd_grid_mapping_traj(ipath_sd, n_top_grid, ipath_top_grid, ipath_grid_block_gps_range,
odir_sd, mapping_rate=1, mapping_bais=None):
"""generate the gird-mapping traj for SD
"""
def random_sampling(grid_range):
"""generate a sample point within a grid ra... | 5,323,953 |
def get_2bit_path(db_opt):
"""Check if alias and return a path to 2bit file."""
if os.path.isfile(db_opt): # not an alias
return db_opt # there is nothing to do
aliased = two_bit_templ.format(db_opt)
# check that it's a file
die(f"Error! Cannot find {aliased} file", 1) if not os.path.isfil... | 5,323,954 |
def test_save_load_from_video(test_video_file):
""" Test generating and saving some frame metrics from TEST_VIDEO_FILE to a file on disk, and
loading the file back to ensure the loaded frame metrics agree with those that were saved.
"""
video = VideoStreamCv2(test_video_file)
stats_manager = StatsMa... | 5,323,955 |
def butterworth_type_filter(frequency, highcut_frequency, order=2):
"""
Butterworth low pass filter
Parameters
----------
highcut_frequency: float
high-cut frequency for the low pass filter
fs: float
sampling rate, 1./ dt, (default = 1MHz)
period:
period of the sign... | 5,323,956 |
def draw_mesh(
# Main input
edof,
coord,
dof,
element_type,
# Other parameters
scale = 0.02,
alpha = 1,
render_nodes = True,
color = 'yellow',
offset = [0, 0, 0],
# BC- & F-marking
bcPrescr = None,
bc = None,
bc_color = 'red',
fPrescr = None,
f = Non... | 5,323,957 |
def test_section_11():
"""Section 11: Precedence rules.
Precedence MUST be calculated by separating the version
into major, minor, patch, pre-release, and build
identifiers in that order. Major, minor, and patch
versions are always compared numerically. Pre-release
and build version precedence ... | 5,323,958 |
def mypad(x, pad, mode='constant', value=0):
""" Function to do numpy like padding on tensors. Only works for 2-D
padding.
Inputs:
x (tensor): tensor to pad
pad (tuple): tuple of (left, right, top, bottom) pad sizes
mode (str): 'symmetric', 'wrap', 'constant, 'reflect', 'replicate', ... | 5,323,959 |
def molarity(compound, setting = None, moles = None, volume = None):
"""
Calculations involving the molarity of a compound. Returns a value based on the setting.
The compound must be the Compound class. The moles/volume setting will be gathered from the compound itself if defined.
**Volume is assumed to be ... | 5,323,960 |
def set_initial_det(noa, nob):
""" Function
Set the initial wave function to RHF/ROHF determinant.
Author(s): Takashi Tsuchimochi
"""
# Note: r'~~' means that it is a regular expression.
# a: Number of Alpha spin electrons
# b: Number of Beta spin electrons
if noa >= nob:
# Here... | 5,323,961 |
def face_detection(frame):
""" detect face using cv2
:param frame:
:return: (x,y), w, h: face position x,y coordinates, face width, face height
"""
if frame is None :
return 0,0,0,0
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gr... | 5,323,962 |
def coro1():
"""定义一个简单的基于生成器的协程作为子生成器"""
word = yield 'hello'
yield word
return word # 注意这里协程可以返回值了,返回的值会被塞到 StopIteration value 属性 作为 yield from 表达式的返回值 | 5,323,963 |
def _deduce_num_classes(params):
"""Set `num_classes` for `params`."""
if 'imagenet' in params.dataset_name.lower():
num_classes = 1000
elif 'cifar100' in params.dataset_name.lower():
num_classes = 100
else:
logging.info(
f'Cannot infer `num_classes` for dataset {params.dataset_name}. Use 10... | 5,323,964 |
def plot_combinations_9array3x3_v2(coli_to_test, sorted_combinations, sorted_vals, comb_ind, renaming_fun):
"""Plot the nine best decompositions of a given set with variables
outside the matrix for a decomposition of 3 variables
Parameters
----------
coli_to_test : Pandas dataframe
cell... | 5,323,965 |
def print_table_of_2_params(results, param_x, param_y, title="Some table"):
"""
Prints table from the results dictionary, currently used only to print the tables for the heatmaps in the
report.
"""
results = results['estimator'][0].cv_results_
param_list_x = set()
param_list_y = set()
fo... | 5,323,966 |
def random_split(df: Union[DataFrame, Series], split_size: float,
shuffle: bool = True, random_state: int = None) -> Tuple[DataFrame]:
"""Shuffles a DataFrame and splits it into 2 partitions according to split_size.
Returns a tuple with the split first (partition corresponding to split_size, an... | 5,323,967 |
def create_discriminator_inputs(images, conditional_vectors):
"""
識別器用入力画像(画像+条件画像)を生成する。
Args:
images: 画像
conditional_vectors: 条件ベクトル
index: image_seqから取得するデータのインデックス
Returns
画像+条件画像を統合したテンソル (B, H, W, A + C)
B: バッチサイズ。images.shape[0]
H: 画像の高さ。images... | 5,323,968 |
def gfs_scan_bands(filepath: str):
"""
Helper function to scan through all bands in grib file and save their names into csv file.
:param filepath: path to particular grib file.
"""
if not os.path.isfile(filepath):
raise ValueError("Wrong filepath - file not found!")
grib = gdal.Open(f... | 5,323,969 |
def add_to_master_list(single_list, master_list):
"""This function appends items in a list to the master list.
:param single_list: List of dictionaries from the paginated query
:type single_list: list
:param master_list: Master list of dictionaries containing group information
:type master_list: li... | 5,323,970 |
def weight_by_attr(
attr: str, prev_edge: Optional[models.Edge], edge: models.Edge
) -> float:
"""
Generic weight function to retrieve a value from an edge.
"""
return getattr(edge, attr) | 5,323,971 |
def check_if_porous(structure: Structure, threshold: float = 2.4) -> Union[bool, None]:
"""Runs zeo++ to check if structure is porous according to the CoRE-MOF
definition (PLD > 2.4, https://pubs.acs.org/doi/10.1021/acs.jced.9b00835)
Args:
structure (Structure): MOF structure to check
thres... | 5,323,972 |
def load_vlay( #load a layer from a file
fp,
providerLib='ogr',
logger=mod_logger):
"""
what are we using this for?
see instanc emethod
"""
log = logger.getChild('load_vlay')
assert os.path.exists(fp), 'requested file does not exist: %s'%fp
basef... | 5,323,973 |
def order_node_list(tree):
"""
Sorts a list of node dict from a LightGBM instance. Key `tree_structure` is
specific for LightGBM.
Parameters
----------
tree : list,
Unsorted list of node dicts
Returns
-------
ordered_node_list : list,
Ordered list of node dicts com... | 5,323,974 |
def test_build(topology):
"""
Test automatic build and unbuild of the topology using pytest plugin.
"""
assert config.pluginmanager.getplugin('topology')
assert isinstance(topology, TopologyManager)
assert topology.get('sw1') is not None
assert topology.get('sw2') is not None
assert topo... | 5,323,975 |
def teardown_request_wrap(exception):
"""
Prints tracebacks and handles bugs
"""
if exception:
logging.error(traceback.format_exc())
return json.dumps({"result":None, 'error':{'message':'Invalid request'}, 'id':1}) | 5,323,976 |
def sanitize_parameters(func):
"""Sets any queryparams in the kwargs"""
@wraps(func)
def wrapper(*args, **kwargs):
try:
logging.info(f'[middleware] [sanitizer] args: {args}')
myargs = dict(request.args)
# Exclude params like loggedUser here
sanitized_... | 5,323,977 |
def build_render_setup(cfg):
"""Build information struct about the rendering backup from a configuration.
This performs type conversion to the expected types. Paths contained in
cfg are expected to be alread expanded. That is, it should not contain
global variables or other system dependent abbreviatio... | 5,323,978 |
def generate_coupled_image_from_self(img, out_img, noise_amp=10):
"""
Generates an input image for siam by concatenating an image with a transformed version of itself
"""
def __synthesize_prev_img(in_img, noise_amp=10):
"""Synthesizes previous frame by transforming the input image
... | 5,323,979 |
def pca_preprocess(df, pca_components):
"""Preprocess the given dataframe using PCA"""
# Drop rows
df.dropna(axis=0, inplace=True)
# Separate features and targets
X = df.drop('ASPFWR5', axis=1)
y = df['ASPFWR5']
# Dimensionality reduction with principal component ana... | 5,323,980 |
def add_nonce(func):
"""Helper function which adds a nonce to the kwargs dict"""
@wraps(func)
def inner(*args, **kwargs):
if "nonce" not in kwargs:
kwargs["nonce"] = int(datetime.datetime.utcnow().timestamp() * 1000)
return func(*args, **kwargs)
return inner | 5,323,981 |
def build_train_dict(config_file: str, task: str) -> Dict[str, Any]:
"""
Read the configuration file given by the user.
If it is a TOML file, ensures that the format corresponds to the one in resources.
Args:
config_file: path to a configuration file (JSON of TOML).
task: task learnt by ... | 5,323,982 |
def lint() -> None:
"""Run linter checks."""
execute("lint", ["flake8"], "Address any remaining flake8 issues manually.") | 5,323,983 |
def morse_encode(string):
"""Converts a string to morse code"""
words = [morse_encode_word(word) for word in string.split(' ')]
return ' '.join(words) | 5,323,984 |
def examples():
"""Load example paths."""
return [(loader(path), path) for path in glob.glob(os.path.join(RESOURCE_DIR, "examples", "*.json"))] | 5,323,985 |
def TIMES_cleanup (file, Model_Module):
"""Cleans data genrated by Oasis TIMES and returns a dataframe witht he DTXSID of the parent compound and InChI key of each metabolite"""
"""The Model_Module argument should be a string to designate the model used for metabolism (e.g., TIMES_RatLiver S9, TIMES_RatInVivo... | 5,323,986 |
def generate_key():
"""Generate an key for our cipher"""
shuffled = sorted(chars, key=lambda k: random.random())
return dict(zip(chars, shuffled)) | 5,323,987 |
def get_sdkconfig_value(sdkconfig_file, key):
"""
Return the value of given key from sdkconfig_file.
If sdkconfig_file does not exist or the option is not present, returns None.
"""
assert key.startswith('CONFIG_')
if not os.path.exists(sdkconfig_file):
return None
# keep track of th... | 5,323,988 |
def unmatched(match):
"""Return unmatched part of re.Match object."""
start, end = match.span(0)
return match.string[:start] + match.string[end:] | 5,323,989 |
def cubicgw(ipparams, width, etc = []):
"""
This function fits the variation in Gaussian-measured PRF half-widths using a 2D cubic.
Parameters
----------
x1: linear coefficient in x
x2: quadratic coefficient in x
x3: cubic coefficient in x
y1: linear coefficient in y
y2: quadratic coeffici... | 5,323,990 |
def _make_parser():
""" Generates argument parser with all necessarry parameters.
:returns script's arguments (host, port, index, type, id,
searchserver, server, stdin, pipeline)
:rtype argparse.ArgumentParser
"""
p = argparse.ArgumentParser(description=__doc__,
forma... | 5,323,991 |
def main():
"""
This function displays all the gui elements of the music recommender system
Parameters:
-
Returns:
df_list (DataFrame): the list of input audio entered by the user
"""
fileslist... | 5,323,992 |
def get_columns_by_type(df, req_type):
"""
get columns by type of data frame
Parameters:
df : data frame
req_type : type of column like categorical, integer,
Returns:
df: Pandas data frame
"""
g = df.columns.to_series().groupby(df.dtypes).groups
type_dict = {k.name: v for k, v ... | 5,323,993 |
def print_atoms(inp_file, atoms, fixed_atom_idxs):
"""Print the atoms to the input file depending on whether they are fixed"""
for i, atom in enumerate(atoms):
x, y, z = atom.coord
if i in fixed_atom_idxs:
line = f'{atom.label:<3}{x:^10.5f} 0 {y:^10.5f} 0 {z:^10.5f} 0'
else... | 5,323,994 |
def get_total(lines):
"""
This function takes in a list of lines and returns
a single float value that is the total of a particular
variable for a given year and tech.
Parameters:
-----------
lines : list
This is a list of datalines that we want to total.
Returns:
--------
... | 5,323,995 |
def get_ipv6_by_ids(ip_ids):
"""Get Many Ipv6."""
networks = list()
for ip_id in ip_ids:
networks.append(get_ipv6_by_id(ip_id))
return networks | 5,323,996 |
def box(t, t_start, t_stop):
"""Box-shape (Theta-function)
The shape is 0 before `t_start` and after `t_stop` and 1 elsewhere.
Args:
t (float): Time point or time grid
t_start (float): First value of `t` for which the box has value 1
t_stop (float): Last value of `t` for which the ... | 5,323,997 |
def main():
"""
The main function, where the program starts.
:return: None
"""
user = start_story()
paths = [scott_adventure, places_to_go(), team_2_adv,
team_3_adv, team_4_adv, team_5_adv,
team_6_adv, team_7_adv, team_8_adv,
team_9_adv, team_10_adv, cullo... | 5,323,998 |
def updateBaselines(product, date:datetime, n_workers=20, block_scale_factor= 1, time=False) -> dict:
"""Updates anomaly baselines
***
Parameters
----------
product:str
date:datetime
n_workers:int
block_scale_factor:int
time:bool
Returns
-------
Dictionary with the fol... | 5,323,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.