content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_work_subdirs(subdirs: List[str]):
"""Create |subdirs| in work directory."""
for subdir in subdirs:
os.mkdir(os.path.join(experiment_utils.get_work_dir(), subdir)) | 18,800 |
def test_from_rsid(rsids, start_rsid):
"""Continue collecting publications for rsids in list, beginning with start_rsid
Args:
rsids (list): list of rsids to collect publications on
start_rsid (str): rsid identifier to resume collecting publications on
Returns:
runtime_rsids (list):... | 18,801 |
def _average_scada(times, values, nvalues):
"""
Function which down samples scada values.
:param times: Unix times of the data points.
:param values: Corresponding sensor value
:param nvalues: Number of samples we average over.
:return: new time values and
"""
if len(times) % nvalues:
... | 18,802 |
def main():
"""
Test harness
"""
def game_factory():
"""
Creates the game we need
"""
return Maze(Layout.from_string(Layout.MEDIUM_STR))
bot_factory = PlannedBot
trainer = BotTrainer(game_factory, bot_factory, 16, 2, goal_score=13)
start_time = time()
gen... | 18,803 |
def behavior_of(classname):
"""
Finds and loads the behavior class for C++ (decoded) classname or returns
None if there isn't one.
Behaviors do not have a required base class, and they may be used with
Awkward Array's ``ak.behavior``.
The search strategy for finding behavior classes is:
1... | 18,804 |
def test_feed_from_annotations_with_3_annotations():
"""If there are 3 annotations it should return 3 entries."""
annotations = [factories.Annotation(), factories.Annotation(),
factories.Annotation()]
feed = rss.feed_from_annotations(
annotations, _annotation_url(), mock.Mock(), ... | 18,805 |
def _abs_user_path(fpath):
"""don't overload the ap type"""
return os.path.abspath(os.path.expanduser(fpath)) | 18,806 |
def save_tmp(config):
"""Save the configuration to a temp file.
The global state of ReachMaster is tracked with a temp
file. Whenever a child window of the main application is
created or destroyed, the temp file is updated to reflect
whatever changes in settings may have occurred. If the
user ... | 18,807 |
def adjust(data):
"""Calculate mean of list of values and subtract the mean of every element
in the list, making a new list.
Returns tuple of mean, list of adjusted values
"""
mu = mean(data)
return mu, map(lambda x: (x-mu), data) | 18,808 |
def clear():
"""
Clears the world, and then returns the cleared representation
"""
myWorld.clear()
return jsonify(myWorld.world()) | 18,809 |
def handle_evap_mode(j,brivis_status):
"""Parse evap part of JSON."""
# pylint: disable=too-many-branches,too-many-statements
cfg = get_attribute(j[1].get("ECOM"),"CFG",None)
if not cfg:
# Probably an error
_LOGGER.error("No CFG - Not happy, Jan")
else:
if y_n_to_bool(get_a... | 18,810 |
def _create_terminal_writer_factory(output: Optional[TextIO]):
"""
A factory method for creating a `create_terminal_writer` function.
:param output: The receiver of all original pytest output.
"""
def _create_terminal_writer(config: Config, _file: Optional[TextIO] = None) -> TerminalWriter:
... | 18,811 |
def filter(
f: typing.Callable,
stage: Stage = pypeln_utils.UNDEFINED,
workers: int = 1,
maxsize: int = 0,
timeout: float = 0,
on_start: typing.Callable = None,
on_done: typing.Callable = None,
) -> Stage:
"""
Creates a stage that filter the data given a predicate function `f`. exact... | 18,812 |
def function_factory(model, loss, dataset):
"""A factory to create a function required by tfp.optimizer.lbfgs_minimize.
Args:
model [in]: an instance of `tf.keras.Model` or its subclasses.
loss [in]: a function with signature loss_value = loss(pred_y, true_y).
train_x [in]: the input pa... | 18,813 |
def main():
"""Main script function.
"""
# arguments
parser = ArgumentParser(
prog='multi-ear-uart',
description=('Sensorboard serial readout with data storage'
'in a local influx database.'),
)
parser.add_argument(
'-i', '--ini', metavar='..', type=... | 18,814 |
def nn_CPRAND(tensor,rank,n_samples,n_samples_err,factors=None,exact_err=False,it_max=100,err_it_max=20,tol=1e-7,list_factors=False,time_rec=False):
"""
Add argument n_samples_err
CPRAND for CP-decomposition in non negative case, with err_rand
return also exact error
Parameters
----------
ten... | 18,815 |
def parametrize_application_yml(argvalues, ids):
"""
Define parameters for testable application definition.
Args:
argvalues (list): Parametrize args values
ids (list): Parametrize ID
"""
from accelpy._application import Application
with scandir(dirname(realpath(__file__))) as e... | 18,816 |
def get_base_url(host_name, customer_id):
"""
:arg host_name: the host name of the IDNow gateway server
:arg customer_id: your customer id
:returns the base url of the IDNow API and the selected customer
"""
return 'https://{0}/api/v1/{1}'.format(host_name, customer_id) | 18,817 |
def sample_category(user, **params):
"""Create and return a sample category"""
defaults = {
'name': 'Sample category',
'persian_title': 'persian',
'parent_category': None
}
defaults.update(params)
return Category.objects.create(user=user, **defaults) | 18,818 |
def lindbladian_average_infid_set(
propagators: dict, instructions: Dict[str, Instruction], index, dims, n_eval
):
"""
Mean average fidelity over all gates in propagators.
Parameters
----------
propagators : dict
Contains unitary representations of the gates, identified by a key.
in... | 18,819 |
def edit(request, course_id):
"""
Teacher form for editing a course
"""
course = get_object_or_404(Course, id=course_id)
courseForm = CourseForm(request.POST or None, instance=course)
if request.method == 'POST': # Form was submitted
if courseForm.is_valid():
courseForm.sa... | 18,820 |
def _build_ontology_embedded_list():
""" Helper function intended to be used to create the embedded list for ontology.
All types should implement a function like this going forward.
"""
synonym_terms_embed = DependencyEmbedder.embed_defaults_for_type(base_path='synonym_terms',
... | 18,821 |
def remap_expn_sample_names(expn):
"""
Super-specific method to remap the sample names.
"""
names = expn.getConditionNames()
new_names = []
for n in names:
if n in sample_description:
new_names.append(sample_description[n])
else:
new_names.append('?%s' % n... | 18,822 |
def interp1d(x,y,xi,axis=None,extrap=True):
"""
Args:
x (uniformly sampled vector/array): sampled x values
y (array): sampled y values
xi (array): x values to interpolate onto
axis (int): axis along which to interpolate.
extrap (bool): if True, use linear extrapolation ba... | 18,823 |
def _back_operate(
servicer, callback, work_pool, transmission_pool, utility_pool,
termination_action, ticket, default_timeout, maximum_timeout):
"""Constructs objects necessary for back-side operation management.
Also begins back-side operation by feeding the first received ticket into the
constructed _... | 18,824 |
def runICA(fslDir, inFile, outDir, melDirIn, mask, dim, TR, seed=None):
""" This function runs MELODIC and merges the mixture modeled thresholded ICs into a single 4D nifti file
Parameters
---------------------------------------------------------------------------------
fslDir: Full path of the bin-directory of F... | 18,825 |
def load_train_val_data(
data_dir: str, batch_size: int,
training_fraction: float) -> Tuple[DataLoader, DataLoader]:
"""
Returns two DataLoader objects that wrap training and validation data.
Training and validation data are extracted from the full original training
data, split according... | 18,826 |
def match(input_string, start_node):
"""匹配字符串
input_string :: 需要配备的字符串
start_node :: NFA起始节点
return :: True | False
"""
# 初始化运行状态的状态集合: 起始节点+空转移能到达的节点
current_state_set = [start_node]
next_state_set = closure(current_state_set)
# 循环读入字符生成状态集合
for i, ch in enumerate(inp... | 18,827 |
def _H_to_h(H):
"""Converts CIECAM02/CAM02-UCS hue composition (H) to raw hue angle (h)."""
x0 = H % 400 * 360 / 400
h, _, _ = fmin_l_bfgs_b(lambda x: abs(h_to_H(x) - H), x0, approx_grad=True)
return h % 360 | 18,828 |
def filter_df_merge(cpu_df, filter_column=None):
"""
process cpu data frame, merge by 'model_name', 'batch_size'
Args:
cpu_df ([type]): [description]
"""
if not filter_column:
raise Exception(
"please assign filter_column for filter_df_merge function")
df_lists = []
... | 18,829 |
def MRP2Euler121(q):
"""
MRP2Euler121(Q)
E = MRP2Euler121(Q) translates the MRP
vector Q into the (1-2-1) euler angle vector E.
"""
return EP2Euler121(MRP2EP(q)) | 18,830 |
def nlayer(depth=64):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = NLayer_D(depth=depth)
return model | 18,831 |
def get_dataset(config):
"""Downloads the dataset if it is not yet available and unzips it"""
datasets = {
"CVE-2014-0160": "https://www.exploids.de/lid-ds-downloads/LID-DS-Recordings-01/CVE-2014-0160.tar.gz",
"PHP_CWE-434": "https://www.exploids.de/lid-ds-downloads/LID-DS-Recordings-01/PHP_CWE... | 18,832 |
def deserialize(
value: ElementTree.Element,
cipher: PSCryptoProvider,
**kwargs: typing.Any,
) -> typing.Optional[typing.Union[bool, PSObject]]:
"""Deserialize CLIXML to a Python object.
Deserializes a CLIXML XML Element from .NET to a Python object.
Args:
value: The CLIXML XML Element... | 18,833 |
def is_url_ok(url: str) -> bool:
"""Check if the given URL is down."""
try:
r = requests.get(url)
return r.status_code == 200
except Exception:
return False | 18,834 |
def calculate_pair_energy_np(coordinates, i_particle, box_length, cutoff):
"""
Calculate interaction energy of particle w/ its environment (all other particles in sys)
Parameters
----------------
coordinates : list
the coordinates for all particles in sys
i_particle : int
pa... | 18,835 |
def lwhere(mappings, **cond):
"""Selects mappings containing all pairs in cond."""
return list(where(mappings, **cond)) | 18,836 |
def get_number(message, limit=4):
"""
convert Chinese to pinyin and extract useful numbers
attention:
1. only for integer
2. before apply this method, the message should be preprocessed
input:
message: the message you want to extract numbers from.
limit: limit the lengt... | 18,837 |
def get_db_connection(path, timeout=30, okay_to_create=False):
"""
Returns a properly configured SQLite database connection.
:param path: path to DB
:param timeout: timeout for connection
:param okay_to_create: if True, create the DB if it doesn't exist
:returns: DB connection object
"""
... | 18,838 |
def calc_merkle_root(trie: Trie):
"""private method that builds the merkle-trie and calculates root_hash"""
txs = trie.transactions.copy()
# if there is only one tx the trie is not valid, hence we need to add an
# empty root
if len(txs) == 1:
txs.append(stringutil.empty_root)
# do until... | 18,839 |
def create_connection(db_file):
"""
Creates a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print... | 18,840 |
def convex_hull(poly):
"""
ratio of the convex hull area to the area of the shape itself
Altman's A_3 measure, from Neimi et al 1991.
"""
chull = to_shapely_geom(poly).convex_hull
return poly.area / chull.area | 18,841 |
def create_scifact_annotations(
claims, corpus, tokenizer, class_to_id: Dict[str, int], neutral_class: str
) -> List[SciFactAnnotation]:
"""Create a SciFactAnnotation for each claim - evidence/cited document pair."""
def get_abstract_and_encoding(
doc_id,
) -> Tuple[List[List[str]], List[torch.... | 18,842 |
def predict_test_results(Test_data, Results_path, cph, col_names,SN=1,penalizer=[],
var_thresh=[],CI=[]):
"""
:param Test_file_path:
:param Results_path:
:param cph:
:param col_names:
:param SN:
:param penalizer:
:param var_thresh:
:return: Tot_test_pred, Y_... | 18,843 |
def epsilon(tagfile):
"""Compute the total epsilon factor for each event
Compute the flatfield correction from the P-flat and L-flat reference files
(PFLTFILE and LFLTFILE respectively).
Parameters
----------
tagfile, str
input STIS time-tag data file
Returns
-------
epsil... | 18,844 |
def contact(update: Update, context: CallbackContext) -> None:
""" /contact command """
update.message.reply_text(
static_text.contact_command,
parse_mode=ParseMode.HTML,
disable_web_page_preview=True,
) | 18,845 |
async def test_no_scopes():
"""The credential should raise ValueError when get_token is called with no scopes"""
credential = VSCodeCredential()
with pytest.raises(ValueError):
await credential.get_token() | 18,846 |
def sort_by_value(front, values):
"""
This function sorts the front list according to the values
:param front: List of indexes of elements in the value
:param values: List of values. Can be longer than the front list
:return:
"""
copied_values = values.copy() # Copy so we can modify it
sorted_list = []
... | 18,847 |
def save_exposure(fitstbl, frame, spectrograph, science_path, par, caliBrate, all_spec2d, all_specobjs):
"""
Save the outputs from extraction for a given exposure
Args:
frame (:obj:`int`):
0-indexed row in the metadata table with the frame
that has been reduced.
all_... | 18,848 |
def test_day_detail_view(init_feasible_db, client):
"""Test day detail view."""
client.login(username="temporary", password="temporary")
day = Day.objects.get(number=1)
response = client.get(reverse("day_detail", kwargs={"pk": day.id}))
assert response.status_code == 200
assert "Day: 1" in respo... | 18,849 |
def get_cell_area(self, indices=[]):
"""Return the area of the cells on the outer surface.
Parameters
----------
self : MeshVTK
a MeshVTK object
indices : list
list of the points to extract (optional)
Returns
-------
areas: ndarray
Area of the cells
"""
... | 18,850 |
def _to_dataarray(origins, sources, values):
""" Converts grid_search inputs to DataArray
"""
origin_dims = ('origin_idx',)
origin_coords = [np.arange(len(origins))]
origin_shape = (len(origins),)
source_dims = sources.dims
source_coords = sources.coords
source_shape = sources.shape
... | 18,851 |
def package(metadata: Metadata, requirements: Optional[List[str]] = None, path: Optional[str] = None):
"""Packages the chatbot into a single archive for deployment.
Performs some preliminary checks on the metadata.
Creates a _package.zip file in the directory containing the file that contains the bot class... | 18,852 |
def warp_grid(grid: tf.Tensor, theta: tf.Tensor) -> tf.Tensor:
"""
Perform transformation on the grid.
- grid_padded[i,j,k,:] = [i j k 1]
- grid_warped[b,i,j,k,p] = sum_over_q (grid_padded[i,j,k,q] * theta[b,q,p])
:param grid: shape = (dim1, dim2, dim3, 3), grid[i,j,k,:] = [i j k]
:param theta... | 18,853 |
def droid_visualization(video, device="cuda:0"):
""" DROID visualization frontend """
torch.cuda.set_device(device)
droid_visualization.video = video
droid_visualization.cameras = {}
droid_visualization.points = {}
droid_visualization.warmup = 8
droid_visualization.scale = 1.0
droid_vis... | 18,854 |
async def makenotifyrole(guild):
"""Make the notify role in the given guild.
:type guild: discord.Guild
:rtype: None | discord.Role
:param guild: Guild instance to create the role in.
:return: The created role, possibly None if the creation failed.
"""
userrole = None
try:
# The... | 18,855 |
def mape(forecast: Forecast, target: Target) -> np.ndarray:
"""
Calculate MAPE.
This method accepts one or many timeseries.
For multiple timeseries pass matrix (N, M) where N is number of timeseries and M is number of time steps.
:param forecast: Predicted values.
:param target: Target values.
... | 18,856 |
def reverse_weighted_graph(graph):
"""
Function for reverting direction of the graph (weights still the same)
Args:
graph: graph representation as Example: {1: {2: 1, 3: 5}, 2: {3: 2}, 4: {1: 2}}
Returns:
reversed graph
Examples:
>>> reverse_weighted_graph({1: {2: 1, 3: 5}... | 18,857 |
def set_logger(log_path, level=logging.INFO, console=True):
"""Sets the logger to log info in terminal and file `log_path`.
In general, it is useful to have a logger so that every output to the terminal is saved
in a permanent file. Here we save it to `model_dir/train.log`.
Example:
```
loggin... | 18,858 |
def test_asset_file_meta_source():
"""Test ht.inline.api.asset_file_meta_source."""
target = "Scanned Asset Library Directories"
path = hou.text.expandString("$HH/otls/OPlibSop.hda")
assert ht.inline.api.asset_file_meta_source(path) == target
assert ht.inline.api.asset_file_meta_source("/some/fak... | 18,859 |
def make_output_dir(out_filename):
"""
Makes the directory to output the file to if it doesn't exist.
"""
# check if output is to cwd, or is a path
dirname = os.path.dirname(out_filename)
if dirname != '' and not os.path.exists(dirname):
try:
os.makedirs(os.path.dirname(out_... | 18,860 |
def clean_bin():
"""permanently deletes entries - crud delete"""
mongo.db.bin.remove()
mongo.db.bin.insert({'_id': ObjectId()})
return redirect(url_for('get_bin', data_requested="teams")) | 18,861 |
def correct_by_threshold(img, threshold):
"""
correct the fMRI RSA results by threshold
Parameters
----------
img : array
A 3-D array of the fMRI RSA results.
The shape of img should be [nx, ny, nz]. nx, ny, nz represent the shape of the fMRI-img.
threshold : int
The nu... | 18,862 |
def config_date(dut, date):
"""
:param dut:
:param date:
:return:
"""
st.log("config date")
command = "date --set='{}'".format(date)
st.config(dut, command)
return True | 18,863 |
def test_verify_email(
api_rf, email_confirmation_factory, email_factory, user_factory
):
"""
Sending a POST request with valid data to the endpoint should mark
the associated email address as verified.
"""
user = user_factory(password="password")
email = email_factory(user=user)
confirm... | 18,864 |
def read_dicom():
"""Read in DICOM series"""
dicomPath = join(expanduser('~'), 'Documents', 'SlicerDICOMDatabase',
'TCIALocal', '0', 'images', '')
reader = sitk.ImageSeriesReader()
seriesIDread = reader.GetGDCMSeriesIDs(dicomPath)[1]
dicomFilenames = reader.GetGDCMSeriesFileNam... | 18,865 |
def test_7():
"""
Detect the date columns in austin_weather.csv
Here 2 date columns are present with different formats.
"""
table = pandas.read_csv('data_for_tests/table_7.csv')
result = date_detection.detect(table)
print(result)
expected_result = '''{'date': {'type': <ColumnTypes.CONSIN... | 18,866 |
def read_file(*file_paths):
"""Read text file."""
with codecs.open(os.path.join(ROOT_DIR, *file_paths), 'r') as fp:
return fp.read() | 18,867 |
def load_config():
"""Load the config file and validate contents."""
filename = os.path.join(user_config_dir("timetagger_cli"), config_fname)
if not os.path.isfile(filename):
raise RuntimeError("Config not set, run 'timetagger setup' first.")
with open(filename, "rb") as f:
config = tom... | 18,868 |
def zfs_upgrade_list(supported: bool = False) -> str:
"""
zfs upgrade [-v]
Displays a list of file systems that are not the most recent version.
-v Displays ZFS filesystem versions supported by the current
software. The current ZFS filesystem version and all previous
supported ve... | 18,869 |
def main():
"""
CLI Interface for developing civ plugins
"""
pass | 18,870 |
def L_model_backward(AL, Y, caches):
"""
完成L层神经网络模型后向传播计算
Arguments:
AL -- 模型输出值
Y -- 真实值
caches -- 包含Relu和Sigmoid激活函数的linear_activation_forward()中每一个cache
Returns:
grads -- 包含所有梯度的字典
grads["dA" + str(l)] = ...
grads["dW" + str(l)] = ...
grads["db... | 18,871 |
def findbps(reads, output, bowtie_options, motif, length, threshold, strand):
"""
Input:
reads: str of name of file where single-end, stranded
RNA-seq reads in fastq format are located
output:str of desired basename of output files
bowtie_options: str of bowtie options you wish to
... | 18,872 |
def Cnot(idx0: int = 0, idx1: int = 1) -> Operator:
"""Controlled Not between idx0 and idx1, controlled by |1>."""
return ControlledU(idx0, idx1, PauliX()) | 18,873 |
def test_get_df_database_input_value():
""" Check input value"""
try:
data_compile.get_df_database(1)
raise Exception()
except ValueError:
pass | 18,874 |
def init_sql_references(conn):
"""
Utility function to get references from SQL.
The returned objects conveniently identify users based on kb_name or user hashkey
"""
# get kb_names to kb_id
kb_ref = pds.read_sql("""SELECT id, kb_name, directory_id FROM dbo.kb_raw""", conn)
get_kb_dir_id = ... | 18,875 |
def inoptimal_truncation_square_root(A, B, C, k, check_stability=False):
"""Use scipy to perform balanced truncation
Use scipy to perform balanced truncation on a linear state-space system.
This method is the natural application of scipy and inoptimal performance
wise compared to `truncation_square_roo... | 18,876 |
def _tessellate_bed(chrom: str, chromStart: int, chromEnd: int, window_size: int) -> pd.DataFrame:
"""Return tessellated pandas dataframe splitting given window.
Parameters
-----------------------
chrom: str,
Chromosome containing given window.
chromStart: int,
Position where the wi... | 18,877 |
def _replace_variables(dictionary):
"""Replace environment variables in a nested dict."""
for path in _walk(dictionary):
value = path.pop()
if isinstance(value, str) and _ispath(value):
value = os.path.expandvars(value)
value = pathlib.Path(value)
last_key = path.pop()
sub_dict = diction... | 18,878 |
def compute_locksroot(locks: PendingLocksState) -> Locksroot:
"""Compute the hash representing all pending locks
The hash is submitted in TokenNetwork.settleChannel() call.
"""
return Locksroot(keccak(b"".join(locks.locks))) | 18,879 |
def refresh_interface(self):
"""
Refresh the Frelatage CLI
"""
# Title
title = "Frelatage {version} ({function_name})".format(
version=__version__, function_name=self.method.__name__
).center(105)
# Execs per second
current_second = int(time.time())
if current_second != self... | 18,880 |
def flatten(text: Union[str, List[str]], separator: str = None) -> str:
"""
Flattens the text item to a string. If the input is a string, that
same string is returned. Otherwise, the text is joined together with
the separator.
Parameters
----------
text : Union[str, List[str]]
The t... | 18,881 |
def convert_byte32_arr_to_hex_arr(byte32_arr):
"""
This function takes in an array of byte32 strings and
returns an array of hex strings.
Parameters:
byte32_arr Strings to convert from a byte32 array to a hex array
"""
hex_ids = []
for byte32_str in byte32_arr:
hex_ids... | 18,882 |
def process_ring(cat, ref, pairs, ringpairs, area, radius, sigma, sigma_init=None, gamma=None, niter=10, nextr=100, mid=True,
printprogress=True, printerror=False):
"""
Estimate omega with robust algorithm in rings. Obtain optimal estimate from best ring.
Internal function to process pairs that are ... | 18,883 |
def backtest_loop(
start_time: Union[pd.Timestamp, str],
end_time: Union[pd.Timestamp, str],
trade_strategy: BaseStrategy,
trade_executor: BaseExecutor,
) -> Tuple[PortfolioMetrics, Indicator]:
"""backtest function for the interaction of the outermost strategy and executor in the nested decision exe... | 18,884 |
def test_assert_sets_equal(test_case: SetsEqualTestCase):
"""
GraphHelper.sets_equals and related functions work correctly in both
positive and negative cases.
"""
lhs_graph: Graph = Graph().parse(data=test_case.lhs, format=test_case.lhs_format)
rhs_graph: Graph = Graph().parse(data=test_case.rh... | 18,885 |
def failOnNonTransient(func):
"""Only allow function execution when immutable is transient."""
@functools.wraps(func)
def wrapper(inst, *args, **kwargs):
# make the call fail if the object is not transient
if inst.__im_state__ != interfaces.IM_STATE_TRANSIENT:
raise AttributeErr... | 18,886 |
def text_has_emoji(text):
"""判断文本中是否包含emoji"""
for character in text:
if character in emoji.UNICODE_EMOJI:
return True
return False | 18,887 |
def rod_faces(n1, n2, xform, dim1, dim2): # validated
"""
defines points in a circle with triangle based end caps
"""
# 4,8,12,16,... becomes 5,9,13,17,...
thetas = np.radians(np.linspace(0., 360., 17))
ntheta = len(thetas)
nfaces = 0
all_faces = []
points_list = []
x = np.zeros... | 18,888 |
def xfork():
""" xfork() is similar to fork but doesn't throw an OSError exception.
Returns -1 on error, otherwise it returns the same value as fork() does.
"""
try:
ret = fork()
except OSError:
ret = -1
return ret | 18,889 |
def cigar_segment_bounds(cigar, start):
"""
Determine the start and end positions on a chromosome of a non-no-matching part of an
RNA-seq read based on a read's cigar string.
cigar string meaning: http://bioinformatics.cvr.ac.uk/blog/tag/cigar-string/
Example:
'50M25N50M' with start = 100 ... | 18,890 |
def augument(data_dir, img_path, steering_angle, range_x=100, range_y=10):
"""
Generate an augumented image and adjust steering angle.
(The steering angle is associated with the image)
"""
image, steering_angle = choose_image(data_dir, img_path, steering_angle)
image, steering_angle = random_fli... | 18,891 |
def ldns_buffer_limit(*args):
"""LDNS buffer."""
return _ldns.ldns_buffer_limit(*args) | 18,892 |
def language():
"""
Loads languages.
:return: None
"""
if os.path.isfile(omw_db):
omw_connection = sqlite3.connect(omw_db)
cursor = omw_connection.cursor()
known = dict()
cursor.execute("""SELECT id, iso639 from lang""")
for (lid, l3) in cursor:
... | 18,893 |
def test_data_folder():
"""
This fixture returns path to folder with shared test resources among all tests
"""
data_dir = os.path.join(script_dir, "testdata")
if not os.path.exists(data_dir):
os.mkdir(data_dir)
files_to_download = ["https://raw.githubusercontent.com/opencv/opencv/4.... | 18,894 |
def _call_godot(environment, source, arguments, target):
"""Runs the Godot executable with the specified command line arguments
@param environment Environment in which the Godot executable will be run
@param source Input files that will be involved
@param arguments Arguments that will be p... | 18,895 |
def random_seeded(func):
""" Decorator that uses the `random_seed` parameter from functions to seed the RNG. """
@wraps(func)
def wrapper(*args, random_seed: int = None, **kwargs):
_RNG.seed(random_seed)
return func(*args, **kwargs)
return wrapper | 18,896 |
def getCRS(station_name=None, crs=None, autoCreate=True):
"""
Method to get CRS code for the give station name. This method may not
scale nicely for a production environment. Use a proper DB instead.
@param station_name: Some characters for the station name.
@param crs: CRS code if known
@p... | 18,897 |
def _initialize_object_from_dict(object_dict, parent=None):
"""Initialize a python object from dict."""
provider = object_dict['provider']
args = object_dict.get('args') or []
kwargs = object_dict.get('kwargs') or {}
obj = _get_object_by_referance(provider)
if parent is not None:
kwarg... | 18,898 |
def from_hdf(in_path, index=None, keypoints=True, descriptors=True):
"""
For a given node, load the keypoints and descriptors from a hdf5 file. The
keypoints and descriptors kwargs support returning only keypoints or descriptors.
The index kwarg supports returning a subset of the data.
Parameters
... | 18,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.