content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_setup_dirs():
"""Test that all GOATOOLS package dirs are in the setup.py file"""
pkgs_setup = set(m for m in PACKAGES if 'test_' not in m)
pkgs_dirs = _get_pkgmods()
assert pkgs_dirs.issubset(pkgs_setup), _errmsg(pkgs_setup, pkgs_dirs)
print('**NOTE: TEST PASSED') | 21,800 |
def config_context(**new_config):
"""** EXPERIMENTAL FEATURE **
Inspired by sklearn's ``config_context``
"""
old_config = asdict(Config)
Config.update(new=new_config)
try:
yield
finally:
Config.update(new=old_config) | 21,801 |
def split_on_first_brace(input,begin_brace = "{",end_brace = "}",error_replacement="brace_error"):
"""
input: string with {Something1} Something2
output: tuple (Something1,Something2)
"""
if error_replacement=="chapter_error":
print(input[:20])
input = remove_empty_at_begin(input)
if... | 21,802 |
def find_files(folder_path: str, pattern: str, maxdepth: int = 1):
"""
Read the absolute path of files under a folder
TODO: make it recursive
"""
assert isinstance(folder_path, str), 'folder path must be a string'
assert maxdepth >= 0
if maxdepth == 0:
return []
res = []
f... | 21,803 |
def test_encryption_materials_cache_in_grace_period_acquire_lock():
"""Test encryption grace period behavior.
When the TTL is GRACE_PERIOD and we successfully acquire the lock for retrieving new materials,
we call to the provider store for new materials.
"""
store = MockProviderStore()
name = "... | 21,804 |
def check_count(value, total_count, dimension_type):
"""check the value for count."""
value = validate(value, "count", int)
if value > total_count:
raise ValueError(
f"Cannot set the count, {value}, more than the number of coordinates, "
f"{total_count}, for the {dimension_ty... | 21,805 |
def test_get_all_pairs_indices():
"""check i < j < n"""
ns = onp.random.randint(5, 50, 10)
for n in ns:
inds_i, inds_j = get_all_pairs_indices(n)
assert (inds_i < inds_j).all()
assert (inds_j < n).all() | 21,806 |
def request_certificate(request):
"""Request the on-demand creation of a certificate for some user, course.
A request doesn't imply a guarantee that such a creation will take place.
We intentionally use the same machinery as is used for doing certification
at the end of a course run, so that we can be s... | 21,807 |
def get_useable_checkers():
"""
列出可用插件列表
:return:
"""
useable_checkers = list()
for (checker_name, checker_instance) in CHECKER_INSTANCE_DICT.items():
if checker_instance.useable:
useable_checkers.append(checker_instance)
return useable_checkers | 21,808 |
def genBubbleChart(df: pd.DataFrame, years, title: str, quartile: str, name: str, mlTitle: str):
"""Generates bubble scatter plot for avg pdsi
color - precipAvg mean of all counties present for the year
size - pdsiAvg mean of all counties present for the year
y - number of counties in lower pdsi quarti... | 21,809 |
def get_training_roidb(imdb):
"""Returns a roidb (Region of Interest database) for use in training."""
if cfg.TRAIN.USE_FLIPPED:
print 'Appending horizontally-flipped training examples...'
imdb.append_flipped_images()
print 'done'
print 'Preparing training data...'
wrdl_roidb.pr... | 21,810 |
def _used_in_calls(schedule_name: str, schedule: ScheduleBlock) -> bool:
"""Recursively find if the schedule calls a schedule with name ``schedule_name``.
Args:
schedule_name: The name of the callee to identify.
schedule: The schedule to parse.
Returns:
True if ``schedule``calls a ... | 21,811 |
def font_size_splitter(font_map):
"""
Split fonts to 4 category (small,medium,large,xlarge) by maximum length of letter in each font.
:param font_map: input fontmap
:type font_map : dict
:return: splitted fonts as dict
"""
small_font = []
medium_font = []
large_font = []
xlarge_... | 21,812 |
def get_candidate_set_size(
mapped_triples: MappedTriples,
restrict_entities_to: Optional[Collection[int]] = None,
restrict_relations_to: Optional[Collection[int]] = None,
additional_filter_triples: Union[None, MappedTriples, List[MappedTriples]] = None,
num_entities: Optional[int] = None,
) -> pand... | 21,813 |
def add_new_user(user_info: dict):
"""
Add a new user to the database from first oidc login.
First check if user with the same email exists.
If so, add the auth_id to the user.
Args:
user_info (dict): Information about the user
"""
db_user = flask.g.db["users"].find_one({"email": u... | 21,814 |
def dm2skin_normalizeWeightsConstraint(x):
"""Constraint used in optimization that ensures
the weights in the solution sum to 1"""
return sum(x) - 1.0 | 21,815 |
def _load_bitmap(filename):
"""
Load a bitmap file from the backends/images subdirectory in which the
matplotlib library is installed. The filename parameter should not
contain any path information as this is determined automatically.
Returns a wx.Bitmap object
"""
basedir = os.path.join(r... | 21,816 |
def figure_9():
"""
Figure 9: Beach width versus storm duration for natural dune simulations
colored by the change in dune volume (red: erosion, blue: accretion), similar
to Figure 7 but with the y-axis re-scaled based on the initial beach width in
each simulation. Each row of plots represents ... | 21,817 |
def get_auth():
"""
POST request to users/login, returns auth token
"""
try:
url_user_login = f"https://{url_core_data}/users/login"
json = {
"username": creds_name,
"password": creds_pw
}
headers = {
"Accept": "ap... | 21,818 |
def vector_between_points(P, Q):
""" vector between initial point P and terminal point Q """
return vector_subtract(Q, P); | 21,819 |
def execve(path, args, env):
"""Execute a new program, replacing the current process.
:type path: bytes | unicode
:type args: collections.Iterable
:type env: collections.Mapping
:rtype: None
"""
pass | 21,820 |
def before_train(loaded_train_model, train_model, train_sess, global_step, hparams, log_f):
"""Misc tasks to do before training."""
stats = init_stats()
info = {"train_ppl": 0.0, "speed": 0.0, "avg_step_time": 0.0,
"avg_grad_norm": 0.0, "avg_train_sel": 0.0,
"learning_rate": loaded_t... | 21,821 |
def reg_file_comp(ref_file, comp_file):
"""Compare the reference file 'ref_file' with 'comp_file'. The
order of these two files matter. The ref_file MUST be given
first. Only values specified by reg_write() are compared. All
other lines are ignored. Floating point values are compared based
on rel_t... | 21,822 |
def evaluate(indir, split, langs, truncate, cutoff, sort_lang, print_cm, fasttext_model):
"""
Evaluate language prediction performance.
"""
if langs is not None:
langs = {l.strip() for l in langs.split(',')}
in_langs = sorted([l for l in os.listdir(indir) if langs is None or l in langs])
... | 21,823 |
def test_egg_re():
"""Make sure egg_info_re matches."""
egg_names_path = os.path.join(os.path.dirname(__file__), "eggnames.txt")
with open(egg_names_path) as egg_names:
for line in egg_names:
line = line.strip()
if line:
assert egg_info_re.match(line), line | 21,824 |
def methodInDB(method_name, dict_link, interface_db_cursor): #checks the database to see if the method exists already
"""
Method used to check the database to see if a method exists in the database
returns a list [Boolean True/False of if the method exists in the db, dictionary link/ID]
"""
cr... | 21,825 |
def dict_to_image(screen):
""" Takes a dict of room locations and their block type output by RunGame.
Renders the current state of the game screen.
"""
picture = np.zeros((51, 51))
# Color tiles according to what they represent on screen:.
for tile in screen:
... | 21,826 |
def get_mobilenet(version,
width_scale,
model_name=None,
pretrained=False,
root=os.path.join('~', '.keras', 'models'),
**kwargs):
"""
Create MobileNet or FD-MobileNet model with specific parameters.
Parameters:
--... | 21,827 |
def channels(context):
"""
*musicpd.org, client to client section:*
``channels``
Obtain a list of all channels. The response is a list of "channel:"
lines.
"""
raise MpdNotImplemented | 21,828 |
def test_svd_space_res(file_prefix='F_s'):
"""
test SVD decomposition of spatial residuals by generating SVD, saving to file and reloading
"""
from proteus.deim_utils import read_snapshots,generate_svd_decomposition
ns = get_burgers_ns("test_svd_space_res",T=0.1,nDTout=10,archive_pod_res=True)
... | 21,829 |
def can_fuse_to(wallet):
"""We can only fuse to wallets that are p2pkh with HD generation. We do
*not* need the private keys."""
return isinstance(wallet, Standard_Wallet) | 21,830 |
def _build_context(hps, encoder_outputs):
"""Compute feature representations for attention/copy.
Args:
hps: hyperparameters.
encoder_outputs: outputs by the encoder RNN.
Returns:
Feature representation of [batch_size, seq_len, decoder_dim]
"""
with tf.variable_scope("memory_context"):
contex... | 21,831 |
def rf_local_divide(left_tile_col: Column_type, rhs: Union[float, int, Column_type]) -> Column:
"""Divide two Tiles cell-wise, or divide a Tile's cell values by a scalar"""
if isinstance(rhs, (float, int)):
rhs = lit(rhs)
return _apply_column_function('rf_local_divide', left_tile_col, rhs) | 21,832 |
def test_init_with_params(color, mode):
"""Tests the initialization of a Printer with custom parameters."""
printer = Printer(Mode[mode], color)
assert printer.mode == Mode[mode]
assert printer.colored == color | 21,833 |
def check_dependencies_ready(dependencies, start_date, dependencies_to_ignore):
"""Checks if every dependent pipeline has completed
Args:
dependencies(dict): dict from id to name of pipelines it depends on
start_date(str): string representing the start date of the pipeline
dependencies_... | 21,834 |
def factor_returns(factor_data, demeaned=True, group_adjust=False):
"""
计算按因子值加权的投资组合的收益
权重为去均值的因子除以其绝对值之和 (实现总杠杆率为1).
参数
----------
factor_data : pd.DataFrame - MultiIndex
一个 DataFrame, index 为日期 (level 0) 和资产(level 1) 的 MultiIndex,
values 包括因子的值, 各期因子远期收益, 因子分位数,
因子分组(... | 21,835 |
def create_input_lambda(i):
"""Extracts off an object tensor from an input tensor"""
return Lambda(lambda x: x[:, i]) | 21,836 |
def create_model_talos(params, time_steps, num_features, input_loss='mae', input_optimizer='adam',
patience=3, monitor='val_loss', mode='min', epochs=100, validation_split=0.1):
"""Uses sequential model class from keras. Adds LSTM layer. Input samples, timesteps, features.
Hyperparameters inclu... | 21,837 |
def parseAnswers(args, data, question_length = 0):
"""
parseAnswers(args, data): Parse all answers given to a query
"""
retval = []
#
# Skip the headers and question
#
index = 12 + question_length
logger.debug("question_length=%d total_length=%d" % (question_length, len(data)))
if index >= len(data):
log... | 21,838 |
def ortho_init(scale=1.0):
"""
Orthogonal initialization for the policy weights
:param scale: (float) Scaling factor for the weights.
:return: (function) an initialization function for the weights
"""
# _ortho_init(shape, dtype, partition_info=None)
def _ortho_init(shape, *_, **_kwargs):
... | 21,839 |
def setup(bot: commands.Bot) -> None:
"""Load the Ping cog."""
bot.add_cog(Ping(bot)) | 21,840 |
def get_rde_model(rde_version):
"""Get the model class of the specified rde_version.
Factory method to return the model class based on the specified RDE version
:param rde_version (str)
:rtype model: NativeEntity
"""
rde_version: semantic_version.Version = semantic_version.Version(rde_version)... | 21,841 |
def pnorm(x, mu, sd):
"""
Normal distribution PDF
Args:
* scalar: variable
* scalar: mean
* scalar: standard deviation
Return type: scalar (probability density)
"""
return math.exp(- ((x - mu) / sd) ** 2 / 2) / (sd * 2.5) | 21,842 |
def getTransformToPlane(planePosition, planeNormal, xDirection=None):
"""Returns transform matrix from World to Plane coordinate systems.
Plane is defined in the World coordinate system by planePosition and planeNormal.
Plane coordinate system: origin is planePosition, z axis is planeNormal, x and y axes are orth... | 21,843 |
def jp_runtime_dir(tmp_path):
"""Provides a temporary Jupyter runtime dir directory value."""
return mkdir(tmp_path, "runtime") | 21,844 |
def _softmax(X, n_samples, n_classes):
"""Derive the softmax of a 2D-array."""
maximum = np.empty((n_samples, 1))
for i in prange(n_samples):
maximum[i, 0] = np.max(X[i])
exp = np.exp(X - maximum)
sum_ = np.empty((n_samples, 1))
for i in prange(n_samples):
sum_[i, 0] = np.sum(exp... | 21,845 |
def merge_dicts(dict1, dict2, dict_class=OrderedDict):
"""Merge dictionary ``dict2`` into ``dict1``"""
def _merge_inner(dict1, dict2):
for k in set(dict1.keys()).union(dict2.keys()):
if k in dict1 and k in dict2:
if isinstance(dict1[k], (dict, MutableMapping)) and isinstance... | 21,846 |
def jaccard_overlap_numpy(box_a: numpy.ndarray, box_b: numpy.ndarray) -> numpy.ndarray:
"""Compute the jaccard overlap of two sets of boxes. The jaccard overlap
is simply the intersection over union of two boxes.
E.g.:
A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
Args:
box_a: Multiple bo... | 21,847 |
def find_pkg(pkg):
""" Find the package file in the repository """
candidates = glob.glob('/repo/' + pkg + '*.rpm')
if len(candidates) == 0:
print("No candidates for: '{0}'".format(pkg))
assert len(candidates) == 1
return candidates[0] | 21,848 |
def random_choice(lhs, ctx):
"""Element ℅
(lst) -> random element of a
(num) -> Random integer from 0 to a
"""
if vy_type(lhs) == NUMBER_TYPE:
return random.randint(0, lhs)
return random.choice(iterable(lhs, ctx=ctx)) | 21,849 |
def ask(choices,
message="Choose one from [{choices}]{default}{cancelmessage}: ",
errormessage="Invalid input", default=None,
cancel=False, cancelkey='c',
cancelmessage='press {cancelkey} to cancel'):
"""
ask is a shorcut instantiate PickOne and use .ask method
"""
return PickOne(ch... | 21,850 |
def cmc(ctx, scores, evaluation, **kargs):
"""Plot CMC (cumulative match characteristic curve).
graphical presentation of results of an identification task eval, plotting
rank values on the x-axis and the probability of correct identification at
or below that rank on the y-axis. The values for the axis ... | 21,851 |
def error_frame(msg=''):
"""Print debug info
The correct way to do this is to use the logging framework which
exposes all of these things to you, but you can access them using
the Python inspect module
"""
caller_frame = inspect.stack()[1]
frame = caller_frame[0]
frame_info = inspect.ge... | 21,852 |
def test_delete_from(db_results):
"""Tests the delete_from function of the database
"""
for remote in db_results['remote']:
DbManager.use_remote_db = remote
DbManager.query_from_string(
"""DROP TABLE IF EXISTS temp;""", """CREATE TABLE temp(
id in... | 21,853 |
def get_shares(depth):
"""
this is pretty janky, again, but simply grab the list of directories under /mnt/user0, an an unraid-specific shortcut to access shares
"""
rootdir = "/mnt/user0/"
shares = []
pattern = "('\w+')"
with os.scandir(rootdir) as p:
depth -= 1
for entry in... | 21,854 |
def parse_cli_args():
"""Function to parse the command-line arguments for PETRARCH2."""
__description__ = """
PETRARCH2
(https://openeventdata.github.io/) (v. 1.0.0)
"""
aparse = argparse.ArgumentParser(prog='petrarch2',
description=__description__)
sub_parse = ... | 21,855 |
def register_webapi_capabilities(capabilities_id, caps):
"""Register a set of web API capabilities.
These capabilities will appear in the dictionary of available
capabilities with the ID as their key.
A capabilities_id attribute passed in, and can only be registerd once.
A KeyError will be thrown ... | 21,856 |
def _check_eq(value):
"""Returns a function that checks whether the value equals a
particular integer.
"""
return lambda x: int(x) == int(value) | 21,857 |
def query_data(session, agency_code, start, end, page_start, page_stop):
""" Request D2 file data
Args:
session - DB session
agency_code - FREC or CGAC code for generation
start - Beginning of period for D file
end - End of period for D file
page_... | 21,858 |
def test_settings_files():
"""Should load settings from this test files."""
def _callback(action: kuber.CommandAction):
s = action.bundle.settings
assert s.foo and s.foo == s.spam
assert s.bar and s.bar == s.ham
assert s.baz and s.baz == s.eggs
cb = MagicMock()
cb.side_... | 21,859 |
def register_store(store_module, schemes):
"""
Registers a store module and a set of schemes
for which a particular URI request should be routed.
:param store_module: String representing the store module
:param schemes: List of strings representing schemes for
which this store s... | 21,860 |
def ProfitBefTax(t):
"""Profit before Tax"""
return (PremIncome(t)
+ InvstIncome(t)
- BenefitTotal(t)
- ExpsTotal(t)
- ChangeRsrv(t)) | 21,861 |
def scroll(amount_x=0, amount_y=0):
"""Scroll the buffer
Will scroll by 1 pixel horizontall if no arguments are supplied.
:param amount_x: Amount to scroll along x axis (default 0)
:param amount_y: Amount to scroll along y axis (default 0)
:Examples:
Scroll vertically::
microdotphat.... | 21,862 |
def myCommand():
"""
listens to commands spoken through microphone (audio)
:returns text extracted from the speech which is our command
"""
r = sr.Recognizer()
with sr.Microphone() as source:
print('Say something...')
r.pause_threshold = 1
r.adjust_for_ambient_noise(sourc... | 21,863 |
def home():
"""Display the home screen."""
with open("front/home.md") as file:
text = file.read()
st.markdown(text, unsafe_allow_html=True) | 21,864 |
def main():
""" Runs the gamefix, with splash if zenity or cefpython3 is available
"""
if 'iscriptevaluator.exe' in sys.argv[2]:
log.debug('Not running protonfixes for iscriptevaluator.exe')
return
if 'getcompatpath' in sys.argv[1]:
log.debug('Not running protonfixes for getcom... | 21,865 |
def hammer(ohlc_df):
"""returns dataframe with hammer candle column"""
df = ohlc_df.copy()
df["hammer"] = (((df["high"] - df["low"])>3*(df["open"] - df["close"])) & \
((df["close"] - df["low"])/(.001 + df["high"] - df["low"]) > 0.6) & \
((df["open"] - df["low"]... | 21,866 |
def longest_dimension_first(vector, start=(0, 0), width=None, height=None):
"""Generate the (x, y) steps on a longest-dimension first route.
Note that when multiple dimensions are the same magnitude, one will be
chosen at random with uniform probability.
Parameters
----------
vector : (x, y, z... | 21,867 |
def calcPhase(star,time):
"""
Calculate the phase of an orbit, very simple calculation but used quite a lot
"""
period = star.period
phase = time/period
return phase | 21,868 |
def advanced_search():
"""
Get a json dictionary of search filter values suitable for use with the javascript queryBuilder plugin
"""
filters = [
dict(
id='name',
label='Name',
type='string',
operators=['equal', 'not_equal', 'be... | 21,869 |
def rdp_rec(M, epsilon, dist=pldist):
"""
Simplifies a given array of points.
Recursive version.
:param M: an array
:type M: numpy array
:param epsilon: epsilon in the rdp algorithm
:type epsilon: float
:param dist: distance function
:type dist: function with signature ``f(point, sta... | 21,870 |
def secBetweenDates(dateTime0, dateTime1):
"""
:param dateTime0:
:param dateTime1:
:return: The number of seconds between two dates.
"""
dt0 = datetime.strptime(dateTime0, '%Y/%m/%d %H:%M:%S')
dt1 = datetime.strptime(dateTime1, '%Y/%m/%d %H:%M:%S')
timeDiff = ((dt1.timestamp()) - (dt0.t... | 21,871 |
def clear_annotation(doc, annotation):
"""Remove an annotation file if it exists."""
annotation_path = util.get_annotation_path(doc, annotation)
if os.path.exists(annotation_path):
os.remove(annotation_path) | 21,872 |
def iframe_home(request):
""" Página inicial no iframe """
# Info sobre pedidos de fabricação
pedidosFabricacao = models.Pedidofabricacao.objects.filter(
hide=False
).exclude(
fkid_statusfabricacao__order=3
).order_by(
'-fkid_statusfabricacao', 'dt_fim_maturacao'
)
... | 21,873 |
def get_raw_KEGG(kegg_comp_ids=[], kegg_rxn_ids=[], krest="http://rest.kegg.jp",
n_threads=128, test_limit=0):
"""
Downloads all KEGG compound (C) and reaction (R) records and formats them
as MINE database compound or reaction entries. The final output is a tuple
containing a compound dictionary and... | 21,874 |
def inv(n: int, n_bits: int) -> int:
"""Compute the bitwise inverse.
Args:
n: An integer.
n_bits: The bit-width of the integers used.
Returns:
The binary inverse of the input.
"""
# We should only invert the bits that are within the bit-width of the
# integers we use. W... | 21,875 |
def _render_flight_addition_page(error):
"""
Helper to render the flight addition page
:param error: Error message to display on the page or None
:return: The rendered flight addition template
"""
return render_template("flights/add.html",
airlines=list_airlines(),
... | 21,876 |
def get_node_index(glTF, name):
"""
Return the node index in the glTF array.
"""
if glTF.get('nodes') is None:
return -1
index = 0
for node in glTF['nodes']:
if node['name'] == name:
return index
index += 1
return -1 | 21,877 |
def online_user_count(filter_user=None):
"""
Returns the number of users online
"""
return len(_online_users()) | 21,878 |
def get_latest_version_url(start=29, template="http://unicode.org/Public/cldr/{}/core.zip"):
"""Discover the most recent version of the CLDR dataset.
Effort has been made to make this function reusable for other URL numeric URL schemes, just override `start` and
`template` to iteratively search for the latest vers... | 21,879 |
def test_field_validator__init_invalid_value_doesnt_crash():
"""Don't crash if an invalid value is set for a field in the constructor."""
class Class(binobj.Struct):
text = fields.StringZ(validate=alnum_validator)
struct = Class(text="!")
with pytest.raises(errors.ValidationError):
str... | 21,880 |
def delete_file(filename):
"""Remove a file"""
filename = os.path.basename(filename)
# FIXME: possible race condition
if os.path.exists(secure_path(cagibi_folder, filename)) and filename in files_info:
os.remove(secure_path(cagibi_folder, filename))
del files_info[filename]
... | 21,881 |
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
level = 0
if name.startswith('.'):
... | 21,882 |
def publish():
"""
The main render script.
"""
num_w = 56
black_list = Blacklist()
valid_data = construct_data_dirs(black_list)
print(valid_data)
print("Publishing segments: ")
num_segments = []
if E('errors.txt'):
os.remove('errors.txt')
try:
multiprocessin... | 21,883 |
def sanitize_filename(filename, replacement='_', max_length=200):
"""compute basename of filename. Replaces all non-whitelisted characters.
The returned filename is always a basename of the file."""
basepath = os.path.basename(filename).strip()
sane_fname = re.sub(r'[^\w\.\- ]', replacement, basepath... | 21,884 |
def get_image_links_from_imgur(imgur_url):
"""
Given an imgur URL, return a list of image URLs from it.
"""
if 'imgur.com' not in imgur_url:
raise ValueError('given URL does not appear to be an imgur URL')
urls = []
response = requests.get(imgur_url)
if response.status_code != 200:
... | 21,885 |
def test_get_versions_for_npm_package_deprecated_package():
"""Test basic behavior of the function get_versions_for_npm_package."""
package_versions = get_versions_for_npm_package("nsp")
assert package_versions is not None | 21,886 |
def filter_ignored_images(y_true, y_pred, classification=False):
""" Filter those images which are not meaningful.
Args:
y_true: Target tensor from the dataset generator.
y_pred: Predicted tensor from the network.
classification: To filter for classification or
regression.
... | 21,887 |
def context_data_from_metadata(metadata):
""" Utility function transforming `metadata` into a context data dictionary.
Metadata may have been encoded at the client by `metadata_from_context_data`, or
it may be "normal" GRPC metadata. In this case, duplicate values are allowed;
they become a list in the... | 21,888 |
def open_debug_and_training_data(t, ids, training_data_path):
"""Open an concatenate the debugging and training data"""
debug_files = {
tag: glob.glob(os.path.join(path, '*.pkl'))
for tag, path in ids.items()
}
# open training
training_ds = xr.open_dataset(training_data_path)
t... | 21,889 |
def plot_results_fit(
xs,
ys,
covs,
line_ax,
lh_ax=None,
outliers=None,
auto_outliers=False,
fit_includes_outliers=False,
report_rho=False,
):
"""Do the fit and plot the result.
Parameters
----------
sc_ax : axes to plot the best fit line
lh_ax : axes to plot th... | 21,890 |
def check_for_features(cmph5_file, feature_list):
"""Check that all required features present in the cmph5_file. Return
a list of features that are missing.
"""
aln_group_path = cmph5_file['AlnGroup/Path'][0]
missing_features = []
for feature in feature_list:
if feature not in cmph5_fil... | 21,891 |
def output_gtif(bandarr, cols, rows, outfilename, geotransform, projection, no_data_value=-99, driver_name='GTiff', dtype=GDT_Float32):
"""
Create a geotiff with gdal that will contain all the bands represented
by arrays within bandarr which is itself array of arrays. Expecting bandarr
to be of shape (B... | 21,892 |
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: psl2chain.py 2901 2010-04-13 14:38:07Z andreas $",
... | 21,893 |
def inverse(a: int, b: int) -> int:
"""
Calculates the modular inverse of a in b
:param a:
:param b:
:return:
"""
_, inv, _ = gcd_extended(a, b)
return inv % b | 21,894 |
def build_md2po_events(mkdocs_build_config):
"""Build dinamically those mdpo events executed at certain moments of the
Markdown file parsing extrating messages from pages, different depending on
active extensions and plugins.
"""
_md_extensions = mkdocs_build_config['markdown_extensions']
md_ex... | 21,895 |
def base_build(order, group, dry_run):
"""Builds base (dependence) packages.
This command builds dependence packages (packages that are not
Bob/BEAT packages) in the CI infrastructure. It is **not** meant to
be used outside this context.
"""
condarc = select_user_condarc(
paths=[os.cu... | 21,896 |
def printExternalClusters(newClusters, extClusterFile, outPrefix,
oldNames, printRef = True):
"""Prints cluster assignments with respect to previously defined
clusters or labels.
Args:
newClusters (set iterable)
The components from the graph G, defining the Pop... | 21,897 |
def is_three(x):
"""Return whether x is three.
>>> search(is_three)
3
"""
return x == 3 | 21,898 |
def get_task_id(prefix, path):
"""Generate unique tasks id based on the path.
:parma prefix: prefix string
:type prefix: str
:param path: file path.
:type path: str
"""
task_id = "{}_{}".format(prefix, path.rsplit("/", 1)[-1].replace(".", "_"))
return get_unique_task_id(task_id) | 21,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.