content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_example(script, monkeypatch):
"""Run all examples to make sure they don't crash."""
# Keep matplotlib from showing figures
monkeypatch.setattr(plt, 'show', lambda: None)
runpy.run_path(script) | 79,300 |
def compare_gaussian_classifiers():
"""
Fit both Gaussian Naive Bayes and LDA classifiers on both gaussians1 and gaussians2 datasets
"""
for f in ["gaussian1.npy", "gaussian2.npy"]:
# Load dataset
X, y = load_dataset(f)
# Fit models and predict over training set
lda = LD... | 79,301 |
def version(client: BaseClient):
"""versionを表示する"""
user = client.get_send_user_name()
logger.debug("%s called 'hato version'", user)
str_ver = "バージョン情報\n```" \
f"Version {conf.VERSION}"
if conf.GIT_COMMIT_HASH:
str_ver += f" (Commit {conf.GIT_COMMIT_HASH[:7]})"
else:
... | 79,302 |
def mp3_get_file_info(filename: str) -> SoundFileInfo:
"""Fetch some information about the audio file (mp3 format)."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("drmp3 *") as mp3:
if not lib.drmp3_init_file(mp3, filenamebytes, ffi.NULL):
raise DecodeError("could not open... | 79,303 |
def generate_test_data(
method: constants.Method,
num_rows=1,
remove_merchant_id=False
) -> Tuple[List[bigquery.Row], constants.Batch, constants.BatchIdToItemId, Dict[
str, Any]]:
"""Generates a tuple containing a triplet of matching row, batch, response.
Args:
method: The API method for this b... | 79,304 |
def enumerate_space(extent):
"""Enumerate all the points in a space with the given extent. Use this
function to ensure spaces are always enumerated in the same order.
"""
return itertools.imap(np.asarray, itertools.product(*map(xrange, extent))) | 79,305 |
def _get_argparser():
"""to organize and clean format argparser args"""
parser = argparse.ArgumentParser()
parser.add_argument(
'arg-1',
help='desc'
)
parser.add_argument(
"--optional-arg-1",
action="store",
dest="optional_arg_1",
default="defaul... | 79,306 |
def file_resource(
path: Path | str,
value_type: type = Stream,
compress: Any = None,
writeable: bool = False,
publish: bool = True,
policies: Iterable[Policy] | None = None,
) -> type:
"""
Return a new resource that manages a file.
Parameters:
• path: path of file
• value_t... | 79,307 |
def test_healpix_binning(tmp_path):
"""Test healpix binning functionality."""
plt.rcParams.update(plt.rcParamsDefault)
np.random.seed(1234)
ra = np.random.uniform(low=30.0, high=40.0, size=10000)
dec = np.random.uniform(low=45.0, high=55.0, size=10000)
C = np.random.uniform(low=0.0, high=10.0,... | 79,308 |
def sc_get_patient_df_dict(all_file_paths):
"""
Loads all the methylation DF and returns them as a dictionary
:param all_file_paths: List of all the methylation files
:return: A dictionary were the keys are the patient and the values a dictionary of chromosome and the methylation df
"""
patient_... | 79,309 |
def rgba2rgb(rgba, background=(255,255,255)):
""" Converts a 4-channel image array to a 3-channel image array
Inputs:
rbga: 4-channel array of image pixel data
Output:
An np array containing the 3-channel array respresenting the pixel values of the image
"""
row, col, ch = rgba.sh... | 79,310 |
def get_model_fields(model, m2m=False):
"""
Given a model class, will return the dict of name: field_constructor
mappings.
"""
tree = get_model_tree(model)
if tree is None:
return None
possible_field_defs = tree.find("^ > classdef > suite > stmt > simple_stmt > small_stmt > expr_stmt... | 79,311 |
def guess_requirements_path(django_directory_path: str,
project_name: str) -> Optional[str]:
"""Guess the absolute path of requirements.txt.
The logic is as the follows:
1. If "requirements.txt" exists in the given directory, return it.
2. If "requirements.txt" exist... | 79,312 |
def trace(a: Numeric, axis1: Int = -2, axis2: Int = -1): # pragma: no cover
"""Compute the trace of a tensor.
Args:
a (tensor): Tensor to compute trace of.
axis1 (int, optional): First dimension to compute trace over. Defaults
to `-2`.
axis2 (int, optional): Second dimensio... | 79,313 |
def _handle_no_answer(prediction, ground_truths):
"""Check if there is no groundtruth answer and compute no-answer score."""
score = None
# Check for no-answer: ground_truths can look like ['', '', '']
# the reason there are multiple empty values because we operate at batch
# and append '' to the maximum... | 79,314 |
def recover_request_key_and_name(recovery_date, recovery_secret1):
"""Download the private information about this ID from Freenet."""
secret1 = recovery_date + "--" + recovery_secret1
uploadprefix = recovery_secret_to_ksk(secret1)
return fastget(uploadprefix + "--identity")[1] | 79,315 |
def _locate(path):
"""Search for a relative path and turn it into an absolute path.
This is handy when hunting for data files to be passed into h2o and used by import file.
Note: This function is for unit testing purposes only.
Parameters
----------
path : str
Path to search for
:ret... | 79,316 |
def load_motchallenge(matrix_data, min_confidence=-1):
"""Load MOT challenge data.
This is a modification of the function load_motchallenge from the py-motmetrics library, defined in io.py
In this version, the pandas dataframe is generated from a numpy array (matrix_data) instead of a text file.
Param... | 79,317 |
def verify_route_four_byte_as(device, expected_as_path, peer_address, target_address=None,
protocol_type=None, protocol='bgp', no_protocol_type=False,
max_time=60, check_interval=10):
""" Verify best path counter
Args:
device ('str'):... | 79,318 |
async def get_resources_from_events(policy_changes: List[Dict]) -> Dict[str, dict]:
"""Returns a dict of resources affected by a list of policy changes along with
the actions and other data points that are relevant to them.
Returned dict format:
{
"resource_name": {
"actions": ["ser... | 79,319 |
def doSiteStable(site_id, site_type='cntr'):
"""Check if site is created or not
:param site_id: Enter site id
:type site_id: string
:param site_type: Enter site type
:type site_type: string
"""
if site_type == 'cntr':
b = Sites()
elif site_type == 'vcs':
b = VcsSite()
... | 79,320 |
def get_instance_fields(derived_col_names, target_name):
"""
It returns the Instance field element.
Parameters
----------
derived_col_names : List
Contains column names after preprocessing.
target_name : String
Name of the Target column.
Returns
-------
... | 79,321 |
def cleanupDatetimeRange(requestKeys, queryDict):
"""
cleanupDatetimeRange
... in queryDict merge submitted__lte and submitted__gte filter
fields into submitted__range for all datetime type fields
(e.g. submitted)
"""
_logger.debug('incoming queryD... | 79,322 |
def parse_requirements(fname='requirements.txt'):
"""
Parse the package dependencies listed in a requirements file.
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
from os.path import dirname, join, exists
require_fpath = join(dirname(__file__), fname)
i... | 79,323 |
def edux_authors_set(config):
"""Saves EDUX authors"""
path = os.path.join(BASE['edux'], EDUX['authors'])
_setter(path, config) | 79,324 |
def get_path_length_grid(timeDict):
"""
:param timeDict:
:return:
"""
Masks = timeDict['Masks']
if isinstance(timeDict['pathLengthAll'], dict):
a = np.zeros((len(timeDict['pathLengthAll']) + 1, len(timeDict['pathLengthAll']) + 1))
for key, value in timeDict['pathLengthA... | 79,325 |
def test_serialize_profile(api_rf, profile_factory, serialized_time):
"""
Test serializing a profile.
"""
profile = profile_factory()
api_rf.user = profile.km_user.user
request = api_rf.get(profile.get_absolute_url())
serializer = serializers.ProfileListSerializer(
profile, context... | 79,326 |
def BFGS(f, x, iters=10, tol=1e-10):
""" Run the gradient descent algorithm to minimize a function f.
Parameters
----------
f: callable (function)
x: int, float, or `Variable` object
initial guess/starting point for minimum
iters: integer
maximum number of iterations
tol: float
thi... | 79,327 |
def get_admin_options(item_container, user_perms):
""" Personen mit manager-Rechten koennen bestimmte Optionen auswaehlen """
if not user_perms.perm_manage:
return ''
from django.template.loader import get_template
from django.template import Context
tSection = get_template('app/survey/admin_options.html'... | 79,328 |
def download_and_save_data(
connection: _WebDBConnection,
simulation: str,
snap_number: int,
min_mass_star: float,
manual_dir: Optional[pathlib.Path] = None,
) -> None:
"""Download the data for a single snapshot."""
df = download_tables(connection, simulation, snap_number, min_mass_star)
... | 79,329 |
def FromString(s, more_formatters=lambda x: None, _constructor=None):
"""Like FromFile, but takes a string."""
f = StringIO.StringIO(s)
return FromFile(f, more_formatters=more_formatters, _constructor=_constructor) | 79,330 |
def xacto(fields,x,y,z):
"""xacto is a function which takes a list of strings iterates through this list until it reaches a passed index 'x' it then runs the recursive function digimon to find the first letter in the string,finds the index of that letter in the string,
splits the string into just numbers 'To... | 79,331 |
def test_sophos_firewall_user_add_command(requests_mock):
"""
Scenario: Add a new user.
Given:
- User has provided valid credentials.
When:
- sophos_firewall_user_add is called.
Then:
- Ensure outputs prefix is correct.
- Ensure a sample value from the API matches what is generat... | 79,332 |
def get_tooltip(mod):
"""Returns the tooltip for the given mod."""
return manifest.get_cfg('mods', mod).get_string('tooltip') | 79,333 |
def dif_prices(p_df_predicciones, p_grupo):
"""
Visualizacion de las diferencias de la mediana del ultimo precio por clase
con respecto a la prediccion
Parameters
---------
p_df_predicciones: DataFrame : resultado de predicciones
p_grupo: str : nombre del grupo de productos
R... | 79,334 |
def divergence(
ts, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True
):
"""
Computes average pairwise divergence between two random choices from x
over the window specified.
"""
windows = ts.parse_windows(windows)
if indexes is None:
indexes = [(0, 1)]
me... | 79,335 |
def get_recipe_options(recipe):
"""Retrieves additional options for the given recipe
Args:
recipe: Project recipe
Returns:
dic: Contains recipe params w/ following potential keys,
BAIT
TARGET
MSKQ
MARKDUPLICATES
For Example:
{'BAIT': '/path/to/HemeBrainPACT_v1_BAITS.interval_list',
... | 79,336 |
def plot_data_type(frag):
"""
Create the plot
:param: frag pd.DataFrame -
:param:
"""
data = []
labels = []
for st_pair, st in SUBSTITUTION_TYPES_COMBINED:
st_sizes = frag[frag['Var'].isin(st_pair)]['Size']
if len(st_sizes) > 1:
data.append(st_sizes)
... | 79,337 |
def _pick_first_with_field(
datasets_wide: Mapping[MultiRegionDataset, pd.DataFrame],
timeseries_field_datasets: Mapping[FieldName, List[MultiRegionDataset]],
) -> Mapping[MultiRegionDataset, pd.DataFrame]:
"""Creates a DataFrame for each dataset that has True for the subset of datasets_wide that is
sel... | 79,338 |
def eval_policy(
_run,
_seed: int,
env_name: str,
eval_n_timesteps: Optional[int],
eval_n_episodes: Optional[int],
num_vec: int,
parallel: bool,
render: bool,
render_fps: int,
videos: bool,
video_kwargs: Mapping[str, Any],
log_dir: str,
policy_type: str,
policy_pa... | 79,339 |
def hash_id(note):
"""Return hashed id from seed note
:param note: Pytest fixture
:return: hash string from note.id
"""
return hashids.encode(note.id) | 79,340 |
def test_setup_doctest(example_tester):
"""Make sure --setup-doctest --outfile is correct."""
command = labeled.contents(label="setup-doctest-outfile")
_ = example_tester(
command, want_file_name="doc/test_setup_doctest.py", pytest_options=None
) | 79,341 |
def build_data(document, publication):
"""
Maps the variables of pt_law_downloader to our form
"""
return {'creator_name': publication['creator'],
'type': publication['type'],
'number': publication['number'],
'text': publication['text'],
'summary': publica... | 79,342 |
def test_2hydroxypyridine():
"""Check on a structure subject to tautomerism, 1/2."""
model=str("""
OpenBabel020922
12 12 0 0 0 0 0 0 0 0999 V2000
1.1010 0.0362 0.2292 O 0 0 0 0 0 0 0 0 0 0 0 0
2.4532 0.1277 0.0818 C 0 0 0 0 0 0 0 0 0 0 0 0
3.0800 1... | 79,343 |
def get_credit_card():
"""
gets a valid credit card from the user via console
"""
print("- PAYMENT INFORMATION -")
print("Please enter your credit card information. This information will NOT be saved.\n")
card_number = input("Please type your CREDIT CARD NUMBER: ").strip()
card_expiry... | 79,344 |
def deduplicate(data_name, data_dict, data_dir):
"""
Return a local path for given data path
Args:
data_name: the basename of the target file
data_dict: the existing mapping of local paths
data_dir: the full path of the destination directory
"""
n_dups = 0
basename = data... | 79,345 |
def gmx_cluster(input_structure_path: str, input_traj_path: str, output_pdb_path: str, input_index_path: str = None, properties: dict = None, **kwargs) -> int:
"""Execute the :class:`GMXCluster <gromacs.gmx_cluster.GMXCluster>` class and
execute the :meth:`launch() <gromacs.gmx_cluster.GMXCluster.launch>` metho... | 79,346 |
def precision_and_recall(true_labels, labels_limits):
"""Estimate the precision and recall
:param true_labels: true labels
:param labels_limits: predicted labels
:return: precision and recall
"""
_, fp, fn, tp = confusion_matrix(true_labels, labels_limits).ravel()
return tp / (fp + tp), tp... | 79,347 |
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_unicode, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case fi... | 79,348 |
def tanh(x, vis=False):
"""
实现tanh函数=(exp(x)-exp(x))/(exp(x)+exp(-x))
:param x:输入的数据, list格式[x1,x2,x3]
:param vis:是否可视化
:return:
"""
y = [(math.exp(x_)-math.exp(-x_))/(math.exp(x_)+math.exp(-x_))
for x_ in x ]
print('Input data2:{}, \nCompute Result:{}'.format(x, y))
if vis:... | 79,349 |
def _get_grid_points_by_rotations(bz_gp, bz_grid: BZGrid, rotations):
"""Grid point rotations without surface treatment."""
rot_adrs = np.dot(rotations, bz_grid.addresses[bz_gp])
grgps = get_grid_point_from_address(rot_adrs, bz_grid.D_diag)
return bz_grid.grg2bzg[grgps] | 79,350 |
def fatal (s):
""" ensure we end if a problem """
logging.fatal("ERROR: "+s)
sys.exit(-1) | 79,351 |
def lstm(xs, ms, s, scope, nh):
"""LSTM layer for policy network, using same weight and bias initialization as LSTM in reward redistribution model
Based on baselines.ppo2.policies.py; These initializations were taken directly from the redistribution model LSTM
and could be optimized;
"""
nbatch... | 79,352 |
def move_left(point):
"""Return a copy of `point`, moved left along the X-axis by 1.
This function returns a tuple, not a Vector2D instance, and should only be
used if performance is essential. Otherwise, the recommended alternative is
to write `point + LEFT`.
"""
x, y = point
return x - 1... | 79,353 |
def _apply_template(template, target, *, checkout, extra_context):
"""Apply a template to a temporary directory and then copy results to target."""
with tempfile.TemporaryDirectory() as tempdir:
repo_dir = cc_main.cookiecutter(
template,
checkout=checkout,
no_input=Tr... | 79,354 |
def search(repos, users=None, sites=None):
"""
Search across supported sites for cloneable repositories.
:param repos: The repo(s) to search for.
:param users: The user(s) to search under. If none is provided, the environment
is examined for possible user names.
:param sites: The site(... | 79,355 |
def get_ensembl_gene(ensembl_id, ENSEMBL_REST_SERVER = GRCH37_ENSEMBL_REST_SERVER):
"""
Get gene details from name
* string
Returntype: Gene
"""
key = (ensembl_id, ENSEMBL_REST_SERVER)
if key not in known_genes:
known_genes[key] = fetch_gene_id(ensembl_id, ENSEMBL_REST_SERVER)
return known_genes[key] | 79,356 |
def amend_xbar(top, xbar):
"""Amend crossbar informations to the top list
Amended fields
- clock: Adopt from module clock if exists
- inst_type: Module instance some module will be hard-coded
the tool searches module list and memory list then put here
- base_addr: from top["module"... | 79,357 |
def list_notes_by_itinerary(itin_id):
"""serialize notes list to jsonify"""
notes_author = db.session.query(User.fname, Note.comment, Note.day).join(User)
itin_notes = notes_author.filter(Note.itinerary_id == itin_id).all()
json_notes = []
for note in itin_notes:
n_dict = {}
n_dic... | 79,358 |
def set_dist_ang(a, b, dist, ang=0):
"""Returns point distance and angle away from a towards b"""
c = normalize(b - a) * dist
cr2d = rotate2D(*c[:2], ang)
cr = cr2d if len(a) == 2 else a3([*cr2d, c[2]])
return cr + a | 79,359 |
def get_share_in_repo_list(request, start, limit):
"""List share in repos.
"""
username = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
repo_list = seafile_api.get_org_share_in_repo_list(org_id, username,
... | 79,360 |
def _off(ns, args):
"""Turns off tracing for files."""
for f in ns.files:
if f == "__file__":
f = _find_caller(args)
if f is None:
continue
tracer.stop(f) | 79,361 |
def load_data(args, device):
"""Loads the data into three different data loaders. (Train, Test, Evaluation)
Split the training dataset into a train / test dataset.
Args:
args: arguments passed to the python script
"""
train_dataset = CSVDataset(args, args.train_files, device)
... | 79,362 |
def check_freq(session, freq):
"""
Check the frequency of the radar with the table, hfrSystemTypes. Return the frequency id
:param session: SQLAlchemy database session instance
:param freq: Frequency floating point number
:return: ID of the appropriate system type in hfrSystemTypes table
"""
... | 79,363 |
def yesterday_and_today():
"""Prode `date` (d) and `str` (s) versions of yesterday and today."""
d = Generic()
d.today = date.today()
d.yesterday = d.today - timedelta(1)
s = Generic()
s.today = d.today.isoformat()
s.yesterday = d.yesterday.isoformat()
result = Generic()
result.d = d... | 79,364 |
def pix_to_sky(idx, nside):
"""Convert the pixels corresponding to the input indexes to sky coordinates (RA, Dec)"""
theta, phi = hp.pix2ang(nside, idx)
ra = np.rad2deg(phi)
dec = np.rad2deg(0.5 * np.pi - theta)
return ra, dec | 79,365 |
def stoi(x):
"""Converts strings to integers"""
if type(x) != str:
raise ValueError("Input value not a string")
try:
ans = 0
for d in x:
ans = 10 * ans + dic[d]
return ans
except:
raise ValueError("Input value not a string") | 79,366 |
def view(args):
""" View data in a dataset
"""
dataset_path = args.dataset_path
# Load dataset
data = pickle.load(open(dataset_path,"rb"))
imgs = data['images']
scores = data['scores']
# Create grid
size = len(imgs)
cols = math.ceil(np.sqrt(size))
rows = math.ceil(size/cols)
# Plot all imag... | 79,367 |
def brightness():
"""Set brightness value for camera."""
# Catch ajax request with form data
brightness_val = 'error'
if request.method == 'POST':
brightness_val = request.form.get('brightness')
if brightness_val is not None:
app.logger.info('Form brightness submitted: %s', b... | 79,368 |
def fraction_low_base_quality(channels: List[np.ndarray],
threshold: int = 127) -> float:
"""Gets fraction of bases that have low base quality scores in a pileup.
Args:
channels: A list of channels of a DeepVariant pileup image. This only uses
channels[1], the base quali... | 79,369 |
def attach_pwn(args):
"""Attaches to a pwn thread
Just sets needed docker arguments and run it as well
"""
container_name = _read_container_name()
# FIXME Is it better that we just exec it with given name?
conts = container.list(filters={'name':container_name})
if len(conts) != 1:
r... | 79,370 |
def convert_deps_from_pip(dep):
""""Converts a pip-formatted dependency to a Pipfile-formatted one."""
dependency = {}
req = get_requirement(dep)
extras = {'extras': req.extras}
# File installs.
if (req.uri or req.path or is_installable_file(req.name)) and not req.vcs:
# Assign a package... | 79,371 |
def saveTurn(player, column):
"""add turn summary to save file
Args:
player (number): player id 1/2
column (number): column index 0-6
"""
addToSaveFile(
f'{grid.gridToStr(grid.cells)}\nLe joueur {PLAYER_NAME[player]} joue en {column+1}\n\n----------------------\n'
) | 79,372 |
def draw_corr(img0, pix_pos0, img1, pix_pos1, num=None):
"""
Draw matches, numpy version. Parameters are the same as draw keypoints
"""
if num is None:
inds = np.arange(len(pix_pos0))
num = len(pix_pos0)
else:
inds = np.linspace(0, len(pix_pos0), num, endpoint=False).astype(n... | 79,373 |
def calc_stft(protocol_df: pd.DataFrame, path: str) -> Tuple[np.ndarray, np.ndarray]:
"""
This function extracts spectrograms from raw audio data by using FFT.
Args:
protocol_df(pd.DataFrame): ASVspoof2019 protocol.
path(str): Path to ASVSpoof2019
Returns:
data: spectrograms that have ... | 79,374 |
def dict_to_yaml(dict_data):
"""Return YAML from dictionary.
:param dict_data: Dictionary data
:type dict_data: dict
:returns: YAML dump
:rtype: string
"""
return yaml.dump(dict_data, default_flow_style=False) | 79,375 |
def assert_dirtrees_eq(tree1: Path, tree2: Path) -> None:
"""Assert that the file trees at the given paths are equal"""
assert sorted(map(attrgetter("name"), tree1.iterdir())) == sorted(
map(attrgetter("name"), tree2.iterdir())
)
for p1 in tree1.iterdir():
p2 = tree2 / p1.name
as... | 79,376 |
def snake_case_to_capital_case(string):
"""
string::str ex. this_is_an_example
return::str ex. ThisIsAnExample
"""
LOG.debug('Converting string to capital case: %s', string)
split_list = string.split('_')
capital_list = [item.capitalize() for item in split_list]
capital_case = ''.join(ca... | 79,377 |
def prepare_annot(annots, out_annot_table, out_annot, labels):
"""generate graphlan annotation"""
annot_table = pd.DataFrame()
#merge individual annotation tables
for annot_f in annots:
annot_table_temp = pd.read_csv(annot_f, sep = "\t", index_col = 0)
annot_table = pd.concat([annot_tabl... | 79,378 |
def print_ruleset(ruleset, file):
""" Print a human-readable ruleset """
pprint(ruleset, stream=file) | 79,379 |
def plot_ape(x_axis, ape, size=(18, 10), title=None):
"""Plots APE error against time for a given metrics.APE instance.
Args:
x_axis: An array-type of values for all the x-axis values (time).
rpe: A metrics.APE instance with pre-processed data.
size: A tuple optionally containing t... | 79,380 |
def set_pokedex(id_pokemon,id_trainer):
"""
You can add a new pokemon to the pokedex
Args:
id_pokemon: We pass the pokemon's identification as a parameter.
id_trainer: We pass the trainer's identification as a parameter.
"""
try:
connection = connec()
if connection.is... | 79,381 |
def set_gef_setting(name, value, _type=None, _desc=None):
"""Set global gef settings.
Raise ValueError if `name` doesn't exist and `type` and `desc`
are not provided."""
global __config__
if name not in __config__:
# create new setting
if _type is None or _desc is None:
... | 79,382 |
def fixed_variables_only_in_inequalities(block):
"""
Method to return a ComponentSet of all fixed Var components which appear
only within activated inequality Constraints in a model.
Args:
block : model to be studied
Returns:
A ComponentSet including all fixed Var components which ... | 79,383 |
def test_get_element(element: str, exists: bool):
"""Verifies correct element is retrieved."""
element_result = get_element(element) is False
assert element_result is not exists, (
f"Error in element '{element}' search. Should be {exists}"
) | 79,384 |
def print_csv_stdout(data, fieldnames, extrasaction="raise", mode="w",
quote_style=csv.QUOTE_NONNUMERIC, round_digits=False):
"""
Given a list of dicts and fieldnames, writes a csv to stdout
:param round_digits: if desired, provide decimal number for rounding
:param data: The data ... | 79,385 |
def generate_white_pawn_attack_bb_from_square(from_square: int) -> np.uint64:
"""
Returns the white pawn attack bitboard on an otherwise empty board from the provided square
:param from_square: starting square from which to generate white pawn attacks
:return: np.uint64 bitboard representation of white ... | 79,386 |
def test_playback_fire_and_forget(event_loop, test_data):
"""Test playing back sound files using fire and forget."""
sound = test_data.get_file('media', 'alert.wav')
source = pyglet.media.load(sound, streaming=False)
player = source.play()
player.on_player_eos = event_loop.interrupt_event_loop
e... | 79,387 |
def _read(file_path):
"""
Reads a given .csv file from disk.
:return: loaded data in the form of a pandas Dataframe.
"""
return pd.read_csv(os.path.join(CURRENT_PATH, file_path)) | 79,388 |
def is_subscription(service_type):
"""
check service type is subscription or empty
"""
return not service_type or service_type == SUBSCRIPTION_SERVICE_TYPE | 79,389 |
def _args_run_polish(args):
"""Run `pbsvp polish`"""
log.info("Running `{}`".format(POLISH_ENTRY))
log.debug('Locals={}'.format(locals()))
run_polish(genome_fa=args.genome_fa, subreads_xml_fn=args.subreads_bam, aln_fn=args.alignments_bam,
in_bed_fn=args.in_rich_bed, out_dir=args.out_dir,
... | 79,390 |
def df_to_list(df):
"""Convert a pandas DataFrame values to a list of lists.
Args:
df (pandas.DataFrame): A DataFrame to convert to a dictionary.
Returns:
list: A list of lists
"""
return [df[column_name].values.tolist() for column_name in df.columns] | 79,391 |
def load_config(config_file_name):
"""Load the JSON configuration file and return its structure."""
try:
with open(config_file_name, 'r') as f:
retval = json.load(f)
return retval
except Exception as e:
print "ERROR reading config file:"
raise e | 79,392 |
def findNearestDate(date_list, date):
"""
Find closest datapoint of each uppermost sensor in time window.
Adapted from https://stackoverflow.com/a/32237949/3816498 .
Parameters
----------
date_list : array-like
List of dates
date : datetime
The date, to which the nearest da... | 79,393 |
def prod(stuff):
""" prod(stuff):
compute the product (i.e. reduce with '*') of the elements of 'stuff'.
'stuff' must be iterable."""
return reduce(lambda x, y: x*y, stuff) | 79,394 |
def GetIonPositions(names_and_pos, ion_input):
"""
input: names_and_pos dict<string, Vector3>: dictionary that contains the position of each labelled element present.
input: ion_input dict<string, Ionic>: dict of Ionic class wich contains info with no radius value
output: dict<string, Vector3>: refined ... | 79,395 |
def log_location(location):
"""Ask for location and log it, together with current wifi signals."""
# read from sensors
signals = get_signals()
# treat case where not enough signals found
if signals.empty:
print('Not enough signals!')
return
# log location to model
log_signals... | 79,396 |
def run_task(
session_id,
task_id,
bindings,
save_to="saved_schedules.txt",
profile_level=0,
no_actual_run=False,
):
"""Run a task in the Session.
Parameters
----------
session_id : int
The Session in which the graph is initialized.
task_id : int
bindings : lis... | 79,397 |
def assert_array_allclose(this, other):
"""Assert that array `this` is close to array `other`."""
if np.ma.isMaskedArray(this) or np.ma.isMaskedArray(other):
np.testing.assert_array_equal(this.mask, other.mask)
np.testing.assert_allclose(this, other) | 79,398 |
def update_permissions(params):
"""Give user and group permissions to all generated files.
"""
start_time = time.time()
sdir = params['sdir']
bids_dicom_dir = params['bids_dicom_dir']
bids_nifti_dir = params['bids_nifti_dir']
group = params['group']
stdout = params['stdout']
for dire... | 79,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.