content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def seq2kmer(seq, k):
"""
Convert original sequence to kmers
Arguments:
seq -- str, original sequence.
k -- int, kmer of length k specified.
Returns:
kmers -- str, kmers separated by space
"""
kmer = [seq[x:x+k] for x in range(len(seq)+1-k)]
kmers = " ".join(kmer)
... | 21cdb39f2484ad4ca4ca18f2e0c9f8fba59fd0f6 | 648,559 |
from typing import Dict
from typing import Union
from typing import List
from typing import Any
import requests
def get_record_by_doi(
doi: str, is_version_doi=True, query_params: Dict[str, Union[int, str]] = {"size": 1}
) -> List[Dict[str, Any]]:
"""Retrieve a Record from the zenodo api, where doi or concept... | 5a29ae1000ae0ae1189f32040521ff51a7d4a29a | 648,560 |
import six
def _DictToMetadataMessage(message_classes, metadata_dict):
"""Converts a metadata dict to a Metadata message."""
message = message_classes.Metadata()
if metadata_dict:
for key, value in sorted(six.iteritems(metadata_dict)):
message.items.append(message_classes.Metadata.ItemsValueListEntry(... | 10334ffea0872ffe55ca60ac032f51003fa88a88 | 648,562 |
def set_zenodo(ctx, production):
"""Add Zenodo details: api urls, communities, to context object
Parameters
----------
ctx: dict
Click context obj to pass arguments onto sub-commands
production: bool
If True using production api, if False using sandbox
Returns
-------
c... | 03a07c7d8aaac397c78bc4ed153b028bfcdbdc10 | 648,563 |
def parse_title(raw_title):
"""
用来移除title中的高亮字符
"""
return raw_title.replace('</em>', '').replace('<em>', '') | 6f04cd7e09498cb6b22397bacbe74798f1b35fe6 | 648,564 |
def process_extracted_contents(inline_intro):
"""
Remove html markup
"""
return inline_intro['contents'] | 0910daaa6557ac036de40e769cc30e9c130ae9ba | 648,565 |
def get_donor_db():
"""
Return an in-memory representation of the donor database
Each donor is represented by a tuple -- kind of like a record
in a database table
The full collection uses a dict with a "normalized" version of
the donor's name as the key:
- all lower case
- spac... | 9b767c571d5bd363e148ed7c0bd286f806e394be | 648,566 |
def transfer_annotations_prob(mapping_matrix, to_transfer):
"""
Transfer cell annotations onto space through a mapping matrix.
Args:
mapping_matrix (ndarray): Mapping matrix with shape (number_cells, number_spots).
to_transfer (ndarray): Cell annotations matrix with shape (number_cells, numb... | 65d6d3167e63c5031f4216c80622960c30a7f8f6 | 648,567 |
from pathlib import Path
import os
def get_root():
"""
Get the path of the project's root directory.
Parameters
----------
None
Returns
-------
str
Path of the project's root directory.
"""
root = str(Path(os.path.abspath(__file__)).parents[1])
return root | 5b7e2615d4b1294f364b463e2e14a3dca0978b4b | 648,568 |
def s_to_min(value):
"""Convert seconds to minutes."""
return "{}:{:02d}".format(int(value // 60), int(value % 60)) | 7aa4fd1e259f288eb04a49a60db41bae3378ed01 | 648,569 |
import inspect
def get_classes_from_module(module):
""" Extract module and name of classes.
Simple version that does not deal with classes nested in other classes.
"""
classes_and_modules = []
class_descriptions = inspect.getmembers(module, inspect.isclass)
# cutting the end allows to find cl... | d1eb850eb285dbebd02cf5081f8a5a62b6beeb03 | 648,570 |
from typing import Optional
import os
def oldest_in_directory(directory: str) -> Optional[str]:
""" Returns the full filepath of the oldest file or folder in the given
directory
Uses last metadata change time of each file to determine the least
recently modified. Returns None if the given directory i... | 83f84cac448540fc2e58f1b98403ec590361b293 | 648,571 |
import re
def change_case(s, separator="-"):
"""Changes the case to snake/kebab case depending on the separator.
As regexes can be confusing, I'll just go through this line by line as an
example with the following string: ' Foo2Boo_barBaz bat'
1. Remove whitespaces from beginning/end. => 'Foo2Boo_ba... | 544b4b1e7dbde7f19ed99831b21c2a5e4a4c01c1 | 648,572 |
import random
def is_prime_prob(n, k=5):
"""
Returns <True> if <n> is a prime number, returns <False> otherwise. It
uses a probabilistic method based on the Fermat little theorem. The
probability of false positives can be reduced incresing <k>.
- The probability of error when returns <True> is ze... | e6ad7a270d1ccf1aa08971a69dab8cf3c009dfca | 648,573 |
def tablestyles():
"""Emit the fixed table styles."""
return '\ntable.middle td { vertical-align: middle; }\n th.center { text-align: center; }\n th.right { text-align: right; }\n td.right { text-align: right; }\n' | d77642678f34b845507c78ebcfcf440501cea094 | 648,574 |
import os
def chk_sep(path):
"""
判断路径字符串末尾是否有分隔符
:param path: 要检查的路径
:return: 布尔值
"""
if path[-1] != os.path.sep:
return False
else:
return True | 25c03f9f675b2595521c45fea5e6919bc4b5ff91 | 648,575 |
def caseins_getattr(enum, attr):
"""Case-insensitive `getattr` for enumerated types."""
lower_attr_keys = list(map(lambda x: x.lower(), enum._fields))
attr_idx = lower_attr_keys.index(attr.lower())
orig_attr = enum._fields[attr_idx]
return getattr(enum, orig_attr) | 6c35bb7f56d0ba535ec4ca5a95b62bb8ebf94bdc | 648,576 |
import yaml
def get_configs(file="config.yaml"):
"""
Load project config file.
Parameters
----------
file: str
Filepath of config file
Returns
-------
config: dict
A loaded config file
"""
if file.endswith('.yaml') or file.endswith('.yml'):
try:
... | 688d78fea209fd57bfaf5f4b8c2b99e76921aac8 | 648,577 |
def isgoldrushlocation(location: str) -> bool:
"""
checks if the provided location is a location where a goldrush can happen.
:param location: the provided location
:return: boolean if location is in the list of locations where a goldrush can happen.
"""
goldrushlocationlist = open("commands/dat... | 8c068f376341c4b3c8c6ce06aa9c5b299408cefe | 648,578 |
def last_added_term_is_concatenation(query_list):
"""
Takes the under-construction query string and determines whether the
last added element is "and", "or", or "not"
"""
if len(query_list) <= 0:
return False
last_query_element = query_list[-1].lower()
return last_query_element in ('... | 9b115d9f4120d4172f925a7ec2fdce3f7a239b22 | 648,579 |
def separate_data(X, c1, c2):
"""Function for diving the dataset X into two separate classes.
Input arguments:
================
X : ndarray [n_rows, n_cols]
The entire dataset having 'n_rows' rows and 'n_cols' columns.
c1, c2 : ndarray [4, ]
The coordinates of the top left and botto... | 025e07df6141951b643e5367e3d5086e7b2199dd | 648,580 |
def determinant(q_form):
"""
The determinant of a tensor, given in quadratic form
Parameters
----------
q_form : ndarray
The quadratic form of a tensor, or an array with quadratic forms of
tensors. Should be of shape (x, y, z, 3, 3) or (n, 3, 3) or (3, 3).
Returns
-------
... | e69720131de7005e0e6f7aefc8d1741fc6818a8c | 648,581 |
def get_skel(s):
"""Get a tuple representing an instrution skeleton.
Args:
s: String of chars in {0, 1, x} of the skeleton
Returns:
Tuple (before, length, after), where
- before is the number before the mask
- length is the length of x's in the mask
- after is t... | c310480448e6a959cf2a68e14d19dcbadb908e18 | 648,582 |
import os
def set_model_from_extension(file_name, config):
"""Using configuration options, determine which Islandora Model value
to assign to nodes created from files. Options are either a single model
or a set of mappings from file extenstion to Islandora Model term ID.
"""
if config['task'... | de34bfa2cce57534789227a3dec6df760980ebff | 648,583 |
import numpy
def histogram_features(hist, maximum, step):
"""Extract features from a histogram, namely the mean,
max and maximum difference at certain intervals.
:param hist: a histogram representing a color channel
:type hist: numpy.ndarray
:param maximum: maximum value of the color channel
... | d5f984bbcfc48f86fde7831724ea2f2523ba19c7 | 648,585 |
import pickle
def get_game_models(fname='models/game_regressions.pkl'):
""" Load pre-trained models from pickle file """
with open(fname, 'rb') as fid:
game_models = pickle.load(fid)
return game_models | dc17f0a6dba91a15f41e283ca582606319c19adc | 648,586 |
def addcss(value, arg):
""" Adds a css class to a form field """
css_classes = value.field.widget.attrs.get('class', '').split(' ')
if css_classes and arg not in css_classes:
css_classes = '%s %s' % (css_classes, arg)
return value.as_widget(attrs={'class': css_classes}) | 9d28ab6e18e9c3fdb6de9044c95ea3c794ffa29d | 648,587 |
def find_clusters(unit_loc, index_clusters):
""" 找到某个位置在clusters中的哪个cluster
return:
cluster的下标,若未找到,返回-1
"""
if unit_loc in index_clusters:
return index_clusters[unit_loc]
return -1 | ce011f8616d97afff535e98186429f16bbfd68f4 | 648,588 |
import json
def load_conf_file(metadata_path):
"""Load the json configuration file create with the function `create_conf_file`.
:param metadata_path: path to the metadata folder
:type metadata_path: str
Example::
result = load_conf_file('/home/romain/Downloads/irsst/metadata/')
"""
json_... | 946b6d601769330de11bbf834526a82525981e18 | 648,589 |
def has_super(cls):
"""Returns True if input class `__super__` is not None.
`__super__` is defined and not None for class trees having
a main superclass and one or more inherited classes.
Parameters
----------
cls : obj
Any class or class isntance.
"""
return hasattr(cls, '__s... | b22dfd7668a4b98b78dbe1d36205e9014cb9d4de | 648,590 |
import os
import click
def get_launch_env(environment_override, environ=None):
"""Given command line arguments, build up the environment array"""
# Copy the environment to avoid modifying the original
if environ is None:
environ = os.environ.copy()
else:
environ = environ.copy()
#... | 86c1100a1905684c698a37d6ad16f51b72073f60 | 648,591 |
def _make_pretty_extended(extended):
"""
Makes the extended description pretty and returns a formatted string.
Otherwise, returns None.
"""
if extended is not None and extended.strip() != "":
extended = "\n".join(map(lambda u: u.strip(), extended.split("\n")))
return "```%s```\n\n" ... | 3d5828eb50e2aef488421122987fb2efec1494ed | 648,592 |
from typing import List
import re
def _tokenize(text: str, n_gram: int) -> List[str]:
"""Retun the list of a tokenized input text, where tokens are represented by N-grams.
Args:
text:
An input sentence.
n_gram
N-gram size to return.
"""
tokens = re.split(r"\s+"... | 4bced06b28f8eb304430568a6a9d2cd355db6f73 | 648,593 |
import base64
def get_string_encoding(image_path):
"""
Get the base64 encoding string of the given image
:param image_path: The path to the image
:returns: The base64 byte string of the image
"""
with open(image_path, 'rb') as image:
string = base64.b64encode(image.read())
s = '... | 9e8465725ce06bd71d2cf47729aab5f7915cfa21 | 648,594 |
import os
def get_mel_dirs(base_dir, db, machine_type, machine_id):
"""
Retrieves the directories where normal and abnormal mel files are stored
:param base_dir (str): path to directory where the "data" directory was or shall be created
:param db (str): noise level, takes values '6dB', '0dB' or 'min6d... | 49ad34577aaa8721ce452b619ba9d1dae76fd4e5 | 648,595 |
import distutils.version
def version_ge(version1, version2):
"""
>>> from util_cplat_packages import *
>>> version1 = distro_version
>>> version2 = '15.03'
"""
flag = distutils.version.LooseVersion(version1) >= distutils.version.LooseVersion(version2)
return flag | c8cacd79d9c3e322a6f8eb3e604bbc2f0090d5e8 | 648,596 |
def read_carry(self) -> int:
"""
Return the value of the carry flag.
Parameters
----------
self : Processor, mandatory
The instance of the processor containing the registers, accumulator etc
Returns
-------
CARRY
A 1 or a 0 (the value of the carry flag)
"""
ret... | c691c39c821e48556dcd650afc29e2151c57f00d | 648,597 |
import json
def add_metadata_to_table(table, metadata, key='my_metadata'):
"""
Add json metadata to a pyarrow.Table under a given key
Notes
-----
Based on: https://stackoverflow.com/a/58978449/709975
"""
# convert dictionary to json representation (str object),
# then convert it to a ... | c1e979a4fbf2d67b35ae4a990bf0933f2e2f7bd0 | 648,598 |
def linear_head_correction(r, V, cutoff):
"""Use a linear function to smoothly force V to a finite value at V(0). """
slope = (V[cutoff + 1] - V[cutoff + 2]) / (r[cutoff + 1] - r[cutoff + 2])
if slope > 0:
slope = -slope
V[: cutoff + 1] = slope * (r[: cutoff + 1] - r[cutoff + 1]) + V[cutoff + 1]... | 64cc9e2c05a00f909edb72d902bbdd0091a49234 | 648,599 |
def cache_string(func, param):
"""Check cache for a string prop"""
def wrapper(*args, **kwargs):
self, *rem = args
cmd = f"{self.identifier}[{self.index}].{param}"
if cmd in self._remote.cache:
return self._remote.cache.pop(cmd)
return func(*args, **kwargs)
retu... | ee2f98ab180ce22c5b2c88b1f350dccfba499029 | 648,600 |
def get_hospital_takeup(model):
"""are there free hospital beds? show big spike!"""
return model.hospital_takeup * 0.1 * model.num_agents | 483ec37d8f6407c0f2a7ef40c930d2a60f5973e0 | 648,601 |
def correl(dataset):
"""
Function that computes the correlation matrix for a given dataset.
:param dataset: Pandas dataframe
:return: Correlation matrix (Pandas Dataframe)
"""
corr_matrix = dataset.corr().abs()
return corr_matrix | 5cfcf963c9d3ffee36e420332e24dedc34230142 | 648,602 |
import os
import subprocess
def get_python_incdir(bin_dir, lib_dir):
"""Determine the python include directory.
:param str bin_dir: directory containing the python executable
"""
script = os.path.join(bin_dir, "python3")
env = dict(os.environ)
env["LD_LIBRARY_PATH"] = lib_dir
proc = subpro... | 10e1abb0d96a1db970306f93cd82024fb3a8ef6d | 648,604 |
import re
from bs4 import BeautifulSoup
def collect_test_modules(stdout):
"""
Takes the xml-ish (no, it's not actually xml so we need to format it a bit) --collect-only output as printed
by pytest to stdout and normalizes it to get a list of all collected tests in a human friendly format
:param stdout... | f5db4baa6307e638106c03dd2f7c2421d222bbe0 | 648,605 |
import argparse
def setup_argument_parser():
"""Setup argparse parser."""
help_description = """
Extract gene regions in BED format (6-col) from (Ensembl) GTF.
"""
# Define argument parser.
p = argparse.ArgumentParser(add_help=False,
prog="gtf_extract_gene_... | 7c6d188fbcb64687af21b58a8fecee7aafa93e5a | 648,607 |
def get_aggregate_stats_overlay_bandwidth_ne_pk_tunnels(
self,
ne_pk_tunnel_list: list[str],
start_time: int,
end_time: int,
granularity: str,
) -> dict:
"""Get aggregate overlay bandwidth stats data filter by query
parameters
.. list-table::
:header-rows: 1
* - Swagger... | ca884974ec8ff1c9cc75e1826800b2f6f920ac37 | 648,608 |
import os
def _read_mpdaf_obj(cls, hdulist, ext, **kwargs):
"""Read an extension from a FITS HDUList and return an MPDAF object."""
filename = hdulist.filename()
try:
obj = cls(filename=filename, hdulist=hdulist, ext=ext, **kwargs)
except Exception as e:
raise IOError('%s: Impossible t... | 89f5595ca6f68549f345aa404a34c5a974db547b | 648,609 |
def vm_location(vm_id, vms_df):
"""input: vm and a vms df
output: host string"""
return vms_df.query(f"vm_id == '{vm_id}'")['vm_host'].to_string(
index=False) | 4ba571cce63e8df32c9aed327c6c26e156845579 | 648,610 |
def transpose(matrix):
"""Returns the transpose for the given matrix"""
if not matrix:
return []
elif matrix[0] and not isinstance(matrix[0], list):
return [[elem] for elem in matrix]
return list(map(list, zip(*matrix))) | 1aaa19714c01bdeb5fca202ca7a34a22d3c9020a | 648,611 |
from typing import Counter
def count_kmers(dna, k):
"""count the kmers of length k in a string"""
kmer_count = Counter()
for i in range(len(dna)):
kmer = dna[i:(i + k)]
if len(kmer) == k:
kmer_count[kmer] += 1
return kmer_count | 9e0a745bed6bc8ee66261939e97709281db0e05d | 648,612 |
import torch
def box2corners_th(box:torch.Tensor)-> torch.Tensor:
"""convert box coordinate to corners
Args:
box (torch.Tensor): (B, N, 5) with x, y, w, h, alpha
Returns:
torch.Tensor: (B, N, 4, 2) corners
"""
B = box.size()[0]
x = box[..., 0:1]
y = box[..., 1:2]
w = bo... | 158a8970d898f869e6e514250ae10b3bb647db1c | 648,613 |
import os
def get_e2e_test_filenames_from_protractor_dir():
"""Extracts the names of the all test files in core/tests/protractor
and core/tests/protractor_desktop directory.
Returns:
list(str). An alphabetically-sorted list of of the all test files
in core/tests/protractor and core/tests/... | 83335a1fbaa2b06c21837578fecef4e8eae11e28 | 648,614 |
def swcf(fsntoa, fsntoac):
"""TOA shortwave cloud forcing """
var = fsntoa - fsntoac
var.long_name = "TOA shortwave cloud forcing"
return var | 6b9286b8df6056564afae1cba0d936b3ec9a129c | 648,615 |
import math
def pretty_size(value):
"""Convert a number of bytes into a human-readable string.
Output is 2...5 characters. Values >= 1000 always produce output in form: x.xxxU, xx.xxU, xxxU, xxxxU.
"""
exp = int(math.log(value, 1024)) if value > 0 else 0
unit = 'bkMGTPEZY'[exp]
if exp == 0:
... | 12859a04f9205ce769eb412e4982eb33999eb2e4 | 648,616 |
def strip(input_str):
"""Strip newlines and whitespace from a string."""
return str(input_str.replace('\n', '').replace(' ', '')) | aab668a9ce531e17ab38a9a6befabdb6f85ae6b2 | 648,617 |
import logging
def get_root_logger(log_file=None, log_level=logging.INFO):
"""Use `get_logger` method in mmcv to get the root logger.
The logger will be initialized if it has not been initialized. By default a
StreamHandler will be added. If `log_file` is specified, a FileHandler will
also be added. ... | d47b736481ff67b044e9a303629f0247f3c89837 | 648,618 |
from pathlib import Path
def rmlink_safe(linkpath: Path):
"""Remove the linkpath only if it is a symbolic link."""
if linkpath.is_symlink():
linkpath.unlink()
if linkpath.exists():
print(f"'{linkpath}' is not a symbolic link; it will not be replaced.")
return False
return True | c610863a8de726e3dd7c05d2307ee3e8561ccc6b | 648,619 |
import collections
def _get_infrequent_phrases(features_set, threshold_rate=0.03):
"""Get infrequent phrases on given dataset
Args:
features_set (iter): list of feature's dict
threshold_rate (float, optional): Defaults to 0.03.
Returns:
set: set of infrequent phrase features
... | 538d0354077df8e94029802f9d1c3fd570b36d39 | 648,620 |
import os
import sys
def build_spreadsheet_title(filename: str) -> str:
"""Return file name without full path and extension."""
_, tail = os.path.split(filename)
head, _ = os.path.splitext(tail)
if not head:
sys.exit(f'Failed to built title for {filename}.')
return head | 0f665ef1dc19eef6cb62e2485b744799cf448ffd | 648,621 |
def extract_csv_links(text):
"""Get a list of csv links from the download link response text"""
links = text.replace("\r", "").split("\n")
links.remove("")
return links | e512a785759b4a80d903975ab7309b892c5c22c5 | 648,622 |
import os
def find_local_config(args):
"""
If the quail.conf.yaml path is not passed we attempt to find it. We look under
the current directory and all its subdirectories and will use the first one we find.
If we cannot find one, we exit and give the user
"""
for root, dirs, files in os.walk(... | 261c7ca0e0a2f153e5a6595f47f4187a84899000 | 648,623 |
import six
import os
def absolute_location(url, location):
"""Attempts to create an absolute URL based on initial URL, and
next URL, specifically in the case of a ``Location`` header.
"""
if '://' in location:
return location
elif location.startswith('/'):
parts = six.moves.urlli... | db1bd46e31e12062cfc17d89b1d0f24a2574ade8 | 648,624 |
def str_is_empty_or_none(str_field: str) -> bool:
"""
Verifies whether a string is empty or None.
Args:
str_field (str): String to validate.
Returns:
bool: Evaluation result.
"""
return str_field is None or not str_field or str_field.isspace() | 3e1a40dff415e5968669e36df61e5a50727f91db | 648,625 |
import os
def setup_directories(config: dict) -> dict:
"""
Create directories and update configs accordingly.
Args:
config (dict): Dictionary with the configurations.
Returns:
dict: Dictionary with the updated configurations.
"""
# Create experiment directories
if not os.... | 5ba94f5a47d9f8a6888c2bfe91a94f6b7d3493b1 | 648,626 |
def residual(gr, f):
""" compute the residual """
ib = gr.ilo
ie = gr.ihi
jb = gr.jlo
je = gr.jhi
r = gr.scratch_array()
r[ib:ie+1,jb:je+1] = f[ib:ie+1,jb:je+1] - \
(gr.phi[ib-1:ie,jb:je+1] - 2.0*gr.phi[ib:ie+1,jb:je+1] + gr.phi[ib+1:ie+2,jb:je+1])/gr.dx**2 - \
(gr.phi[ib:... | bc55183c51c87faee00baed20a36c541acf16a2f | 648,628 |
def filter_clone(function, xs):
"""
Elements from xs are filtered out only for which the output of function holds True.
"""
filtered_lst = [] # We'll store our results here.
for elem in xs:
if function(elem):
filtered_lst += [elem]
return filtered_lst | da8da6967a2e6eaa446ee22331c3893cc39c0f34 | 648,629 |
def _get_unit_of_variable(df, variable, multiple_units="raise"):
"""
Get the unit of a variable in ``df``
Parameters
----------
variable : str
String to use to filter variables
multiple_units : str
If ``"raise"``, check that the variable only has one unit and raise an
`... | 6234c474c71dba70fc330f017b47a371d7613942 | 648,630 |
import stat
def calcPerms(initial, perms):
"""This compares ondisk permissions with specified ones."""
pdisp = [{1:stat.S_ISVTX, 2:stat.S_ISGID, 4:stat.S_ISUID},
{1:stat.S_IXUSR, 2:stat.S_IWUSR, 4:stat.S_IRUSR},
{1:stat.S_IXGRP, 2:stat.S_IWGRP, 4:stat.S_IRGRP},
{1:stat.S... | d97e6fc088055080e3d8191e4c590e95198313d7 | 648,631 |
def slurp(fname, binary=False):
""" fname -> str|bytes.
binary=True -- read bytes not text
"""
mode = 'rb' if binary else 'rt'
with open(fname, mode) as f:
return f.read() | 677aa38863851db78ecda6ab3b61d16e17f9fbfb | 648,632 |
def pretty_format_args(*args, **kwargs):
"""
Take the args, and kwargs that are passed them and format in a
prototype style.
"""
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args... | d3326bf2a36dc2eb002a77aec257682757f7bca5 | 648,633 |
def transform(matrix, vector):
"""
Given a matrix and a vector, return the result of transforming the vector by
the matrix.
matrix = [[0, 0, 0, 0], [0, 0, 0, 0]]
vector = [0, 0, 0, 0]
return = [0, 0]
"""
vout = []
for j in range(2):
x = 0
for i in range(4):
... | f06a467da6bf2ffaef0870693ede6ae5966a22e6 | 648,634 |
def YumGetPathToConfig(vm):
"""Returns the path to the mongodb config file."""
return '/etc/mongod.conf' | 1e7be583853d97e93efa81457edac3b548e42967 | 648,635 |
import os
def get_tmp_dirpath(input_xml_filepath):
"""Return absolute path to output_txt_dirpath/tmp/."""
return os.path.join(os.path.dirname(input_xml_filepath), 'tmp') | 84dae2ed1ad4e56456e333fb170fcdbd75c68e20 | 648,636 |
def define_stim_state(rel_time, on_time, off_time):
"""
Define stimulus state (1 = ON; 0 = OFF) based on relative stimulus time
"""
stim_state = ((rel_time > on_time) * (rel_time < off_time)).astype(int)
return stim_state | 0b447b22f7f2af627e7d4024f3bcde9eafccbb2d | 648,637 |
def check_axes(x, axes):
"""
Checks if a list of axes is valid for a tensor or ndarray.
If the input axis indices are not valid, a ValueError
will be raised. Otherwise, the axes will be processed into
a tuple of nonnegative integers
Parameters
----------
x : torch.Tensor or np.ndarray
... | 4f2528f28c612fde9d6b0410deac3ecab5291559 | 648,638 |
def send_request(client, post_data, **kwargs):
"""uses a dict to create a request on dataforSeo api
parameters:
client : Restclient object created with create_request
post_data: dict created with create_request
Optional parameters:
server: server to use for request
returns json style list"... | 973fef88a77a592c8129ad5e409430173da08d69 | 648,639 |
def psy_const_of_psychrometer(psychrometer, atmos_pres):
"""
Calculate the psychrometric constant for different types of
psychrometer at a given atmospheric pressure.
Based on FAO equation 16 in Allen et al (1998).
:param psychrometer: Integer between 1 and 3 which denotes type of
psychrom... | 0c1fe1d0b3702678cb1bc207d9e8e8537619b7d7 | 648,640 |
def set_model_parameters(params, model):
""" params - array, needs to have the same order as
model.listOfParameters """
for e, (pname, p) in enumerate(model.listOfParameters.items()):
model.get_parameter(pname).set_expression(params[e])
return model | 1a464e25036a0a75ec4d35468894b7a792d1fce0 | 648,641 |
import re
def SkipTableCheck(table, zone_data):
"""Check that this table isnt blacklisted"""
# print(zone_data['table_blacklist'])
# import sys
# sys.exit(0)
for black_item in zone_data['table_blacklist']:
black_item_regex = black_item.replace('*', '.*?')
results = re.findall(black_item_regex, ta... | db819c5e1bcc7ecb3520537ea1da9010f27c01ae | 648,642 |
def to_lowercase_all(df):
"""
This function transforms all strings in the dataframe to lowercase
Args:
df (pd.DataFrame): Raw dataframe with some text columns.
Returns:
pd.DataFrame: Dataframe with lowercase standardization.
"""
return df.applymap(lambda s: s.lower() if type(s)... | 131b10e97d2a882774b410eae7ab5b8c2c5f6946 | 648,643 |
import os
def get_datafile_path(start_loc, filename):
"""Get the path for a data file."""
return os.path.join(
os.path.dirname(os.path.abspath(start_loc)),
'data',
filename) | a6b92c2e9adb6e30fa40aaf60a39c5cbeab9e75a | 648,644 |
def hard_most_common_letter(a):
"""Takes in a string of lowercase letters and returns the most common letter (if multiple, just pick one)."""
# too tricky?
d = {}
for c in a:
d[c] = d.get(c, 0) + 1
l = list(d.items())
l.sort(key=lambda x: -x[1])
return l[0][0] | ca5fc20d08dc9fe38e2d721e7e3557bdf92a51f6 | 648,645 |
def empty_v(coord_set, origin, top_idx, bot_idx):
"""Makes sure no conflicts occur when a word is placed vertically.
The parameters and return values are similar to the function, empty_h()
"""
# print(origin)
left = origin[0] - 1
right = origin[0] + 1
ex = origin[1]
for idx in range(top_... | 904e4c278ee66af4266ce7cc087083e0bc31255d | 648,646 |
import os
import json
def prepare_options(hypes_path, options):
"""Sets parameters of the prediction process.
Args:
hypes_path (string): The path to model hyperparameters file.
options (dict): The command line options to set before start predictions.
Returns (dict):
The model hyp... | a7751f0ae6848c263dd209a2897f058eec4e26ac | 648,647 |
def export_dot(graphe):
"""Renvoie une chaîne encodant le graphe au format dot."""
string = "digraph graphe { "
sommets = "\n"
for sommet in graphe.sommets() :
sommets += "\t" + str(sommet) + ";\n"
arcs = ""
for u, v in graphe.arcs() :
arcs += "\t" + str(u) + " -> " + str(v)... | f53fa2fba33313959c3d2b857b5fbaab06a7483a | 648,648 |
def decompose_tokenized_text(token_list):
"""
Split the output of BERT tokenizer into word_list and tag_list
"""
# The initial tag is 'O'
tag = 'O'
word_list = []
tag_list = []
# A flag to indicate if it is in the entity now
# 0 means out, 1 means start, 2 means in the middle
i... | efce106b78a72f3c3151a144b77cdbdab21ac78f | 648,649 |
import inspect
def checkstack(the_string):
"""checks for pytex"""
thestack = []
for bit in inspect.stack():
for b in bit:
thestack.append(str(b))
as_string = ' '.join(thestack)
return as_string.lower().count(the_string) > 1 | afb0bd7cae9e16d4c84d3e39e5f23b35c4b329f2 | 648,650 |
def matrix2cube(data_matrix, im_shape):
"""Matrix to Cube.
This method transforms a 2D matrix to a 3D cube.
Parameters
----------
data_matrix : numpy.ndarray
Input data cube, 2D array
im_shape : tuple
2D shape of the individual images
Returns
-------
numpy.ndarray
... | 78e6daa5c983d2e36e483baadfbf7d8a9de1290e | 648,651 |
def __fallback_next(*args):
"""next_(iterator[, default])
Return the next item from the iterator. If default is given and
the iterator is exhausted, it is returned instead of
raising StopIteration."""
args_len = len(args)
if (args_len < 1):
raise TypeError(f"expected at least 1 a... | 2d1ad97bed1b8468b8acf0bcafa8fd6c38265cb4 | 648,652 |
def bytes_data():
"""
Return a bytes object
"""
return bytes(range(256)) | 9d11c8da907951b46cf76df70427da708cf5d3b8 | 648,653 |
import math
def temperature_range(n, cut):
"""
Define the range of allowed temperature
for given image size and cut.
"""
if isinstance(cut, (float, int)):
log = math.log(cut)
else:
log = cut.log()
T1 = 1 / (math.pi * n ** 2 * log)
T2 = 4 / (math.pi ** 3 * cut ** 2 * log... | 8701d2fb9503e82f31079b009cea4c89e7277e60 | 648,654 |
def test_gcd():
"""
Given a list of numbers,
find GCD
"""
def gcd(ns):
if len(ns)==2:
return gcd2(ns[0], ns[1])
else:
a,b = ns[:2]
return gcd([gcd2(a,b)] + ns[2:])
def gcd2(a,b):
# Euclidean algorithm
if a==b:
return a
elif a<b:
a,b = b,a
while b != 0:... | 1e00b95fd0ec763fe18b4b50ffeabef48fc197a7 | 648,655 |
import math
def headerFunkyDouble2String( d ) :
"""For internal use only."""
nines = 9.999 # Must be less than 15 nines otherwise log10 may not return as excepted.
maxValue, abs_d = nines * 1e10, abs( d )
if( d < 0 ) : maxValue /= 10
if( 1e-2 < abs_d < maxValue ) :
p... | 018946976b398f63ce35b70a22e61c7cec67af42 | 648,656 |
def get_score(outcome, score):
""" determines the new score based on the outcome """
if outcome == 1:
return (score[0]+1, score[1], score[2])
elif outcome == 0:
return (score[0], score[1]+1, score[2])
else:
return (score[0], score[1], score[2]+1) | ccc7d70f5a66ae8510c29d931bfe5338fb3ec03c | 648,657 |
from typing import Dict
def getLetters(string: str) -> Dict[str, int]:
"""Gets the letters of string and puts their occurences in a dictionary"""
letters: Dict[str, int] = {}
for letter in string:
letters[letter] = letters.get(letter, 0) + 1
return letters | 8a20cbc64baff825ad43874c96ca6ecd7f2e9231 | 648,658 |
import html
def html2unicode(code):
""" Converts HTML entities to unicode ('&' => '&') """
return html.unescape(code) | 1fc1ba02d47891320c087a7635327968bfe4f87c | 648,659 |
from datetime import datetime
def validate_datetime(datetime_text, datetime_format="%Y-%m-%d %H:%M:%S"):
"""
检查是否有效日期字符串
"""
try:
datetime.strptime(datetime_text, datetime_format)
return True
except ValueError:
return False | f5845c6eff517217dc57c6939b6f108b29c76a0a | 648,660 |
import re
def x7s_wireDirectionLengthClustering(pj):
""" Clusters the PJ based on the direction and length of the wire.
Examples:
NN2BEG1 -> NN2
SW6END3 -> SW6
"""
s = pj.name
if s.startswith("LV") or s.startswith("LH"):
return s
match = re.search(r"([A-Z... | 50ef18b876db850d027afc3fce2972d0c94d8225 | 648,661 |
def should_send_event(socket, annotation, event_data):
"""
Inspects the passed annotation and action and decides whether or not
the underlying session should receive the event. If it should, the
action is wrapped up in a websocket packet and sent to the client.
"""
if socket.terminated:
... | eb4458f58ad83ddb8de3716ee540e4fe2638d420 | 648,662 |
from typing import List
def parse(text: str) -> List[str]:
"""
Parse a textual arguments into a list of strings in Unix style.
This function currently supports:
* Splitting arguments by spaces, cleaning up redundant spaces
* String literals using single and double quotes
:param text:... | e999023c8249c74216ee3b030828dd8d5a266477 | 648,663 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.