content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def flatten(input_ds, output_ds, lax_mode=False, _copy_data=True, copy_slices=None):
"""Flatten an input NetCDF dataset and write the result in an output NetCDF dataset.
For variable that are too big to fit in memory, the optional "copy_slices" input allows to copy some or all of the
variables in slices.
... | 5,351,000 |
def validate(i):
"""
Input: {
model_name - model name:
earth
lm
nnet
party
... | 5,351,001 |
def cluster_absent(
name='localhost',
quiet=None):
"""
Machine is not running as a cluster node
quiet:
execute the command in quiet mode (no output)
"""
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __salt__['crm... | 5,351,002 |
def link_symbols_in_code_blocks(path, blocks, symbols):
"""Link symbols appearing a sequence of blocks."""
return [link_symbols_in_code_block(path, block, symbols)
for block in blocks] | 5,351,003 |
def cem_model_factory(
env, network=mlp, network_params={},
input_shape=None,
min_std=1e-6, init_std=1.0, adaptive_std=False,
model_file_path=None, name='cem'):
"""
Model for gradient method
"""
def build_graph(model, network=network,
input_shape=inpu... | 5,351,004 |
def get_job(job_id: UUID) -> Job:
"""
Get job by ID.
Args:
job_id (UUID): ID of the job to be returned.
Returns:
Job
"""
return JobRepository.get_one_by_id(model_id=job_id) | 5,351,005 |
def set_job_dirs():
"""Sets job directories based on env variables set by Vertex AI."""
model_dir = os.getenv('AIP_MODEL_DIR', LOCAL_MODEL_DIR)
if model_dir[0:5] == 'gs://':
model_dir = model_dir.replace('gs://', '/gcs/')
checkpoint_dir = os.getenv('AIP_CHECKPOINT_DIR', LOCAL_CHECKPOINT_DIR... | 5,351,006 |
def localize_datetime(input_df, timezone=DEFAULT_TIMEZONE,
tms_gmt_col=DEFAULT_TMS_GMT_COL):
"""
Convert datetime column from UTC to another timezone.
"""
tmz = pytz.timezone(timezone)
df = input_df.copy()
return (df.set_index(tms_gmt_col)
.tz_localize(pytz.ut... | 5,351,007 |
def get_available_port() -> int:
"""Finds and returns an available port on the system."""
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.bind(('', 0))
_, port = sock.getsockname()
return int(port) | 5,351,008 |
def prettyprint_float(val, digits):
"""Print a floating-point value in a nice way."""
format_string = "%." + f"{digits:d}" + "f"
return (format_string % val).rstrip("0").rstrip(".") | 5,351,009 |
def year_page(archive_id: str, year: int) -> Any:
"""
Get year page for archive.
Parameters
----------
archive : str
Must be an arXiv archive identifier.
year: int
Must be a two or four digit year.
Returns
-------
dict
Search result response data.
int
H... | 5,351,010 |
def test_delete_artifact_store_works(tmp_path: str) -> None:
"""Test delete_artifact_store works as expected."""
Repo.init(tmp_path)
Repository.init_repo(str(tmp_path))
repo = Repository(str(tmp_path))
local_service = repo.get_service()
artifact_store_dir = os.path.join(tmp_path, "test_store")
... | 5,351,011 |
def vert_polyFit2(data, z, bin0, step=1, deg=2):
"""
Trying to use the vertical polynomial fit to clean up the data
not reallly sure about what im doing though
"""
data = np.squeeze(data)
z = np.squeeze(z)
dz = np.nanmean(np.gradient(np.squeeze(z)))
bin1 = int(np.ceil(bin0/dz))
fi... | 5,351,012 |
def is_downloadable(url):
"""
Does the url contain a downloadable resource
"""
h = requests.head(url, allow_redirects=True)
header = h.headers
content_type = header.get('content-type')
print content_type
if 'text' in content_type.lower():
return False
if 'html' in content_typ... | 5,351,013 |
def _main(argv):
"""Command-line interface."""
parser = ArgumentParser()
parser.add_argument('--quiet', action='store_const', default=False,
const=True,
help='Do not display debugging messages')
parser.add_argument('--dbfile', nargs=1, default='imdb.zip',
... | 5,351,014 |
def dataframe_is_one_query_target_pair(dataframe):
"""
make sure there is only one query sequence and reference sequence in the
given dataframe. Used to check that we aren't aggregating % identity
numbers across bin alignment pairs.
:param dataframe:
:return:
"""
num_query_bins = len(d... | 5,351,015 |
def update_api_key(
self,
name: str,
permission: str,
expiration: int,
active: bool,
key: str = None,
description: str = None,
ip_list: str = None,
) -> bool:
"""Update existing API key on Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
... | 5,351,016 |
def cleanGender(x):
"""
This is a helper funciton that will help cleanup the gender variable.
"""
if x in ['female', 'mostly_female']:
return 'female'
if x in ['male', 'mostly_male']:
return 'male'
if x in ['couple'] :
return 'couple'
else:
return 'unknownGe... | 5,351,017 |
def get_servers():
"""
Retrieve all the discord servers in the database
:return: List of servers
"""
session = Session()
servers = session.query(Server).all()
return servers | 5,351,018 |
def wait_till_postgres_responsive(url):
"""Check if something responds to ``url`` """
engine = sa.create_engine(url)
conn = engine.connect()
conn.close()
return True | 5,351,019 |
def get_string_display(attr1, attr2, helper1, helper2, attribute_mode):
"""
get the attribute mode for string
attribute mode can be:
'base', 'full', 'partial', 'masked'
Note that some attribute does not have partial mode, in this case, partial mode will return masked mode
Remeber to call has_par... | 5,351,020 |
def is_doi(identifier: str) -> bool:
"""Validates if identifier is a valid DOI
Args:
identifier (str): potential doi string
Returns:
bool: true if identifier is a valid DOI
"""
doi_patterns = [
r"(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\'])\S)+)",
r"(10.\d{4,9}/[-._... | 5,351,021 |
def meshgrid_flatten(*X):
"""
Functionally same as numpy.meshgrid() with different output
format. Function np.meshgrid() takes n 1d ndarrays of size
N_1,...,N_n, and returns X_1,...,X_n n-dimensional arrays of shape
(N_1, N_2,... N_n). This returns instead a 2d array of shape
(N_1*...*N_n, n).... | 5,351,022 |
def transform_scale(
features,
factor: float,
origin: Union[str, list] = "centroid",
mutate: bool = False,
):
"""
Scale a GeoJSON from a given
point by a factor of scaling
(ex: factor=2 would make the GeoJSON 200% larger).
If a FeatureCollection is provided, the origin
point will... | 5,351,023 |
def create_agent(opt):
"""Create an agent from the options model, model_params and model_file.
The input is either of the form "parlai.agents.ir_baseline.agents/IrBaselineAgent"
(i.e. the path followed by the class name) or else just 'IrBaseline' which
assumes the path above, and a class name suffixed w... | 5,351,024 |
def check_version(actver, version, cmp_op):
"""
Check version string of an active module against a required version.
If dev/prerelease tags result in TypeError for string-number comparison,
it is assumed that the dependency is satisfied.
Users on dev branches are responsible for keeping their... | 5,351,025 |
def calculate_efficiency_metrics(pipeline, X, y):
"""
Apply KFold to the given data and calculate the follow metrics for each fold :
- accuracy
- precision
- recall
- f1-score
- confusion matrix
Finally, it will calculate for each metric its mean and standard deviati... | 5,351,026 |
def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict:
""" Returns a DFA accepting the intersection of the DFAs in
input.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs.
Then there is a DFA :math:`A_∧` that runs simultaneously both
... | 5,351,027 |
def change_status(request, page_id):
"""
Switch the status of a page.
"""
perm = PagePermission(request.user).check('change', method='POST')
if perm and request.method == 'POST':
page = Page.objects.get(pk=page_id)
page.status = int(request.POST['status'])
page.invalidate()
... | 5,351,028 |
def str2bytes(s):
"""
Returns byte string representation of product state.
Parameters
----------
s : str
Representation of a product state, in terms of a string.
"""
return bitarray2bytes(str2bitarray(s)) | 5,351,029 |
def find_links(text, image_only=False):
"""
Find Markdown links in text and return a match object.
Markdown links are expected to have the form [some txt](A-url.ext)
or .
Parameters
----------
text : str
Text in which to search for links.
image_only... | 5,351,030 |
def least_one_row(data_frame):
"""
checking at least one row in dataframe
Input: pandas dataframe
Output: True or False
"""
if data_frame:
return True
return False | 5,351,031 |
def get_reference_docs():
"""Create reference documentation from the source code.
A bit like Sphinx autodoc, but using Markdown, and more basic.
Returns a str in Markdown format.
Note that this function is used to build the Dash Slicer chapter
in the Dash docs.
"""
methods = []
props =... | 5,351,032 |
def stop_nova_openstack_compute():
"""Stop the contrail openstack compute service."""
tsn_nodes = []
tor_nodes = []
host = env.host_string
if 'tsn' in env.roledefs:
tsn_nodes = env.roledefs['tsn']
if 'toragent' in env.roledefs:
tor_nodes = env.roledefs['toragent']
if host not... | 5,351,033 |
def generate_label_colors(labels: list, colors: list, palette='Set2'):
"""Matches labels with colors
If there are more labels than colors, repeat and cycle through colors
"""
label_colors = defaultdict(dict)
num_repeats = math.ceil(len(labels) / len(colors))
for label in enumerate(labels):
... | 5,351,034 |
def get_xml_file_path_from_image_name(image_name, xml_dir_or_txt):
"""Retrieve xml filepath from xml dir
Args:
image_name:
xml_dir_or_txt:
Returns:
xml_path:
"""
if os.path.isfile(xml_dir_or_txt):
filepaths = fileio.read_list_from_txt(xml_dir_or_txt, field=-1)
el... | 5,351,035 |
def cancel_command():
"""Removes current reply keyboard"""
SendMessage(context.user.id, "🔹 What's next?", reply_markup=ReplyKeyboardRemove()).webhook() | 5,351,036 |
def index():
"""
View root page function that returns the index page and its data
"""
# getting top headlines in sources
topheadlines_sources = get_sources('top-headlines')
business_sources = get_sources('business')
entertainment_sources = get_sources('entertainment')
title = 'Home - We... | 5,351,037 |
def func(foo):
"""
Parameters:
foo (Foo): ignored
"""
pass | 5,351,038 |
def CheckPrerequisites(_):
"""Verifies that the required resources are present.
Raises NotImplementedError.
"""
# currently only support GCS object storage
# TODO(user): add AWS & Azure support for object storage
if FLAGS.ch_network_test_service_type == STORAGE and FLAGS.cloud != 'GCP':
raise NotImplem... | 5,351,039 |
def start_ltm(tup,
taus,
w=0.1,
add_coh=False,
use_cv=False,
add_const=False,
verbose=False,
**kwargs):
"""Calculate the lifetime density map for given data.
Parameters
----------
tup : datatup... | 5,351,040 |
def manhattan_distance(origin, destination):
"""Return the Manhattan distance between the origin and the destination.
@type origin: Location
@type destination: Location
@rtype: int
>>> pt1 = Location(1,2)
>>> pt2 = Location(3,4)
>>> print(manhattan_distance(pt1, pt2))
4
"""
ret... | 5,351,041 |
def get_release():
"""Get the current release of the application.
By release, we mean the release from the version.json file à la Mozilla [1]
(if any). If this file has not been found, it defaults to "NA".
[1]
https://github.com/mozilla-services/Dockerflow/blob/master/docs/version_object.md
""... | 5,351,042 |
def test_BBPSSW_psi_minus_psi_plus():
"""
psi- psi+
0b0
[ 0. +0.j 0.5+0.j -0.5+0.j 0. +0.j]
0b1
[0.+0.j 0.+0.j 0.+0.j 0.+0.j]
0b10
[0.+0.j 0.+0.j 0.+0.j 0.+0.j]
0b11
[ 0. +0.j 0.5+0.j -0.5+0.j 0. +0.j]
"""
counter = 0
for i in range(100):
... | 5,351,043 |
def add_mclag_member(ctx, domain_id, portchannel_names):
"""Add member MCLAG interfaces from MCLAG Domain"""
db = ctx.obj['db']
entry = db.get_entry('MCLAG_DOMAIN', domain_id)
if len(entry) == 0:
ctx.fail("MCLAG Domain " + domain_id + " not configured, configure mclag domain first")
portcha... | 5,351,044 |
def find_best_resampler(
features_train: pd.DataFrame, labels_train: pd.DataFrame, parameters: Dict
) -> List:
"""Compare several resamplers and find the best one to handle imbalanced labels.
Args:
features_train: Training data of independent features.
labels_train: Training data of next mo... | 5,351,045 |
def grid(dim, num):
"""Build a one-dim grid of num points"""
if dim.type == "categorical":
return categorical_grid(dim, num)
elif dim.type == "integer":
return discrete_grid(dim, num)
elif dim.type == "real":
return real_grid(dim, num)
elif dim.type == "fidelity":
re... | 5,351,046 |
def path(graph, source, target, excluded_edges=None, ooc_types=ooc_types):
""" Path of functions between two types """
if not isinstance(source, type):
source = type(source)
if not isinstance(target, type):
target = type(target)
for cls in concatv(source.mro(), _virtual_superclasses):
... | 5,351,047 |
def is_resource_sufficient(order_ingredients):
"""Return true or false"""
for item in order_ingredients:
if order_ingredients[item]>=resources[item]:
print(f"Sorry not Enough {item} to Make Coffee.")
return False
return True | 5,351,048 |
def get_gh_releases_api(project, version=None):
"""
"""
# https://developer.github.com/v3/auth/
# self.headers = {'Authorization': 'token %s' % self.api_token}
# https://api.github.com/repos/pygame/stuntcat/releases/latest
repo = get_repo_from_url(project.github_repo)
if not repo:
re... | 5,351,049 |
def set_source(code, filename='__main__.py', sections=False, independent=False,
report=None):
"""
Sets the contents of the Source to be the given code. Can also be
optionally given a filename.
Args:
code (str): The contents of the source file.
filename (str): The filename... | 5,351,050 |
def test_make_tiles():
"""Test make_tiles"""
tiles = make_tiles()
assert len(tiles) == 104
assert len(list(filter(lambda tile: tile[0] == 'R', tiles))) == 26
assert len(list(filter(lambda tile: tile[1] == 1, tiles))) == 8
assert len(
list(filter(lambda tile: tile[0] == 'K' and tile[1] =... | 5,351,051 |
def weak_move(board):
"""Weak AI - makes a random valid move.
Args:
board: (Board) The game board.
Returns:
Array: Our chosen move.
"""
valid_moves = _get_moves(board, Square.black)
# Return a random valid move
our_move = valid_moves[random.randrange(0, len(valid_moves))]
logging.info('Weak AI... | 5,351,052 |
def flow_to_image(flow):
"""
Input:
flow:
Output:
Img array:
Description:
Transfer flow map to image.
Part of code forked from flownet.
"""
out = []
maxu = -999.
maxv = -999.
minu = 999.
minv = 999.
maxrad = -1
for i in range(flow.shape[0])... | 5,351,053 |
def set_engines(N=0):
"""
Called only when read_file is called.
Sets the MC engines that are used in verification according to
if there are 4 or 8 processors. if if_no_bip = 1, we will not use any bip and reachx engines
"""
global reachs,pdrs,sims,intrps,bmcs,n_proc,abs_ratio,ifbip,bmcs1, if_no_... | 5,351,054 |
def parse_model_value(value, context):
"""
do interpolation first from context,
"x is {size}" with size = 5 will be interpolated to "x is 5"
then return interpolated string
:param value:
:param context:
:return:
"""
return value.format(**context) | 5,351,055 |
def apply_tropomi_operator(
filename,
n_elements,
gc_startdate,
gc_enddate,
xlim,
ylim,
gc_cache,
build_jacobian,
sensi_cache,
):
"""
Apply the tropomi operator to map GEOS-Chem methane data to TROPOMI observation space.
Arguments
filename [str] : TR... | 5,351,056 |
def load_configuration(yaml: yaml.ruamel.yaml.YAML, filename: str) -> DictLike:
"""Load an analysis configuration from a file.
Args:
yaml: YAML object to use in loading the configuration.
filename: Filename of the YAML configuration file.
Returns:
dict-like object containing the loa... | 5,351,057 |
def device_list(request):
"""
:param request:
:return:
"""
device_list = True
list = Device.objects.all()
return render(request, "back/device_list.html", locals()) | 5,351,058 |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // 50))
print(lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr | 5,351,059 |
def L008_eval(segment, raw_stack, **kwargs):
""" This is a slightly odd one, because we'll almost always evaluate from a point a few places
after the problem site """
# We need at least two segments behind us for this to work
if len(raw_stack) < 2:
return True
else:
cm1 = raw_stack[-... | 5,351,060 |
def overwrite_ruffus_args(args, config):
"""
:param args:
:param config:
:return:
"""
if config.has_section('Ruffus'):
cmdargs = dict()
cmdargs['draw_horizontally'] = bool
cmdargs['flowchart'] = str
cmdargs['flowchart_format'] = str
cmdargs['forced_tasks']... | 5,351,061 |
def read_sfr_df():
"""Reads and prepares the sfr_df
Parameters:
Returns:
sfr_df(pd.DataFrame): dataframe of the fits file mosdef_sfrs_latest.fits
"""
sfr_df = read_file(imd.loc_sfrs_latest)
sfr_df['FIELD_STR'] = [sfr_df.iloc[i]['FIELD'].decode(
"utf-8").rstrip() for i in range(le... | 5,351,062 |
def redshift(x, vo=0., ve=0.,def_wlog=False):
"""
x: The measured wavelength.
v: Speed of the observer [km/s].
ve: Speed of the emitter [km/s].
Returns:
The emitted wavelength l'.
Notes:
f_m = f_e (Wright & Eastman 2014)
"""
if np.isnan(vo):
vo = 0 # propagate ... | 5,351,063 |
def overlay_spectra_plot(array, nrow=5,ncol=5,**kwargs):
"""
Overlay spectra on a collapsed cube.
Parameters
----------
array : 3D numpy array
nrow : int
Number of rows in the figure.
ncol : int
Number of columns in the figure.
**kwargs :... | 5,351,064 |
def digest_from_rsa_scheme(scheme, hash_library=DEFAULT_HASH_LIBRARY):
"""
<Purpose>
Get digest object from RSA scheme.
<Arguments>
scheme:
A string that indicates the signature scheme used to generate
'signature'. Currently supported RSA schemes are defined in
`securesystemslib.keys.RS... | 5,351,065 |
def getconfig(filename):
"""
1. Checks if the config file exists.
2. If not, creates it with the content in default_config.
3. Reads the config file and returns it.
Returns False in case of errors.
"""
global default_config
if os.path.exists(filename):
configfile = ope... | 5,351,066 |
def table(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", transl... | 5,351,067 |
def _ev_match(
output_dir, last_acceptable_entry_index, certificate, entry_type,
extra_data, certificate_index):
"""Matcher function for the scanner. Returns the certificate's hash if
it is a valid, non-expired, EV certificate, None otherwise."""
# Only generate whitelist for non-precertific... | 5,351,068 |
def axis_ratio_disklike(scale=0.3, truncate=0.2):
"""Sample (one minus) the axis ratio of a disk-like galaxy from the Rayleigh distribution
Parameters
----------
scale : float
scale of the Rayleigh distribution; the bigger, the smaller the axis ratio
truncate : float
the minimum val... | 5,351,069 |
def rk4(y0, t0, te, N, deriv, filename=None):
"""
General RK4 driver for
N coupled differential eq's,
fixed stepsize
Input:
- y0: Vector containing initial values for y
- t0: Initial time
- te: Ending time
- N: Number of steps
- deriv: See rk4_st... | 5,351,070 |
def create_txt_substitute_record_rule_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]:
"""
Args:
client: Client object
args: Usually demisto.args()
Returns:
Outputs
"""
name = args.get('name')
rp_zone = args.get('rp_zone')
comment = args.get('comment')
... | 5,351,071 |
def pot_rho_linear(SP, t, rho0=1025, a=2e-4, b=7e-4, SP0=35, t0=15):
"""
Potential density calculated using a linear equation of state:
Parameters
----------
SP : array-like
Salinity [g/kg]
t : array-like
Temperature [°C]
rho0 : float, optional
Constant ... | 5,351,072 |
def oembed(url, params=""):
"""
Render an OEmbed-compatible link as an embedded item.
:param url: A URL of an OEmbed provider.
:return: The OEMbed ``<embed>`` code.
"""
# Note: this method isn't currently very efficient - the data isn't
# cached or stored.
kwargs = dict(urlparse.parse_... | 5,351,073 |
async def create_assc(conn : asyncpg.Connection, name : str, type : str,
base : str, leader : int) -> Association:
"""Create an association with the fields given.
type must be 'Brotherhood','College', or 'Guild'.
"""
psql = """
SELECT assc_id
FROM associations
... | 5,351,074 |
def ssx_plot(data):
"""
Plot the current list of ints so far. Data requires the following keys
* xdim (int) X dimension for the plot
* ydim (int) Y dimension for the plot
* int_indices (list of ints) list of int 'hits' to light up on the plot
* plot_name (path) full filename to s... | 5,351,075 |
def filter_tof_to_csr(
tof_slices: np.ndarray,
push_indices: np.ndarray,
tof_indices: np.ndarray,
push_indptr: np.ndarray,
) -> tuple:
"""Get a CSR-matrix with raw indices satisfying push indices and tof slices.
Parameters
----------
tof_slices : np.int64[:, 3]
Each row of the a... | 5,351,076 |
def get_path_from_query_string(req):
"""Gets path from query string
Args:
req (flask.request): Request object from Flask
Returns:
path (str): Value of "path" parameter from query string
Raises:
exceptions.UserError: If "path" is not found in query string
"""
if req.arg... | 5,351,077 |
def test_cray_bos_sessiontemplateteplate_list(cli_runner, rest_mock):
""" Test cray bos sessiontemplatetemplate list """
runner, cli, config = cli_runner
result = runner.invoke(
cli,
['bos', 'sessiontemplatetemplate', 'list']
)
assert result.exit_code == 0
data = json.loads(resul... | 5,351,078 |
def entropy_grassberger(n, base=None):
""""
Estimate the entropy of a discrete distribution from counts per category
n: array of counts
base: base in which to measure the entropy (default: nats)
"""
N = np.sum(n)
entropy = np.log(N) - np.sum(n*scipy.special.digamma(n+1e-20))/N
if base:... | 5,351,079 |
def beaching_kernel(particle, fieldset, time):
"""
Author: Victor Onink, 25/01/2022
"""
# Beaching
if particle.beach == 0:
dist = fieldset.distance2shore[time, particle.depth, particle.lat, particle.lon]
if dist < fieldset.Coastal_Boundary:
if ParcelsRandom.uniform(0, 1) > fieldset.p_beach:
... | 5,351,080 |
def get_param_layout():
"""Get layout for causality finding parameters definition window
Parameters
----------
Returns
-------
`List[List[Element]]`
Layout for causality finding parameters window
"""
box = [
[
sg.Text('Parameters')
],... | 5,351,081 |
def senti_histplot(senti_df):
"""histogram plot for sentiment"""
senti_hist = (
alt.Chart(senti_df)
.mark_bar()
.encode(alt.Y(cts.SENTI, bin=True), x="count()", color=cts.SENTI,)
.properties(height=300, width=100)
).interactive()
return senti_hist | 5,351,082 |
def pd_df_sampling(df, coltarget="y", n1max=10000, n2max=-1, isconcat=1):
"""
DownSampler
:param df:
:param coltarget: binary class
:param n1max:
:param n2max:
:param isconcat:
:return:
"""
df1 = df[df[coltarget] == 0].sample(n=n1max)
n2max = len(df[df[coltarget] == 1]) ... | 5,351,083 |
def _build_parser():
"""Build parser object."""
from functools import partial
from pathlib import Path
from argparse import (
ArgumentParser,
ArgumentDefaultsHelpFormatter,
)
from packaging.version import Version
from .version import check_latest, is_flagged
from niworkfl... | 5,351,084 |
def get_deliverer(batch_size, max_staleness, session):
""" Helper function to returns the correct deliverer class for the
batch_size and max_stalennes parameters
"""
if batch_size < 1:
return SimpleDeliverer(session)
else:
return BatchDeliverer(session, batch_size, max_staleness) | 5,351,085 |
def trace_fweight_deprecated(fimage, xinit, ltrace=None, rtraceinvvar=None, radius=3.):
""" Python port of trace_fweight.pro from IDLUTILS
Parameters:
-----------
fimage: 2D ndarray
Image for tracing
xinit: ndarray
Initial guesses for x-trace
invvar: ndarray, optional
Inverse ... | 5,351,086 |
def home():
"""Renders the card page."""
cardStack = model.CardStack()
return render_template(
'cards.html',
title ='POSTIN - Swipe',
cardSet = cardStack.cardList,
year=datetime.now().year,
) | 5,351,087 |
def uncompress(filename: str, path: str = os.getcwd()) -> None:
"""Uncompress a tar file
Args:
filename: a tar file (tar, tgz, ...)
path: where the filename will be uncompressed
Example:
>>> import robotathome as rh
>>> rh.uncompress('~/WORKSPACE/Robot@Home2_db.tgz... | 5,351,088 |
def index(request):
"""
User profile page.
"""
user = request.user
profile = user.userprofile
context = collect_view_data(request, 'profile')
context['user'] = user
context['profile'] = profile
context['uform'] = UserForm(request, request.user, init=True)
context['upform'] = User... | 5,351,089 |
def user_confirm_email(token):
"""Confirm a user account using his email address and a token to approve.
Parameters
----------
token : str
The token associated with an email address.
"""
try:
email = ts.loads(token, max_age=86400)
except Exception as e:
logger.error(... | 5,351,090 |
def num_zeros_end(num):
"""
Counts the number of zeros at the end
of the number 'num'.
"""
iszero = True
num_zeros = 0
i = len(num)-1
while (iszero == True) and (i != 0):
if num[i] == "0":
num_zeros += 1
elif ... | 5,351,091 |
def batch_summarize(texts: List[str]) -> List[str]:
"""Summarizes the texts (local mode).
:param texts: The texts to summarize.
:type texts: List[str]
:return: The summarized texts.
:rtype: List[str]
"""
if _summarizer is None:
load_summarizer()
assert _summarizer is not None... | 5,351,092 |
def test_list_posts_of_feed(
client: testclient.TestClient, db_session: sa.orm.Session,
):
"""
Test list posts of a specific RSS feed.
"""
with factories.single_commit(db_session):
post_1 = factories.PostFactory()
factories.PostFactory()
response = client.get(f"/api/feeds/{post_... | 5,351,093 |
def _reader_bytes(handle, count=None, chunk_size=1024):
"""
Read a given number of bytes
Examples:
>>> tmp_dir = getfixture('tmpdir')
>>> tmp_file = tmp_dir.join('test')
>>> tmp_file.write('abcdefghi')
>>> handle = tmp_file.open()
>>> handle.seek(4)
4
>>> list(_reader_bytes(ha... | 5,351,094 |
def test_fcos_head_get_bboxes():
"""Test fcos head get_bboxes() in ort."""
fcos_model = fcos_config()
s = 128
img_metas = [{
'img_shape_for_onnx': torch.Tensor([s, s]),
'img_shape': (s, s, 3),
'scale_factor': np.ones(4),
'pad_shape': (s, s, 3)
}]
cls_scores = [
... | 5,351,095 |
def dbg(message: str) -> None:
"""Prints a debug-level log message.
"""
_log(co.GRAY, "🖝 ", message) | 5,351,096 |
def make_final_legend():
"""Makes the legend of figure 4 of the publication."""
fig = plt.figure(figsize=(10, 1))
me.get_final_graph_legend(fig)
fig.savefig("cumul_shuttle_leg.pdf") | 5,351,097 |
def Vp_estimation(z, T, x, g=param.g):
""" Estimation of the Vp profile from the results of solving the system.
"""
DT = T - T[-1] # temperature variation in the layer compared to T[ICB]
drhoP = -param.rhoH**2. * g * z / Seismic_observations.calcK(z)
drhoT = -param.rhoH * param.alpha * DT # *(Mp*... | 5,351,098 |
def ShowAllSchedUsage(cmd_args=None):
""" Prints the sched usage information for all threads of each task
"""
out_str = ''
for taskp in kern.tasks:
ShowTask([unsigned(taskp)])
print ShowAllSchedUsage.header
for actp in IterateQueue(taskp.threads, 'thread *', 'task_threads'):
... | 5,351,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.