content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_possible_zeros(coefficients: list) -> list:
"""Rational Zeros Theorem possible zeros of a polynomial function.
Args:
coefficients (list): The coefficients of a polynomial function,
in order of degree including all from a_n to a_0.
Returns:
list: A list containing all possib... | 2,400 |
def read_aa_traj(ns):
"""Read atomistic trajectory
ns creates:
aa_universe
"""
print("Reading All Atom (AA) trajectory")
ns.aa_universe = mda.Universe(ns.aa_tpr_filename, ns.aa_traj_filename,
in_memory=True, refresh_offsets=True,
... | 2,401 |
def verify_province():
"""
Verify if user's province is British Columbia.
:precondition: User's input must be a string
:postcondition: Correctly verify if user's province is British Columbia
:raise ValueError if the user enters an empty string when prompted for input
"""
try:
# Ask ... | 2,402 |
def view() -> pn.Column:
"""# Bootstrap Dashboard Page.
Creates a Bootstrap Dashboard Page with a Chart and a Table
- inspired by the [GetBoostrap Dashboard Template]
(https://getbootstrap.com/docs/4.4/examples/dashboard/)
- implemented using the `awesome_panel' Python package and in partic... | 2,403 |
def load_tests(loader, tests, ignore):
"""
Creates a ``DocTestSuite`` for each module named in ``DOCTEST_MODULES``
and adds it to the test run.
"""
for module in DOCTEST_MODULES:
tests.addTests(doctest.DocTestSuite(module))
return tests | 2,404 |
def main(departure, arrival, next, transport, verbose):
""" Search trips with Trainline and returns it in csv """
# Get current datetime > from_date
from_date_obj = datetime.now()
# Decode duration (ex : 1day => timedelta(days=1))
delta = _decode_next_param(next)
# Calculate the end date > to... | 2,405 |
def run_all(names, args):
"""
Function is called by main program
"""
print(BANNER)
valid_accounts = check_storage_accounts(names, args.threads,
args.nameserver)
if valid_accounts and not args.quickscan:
brute_force_containers(valid_accounts, a... | 2,406 |
def buildGeneMap(identifiers, separator="|"):
"""build map of predictions to genes.
Use an identifier syntax of species|transcript|gene. If none is
given, all transcripts are assumed to be from their own gene.
"""
map_id2gene, map_gene2ids = {}, {}
for id in identifiers:
f = id.spli... | 2,407 |
def flexible_set_value(object, value, attr=True, null_others=True):
"""Given an object, set either value_int, value_str, or value_float as appropriate.
:param attr: if True, the attribute is set. If False, the dictionary value is set instead.
:param null_others: if True, the remaining values are set to Non... | 2,408 |
def get_kline(symbol, end_date, freq, start_date=None, count=None):
"""获取K线数据
:param symbol: str
聚宽标的代码
:param start_date: datetime
截止日期
:param end_date: datetime
截止日期
:param freq: str
K线级别,可选值 ['1min', '5min', '30min', '60min', 'D', 'W', 'M']
:param count: int
... | 2,409 |
def create_trial_instance(
trial_def: Type[det.Trial],
checkpoint_dir: str,
config: Optional[Dict[str, Any]] = None,
hparams: Optional[Dict[str, Any]] = None,
) -> det.Trial:
"""
Create a trial instance from a Trial class definition. This can be a useful
utility for debugging your trial logi... | 2,410 |
def test_duplicate_submission(app, pg_driver, cgci_blgsp, submitter):
"""
Make sure that concurrent transactions don't cause duplicate submission.
"""
data = {
"type": "experiment",
"submitter_id": "BLGSP-71-06-00019",
"projects.id": "daa208a7-f57a-562c-a04a-7a7c77542c98"
}
... | 2,411 |
def magnitude(number: SnailNumber) -> int:
"""Calculates the magnitude of asnail number
Args:
number (SnailNumber): input number
Returns:
(int): mangitude
Examples:
>>> magnitude([[1, 1], [2, 2]])
35
>>> magnitude([[[[0,7],4],[[7,8],[6,0]]],[8,1]])
1384... | 2,412 |
def _load_model_from_tarball(tarball_path, gpg_home_dir):
"""Load a model from a tarball
Args:
tarball_path: a path to a model gzipped tar file
gpg_home_dir: home directory for gpg to verify signed model (e.g. path/to/.gnupg)
Returns:
something of type SerializableModel
"""
... | 2,413 |
def read_csv():
"""
Reads data from .csv file
"""
# reads data and stores it into dataframe
df = pd.read_csv('train_set', sep=',')
df_test = pd.read_csv('test_set', sep=',')
split_dataframe(df, df_test) | 2,414 |
def strip_begin_end_key(key) :
"""
Strips off newline chars, BEGIN PUBLIC KEY and END PUBLIC KEY.
"""
return key.replace("\n", "")\
.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "") | 2,415 |
def add_expdvr(npoints: int, qmin: float, qmax: float) -> DVRSpecification:
"""Register a new exponential DVR
Args:
npoints (int): number of grid points
qmin (float): minimal x value
qmax (float): maximal x value
"""
return DVRSpecification("ExponentialDVR", npoints, qmin, qmax) | 2,416 |
def main():
"""Main CLI function.
:rtype: int
:returns: exit code, which is sum of all exit codes
"""
opts, args = parse_args()
setup_logging(opts.verbose)
if opts.show_configs:
print_configs()
return 0
build_env = os.environ.copy()
chpl_misc = get_chpl_misc(opts, ... | 2,417 |
def write_markdown(path, content):
""" Write gathered metadata in the markdown format """
to_print = ""
if content['setup']:
to_print += "# Setup\n" + content['setup'] + '\n\n'
if content['action'] or content['expected']:
to_print += "# Test\n\n"
if content['action']:
... | 2,418 |
def _add_rule_pattern_constraints_to_table(decoder, table):
"""Adds an additional column to the given table, defining
additional constraints assumed by rule patterns in rows.
"""
global _trace
if _trace and _process_table(table):
print "*** processing table: %s ***" % table.name
constra... | 2,419 |
def sync_now(r, **attr):
"""
Manual synchronization of a repository
@param r: the S3Request
@param attr: controller options for the request
"""
T = current.T
auth = current.auth
response = current.response
rheader = attr.get("rheader", None)
if rheader:
rhe... | 2,420 |
def ensure_valid_positions(epochs):
"""Make sure the EEG channel positions are valid.
If channels are bipolar and referenced to M1 or M2, rename them to just the
first derivation so that autoreject can be used.
"""
ch_names = epochs.info['ch_names']
if all(['-' not in c for c in ch_names]): # ... | 2,421 |
def checkdnsrr():
"""Check DNS records corresponding to a given
Internet host name or IP address"""
return NotImplementedError() | 2,422 |
def test_get_sub_by_id(session):
"""ASTM Compliance Test: DSS0030_E_GET_SUB_BY_ID."""
resp = session.get('/subscriptions/{}'.format(SUB_ID))
assert resp.status_code == 200, resp.content
data = resp.json()
assert data['subscription']['id'] == SUB_ID
assert data['subscription']['notification_index'] == 0
a... | 2,423 |
def get_horizontal_rainbow_00():
"""
Returns the main horizontal rainbow
Programs that use this function:
- Diagonal Ripple 1
- Diagonal Ripple 2
- Diagonal Ripple 3
- Diagonal Ripple 4
- Double Ripple 1
- Double Ripple 2
- Double Ripple 3
- D... | 2,424 |
def check_sweep(oDesign, setup_name, sweepname):
"""
Check that SweepName is in the SetupName. If not raise an exception.
Parameters
----------
oDesign : pywin32 COMObject
The HFSS oDesign object upon which to operate.
SetupName : str
Name of HFSS setup to use, for example "Setu... | 2,425 |
def xml_attr_or_element(xml_node, name):
""" Attempt to get the value of name from the xml_node. This could be an attribute or
a child element.
"""
attr_val = xml_node.get(name, None)
if attr_val is not None:
return attr_val.encode('utf-8').strip()
for child in xml_node.getchildren()... | 2,426 |
def kmeans_init_centroids(x_array, num_centroids_K):
"""
This function initializes K centroids that are to be used in K-means on the dataset x_array.
Parameters
----------
x_array : array_like
The dataset of size (m x n).
num_centroids_K : int
The number of clusters.
Retur... | 2,427 |
def get_coinbase_candle_url(url, timestamp_from, pagination_id):
"""Get Coinbase candle URL."""
start = timestamp_from.replace(tzinfo=None).isoformat()
url += f"&start={start}"
if pagination_id:
url += f"&end={pagination_id}"
return url | 2,428 |
def part2():
"""This view will be at the path ``/part2``"""
return "Part 2" | 2,429 |
def create_strings_from_file(filename, count):
"""
Create all strings by reading lines in specified files
"""
strings = []
with open(filename, 'r') as f:
lines = [l.strip()[0:200] for l in f.readlines()]
if len(lines) == 0:
raise Exception("No lines could be read in... | 2,430 |
def drive_around(a_th_gld=1.2):
"""
Function that implements the logic with which the robot will decide to navigate in 2D space, it is essentially based on the (frontal and lateral)
distance values of the golden tokens obtained by find_obstacles()
Args:
dist_left (float): distance of the closest golden token o... | 2,431 |
def a_request(session_request):
"""AnonymousUser request"""
session_request.user = AnonymousUser()
return session_request | 2,432 |
def main():
"""
Connect to a generic device and then commandeer that connection
Generally this would be used for connecting to a terminal server, then doing *something* to
connect to one of its downstream devices (i.e. access terminal server port 123 or whatever).
Once on the console of the downstr... | 2,433 |
def subplot_index(nrow, ncol, k, kmin=1):
"""Return the i, j index for the k-th subplot."""
i = 1 + (k - kmin) // ncol
j = 1 + (k - kmin) % ncol
if i > nrow:
raise ValueError('k = %d exceeds number of rows' % k)
return i, j | 2,434 |
def save():
"""
-- opens game_save.txt and writes over the old file. writes each players values to the document inorder
-- to save them which will bve read when loading. (tries to adda score to the player inorder to make sure that there
-- are no more than 10 elements in each score array, if array i... | 2,435 |
def read_transport_maps(input_dir, ids=None, time=None):
"""
Find and parse all transport maps in a directory.
Returns a list containing the transport maps and start/end timepoints.
Parameters
----------
input_dir : str
The directory in which to look for transport maps.
Alternat... | 2,436 |
def _check_parents(item):
"""Check parents where all children are checked.
"""
parent = item.parent()
if parent:
checked = parent.object.data().checked.all()
# checked = _all_children_checked(parent) # TEST!
_set_check_state(parent, checked)
_check_parents(parent) | 2,437 |
def _split_keys(keypath, separator):
"""
Splits keys using the given separator:
eg. 'item.subitem[1]' -> ['item', 'subitem[1]'].
"""
if separator:
return keypath.split(separator)
return [keypath] | 2,438 |
def get_code_base_url() -> str | None:
"""Get current code base url."""
code_base = None
with suppress(subprocess.CalledProcessError):
code_base = subprocess.check_output("git config --get remote.origin.url".split()).decode("utf-8").strip()
return code_base | 2,439 |
def _get_referenced_type_equivalences(graphql_types, type_equivalence_hints):
"""Filter union types with no edges from the type equivalence hints dict."""
referenced_types = set()
for graphql_type in graphql_types.values():
if isinstance(graphql_type, (GraphQLObjectType, GraphQLInterfaceType)):
... | 2,440 |
def E(poly, dist=None, **kws):
"""
Expected value operator.
1st order statistics of a probability distribution or polynomial on a given
probability space.
Args:
poly (Poly, Dist) : Input to take expected value on.
dist (Dist) : Defines the space the expected value is taken on.
... | 2,441 |
def spacify(string, spaces=2):
"""Add spaces to the beginning of each line in a multi-line string."""
return spaces * " " + (spaces * " ").join(string.splitlines(True)) | 2,442 |
def create_stage(AccessLogSettings=None, ApiId=None, AutoDeploy=None, ClientCertificateId=None, DefaultRouteSettings=None, DeploymentId=None, Description=None, RouteSettings=None, StageName=None, StageVariables=None, Tags=None):
"""
Creates a Stage for an API.
See also: AWS API Documentation
Except... | 2,443 |
def simple_line_plot(x, y = None,
title = "",
xlabel = "",
ylabel = "",
context = 'notebook',
xlim = None,
ylim = None,
color = 'blue',
parse_axe... | 2,444 |
def generate(parsed_data, template, opath, dme_vault, helper, **kwargs):
"""Generates collection and data-object metadata needed for DME upload.
For each collection (directory) and data-object (file), an output file is
generated in JSON format. 'opath' dictates where these files will be saved.
Returns a... | 2,445 |
def pytest_addoption(parser):
"""Add option to run slow tests."""
parser.addoption("--run-slow", action="store_true",
default=False, help="Run slow tests") | 2,446 |
def _get_snmp(oid, hostname, community):
"""SNMP Wrapper function. Returns tuple of oid, value
Keyword Arguments:
oid --
community --
"""
from pysnmp.entity.rfc3413.oneliner import cmdgen
cmd_gen = cmdgen.CommandGenerator()
error_indication, error_status, error_index, var_bind... | 2,447 |
def com_google_fonts_check_048(ttFont):
"""Font has **proper** whitespace glyph names?"""
from fontbakery.utils import get_glyph_name
def getGlyphEncodings(font, names):
result = set()
for subtable in font['cmap'].tables:
if subtable.isUnicode():
for codepoint, name in subtable.cmap.items()... | 2,448 |
def ensure_format_is_valid( r, dataset_name ):
"""
This extracts the format from the given resource
and maps it according to the formats mapping, if provided."""
if not 'format' in r:
log.error( '%s resources-object is missing format-property. Cannot save this value', dataset_name )
# T... | 2,449 |
def find_nearest(array, value):
"""
Inputs:
array - array...
value - value to search for in array
Outputs:
array[idx] - nearest value in array
"""
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx] | 2,450 |
def sync_contacts(contacts, create_missing=True, quiet=True):
"""
contacts is a list of dictionaries like this:
[{
u'E-Mail': u'total-berlin-admin@total.de',
u'Gender': 2,
u'First Name': u'Admin',
u'Last Name': u'von Total Berlin',
...
... | 2,451 |
def vader_entity_sentiment(df,
textacy_col,
entity,
inplace=True,
vader_sent_types=['neg', 'neu', 'pos', 'compound'],
keep_stats=['count', 'mean', 'min', '25%', '50%', '7... | 2,452 |
def install(eventloop=None):
"""
Install a tulip-based reactor.
"""
if eventloop is None:
eventloop = get_event_loop()
reactor = AsyncioSelectorReactor(eventloop)
from twisted.internet.main import installReactor
installReactor(reactor) | 2,453 |
def post_list(request):
"""
Create a view that will return a list of
Posts that were published prior to 'now' and
render them to the 'blogposts.html' template
:param request:
:return:
"""
posts = Post.objects.filter(published_date__lte=timezone.now()
).or... | 2,454 |
def get_model():
"""
Returns a compiled convolutional neural network model. Assume that the
`input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.
The output layer should have `NUM_CATEGORIES` units, one for each category.
"""
# initialize a convolutional model
model = tf.k... | 2,455 |
def get_app_icon_path():
"""Path to OpenPype icon."""
return resources.get_openpype_icon_filepath() | 2,456 |
def post_create_ipsec_endpoint_tunnel(
api_client,
endpoint_id,
remote_subnet=None,
local_subnet=None,
enabled=None,
ping_ipaddress=None,
ping_interface=None,
ping_interval=None,
description=None,
**kwargs
): # noqa: E501
"""post_create_ipsec_endpoint_tunnel # noqa: E501
... | 2,457 |
def cow_service(
wfo: List[str] = Query(
[], min_length=3, max_length=4, title="WFO Identifiers"
),
begints: datetime = Query(...),
endts: datetime = Query(...),
phenomena: List[str] = Query(None, max_length=2),
lsrtype: List[str] = Query(None, max_length=2),
hailsize: float = Query(... | 2,458 |
def add_edges_reverse_indices(edge_indices, edge_values=None, remove_duplicates=True, sort_indices=True):
"""Add the edges for (i,j) as (j,i) with the same edge values. If they do already exist, no edge is added.
By default, all indices are sorted.
Args:
edge_indices (np.array): Index list of ... | 2,459 |
def isint(var:Any, raise_error:bool=False)-> bool:
"""Check if var is an integer
Args:
var (str): variable to check
raise_error (bool, optional): TypeError raised if set to `True`. Defaults to `False`.
Raises:
TypeError: raised if var is not an integer
Returns:
bool: `... | 2,460 |
def convert_interpolate2d(g, op, x):
"""Operator converter for interpolate 2D(dims == 4)."""
def get_interpolate_mode(op):
"""conver 'interp_method' attr of paddle to tvm"""
interp_method = op.attr("interp_method")
align_corners = op.attr("align_corners")
align_mode = op.attr("... | 2,461 |
def analysis_multi_frames(plot_config, args):
"""Analysis for multiple time frames
"""
tframes = range(args.tstart, args.tend + 1)
for tframe in tframes:
plot_config["tframe"] = tframe
plot_phase_diagram(plot_config, show_plot=False) | 2,462 |
def get_stats_on_spatial_predictions_4x5_2x25_by_lat(res='4x5', ex_str='',
target='Iodide',
use_annual_mean=False, filename=None,
folder=None, ds=None,
... | 2,463 |
def calc_dif_mod_cn (x, y):
""" Check if the difference between the modulus of consecutive numbers is a prime number """
modx = math.sqrt(x.real ** 2 + x.imag ** 2) # modulus of the first complex number
mody = math.sqrt(y.real ** 2 + y.imag ** 2) # modulus of the second complex number
dif = modx-mody... | 2,464 |
def mitochondrialGTF(concatenated_gff, output_directory):
"""Convert GFF file with information for mitochondrial genes to GTF and return the path to GTF file.
Keyword arguments:
concatenated_gff -- path to concatenated GFF file
output_directory -- path to directory where GTF file should be placed
Important: tran... | 2,465 |
def benchmark_read_json():
"""
:return:
"""
start = time.time()
actual_start = time.time()
logger.info("in benchmark %s", start)
counter = 0
last_counter = 0
size = 0
last_size = 0
time_rate = 1
for pmid in pmids:
filename = get_path_from_pmid(pmid, 'xml')
... | 2,466 |
def backward(outputs, grad_outputs=None, **kwargs):
"""backward(outputs, grad_outputs=None, *, enable_double_backprop=False)
Runs backpropagation from variables simultaneously.
.. warning::
This feature is experimental. The interface can change in the future.
Args:
outputs (tuple or ... | 2,467 |
def get_none_zero_region(im, margin):
"""
get the bounding box of the non-zero region of an ND volume
"""
input_shape = im.shape
if(type(margin) is int ):
margin = [margin]*len(input_shape)
assert(len(input_shape) == len(margin))
indxes = np.nonzero(im)
idx_min = []
idx_max =... | 2,468 |
def create_short_link(request):
"""Given an URL, return a shortened link.
Args:
url: URL to be shortened.
Returns:
short_link: Shortened result of URL.
expires_at: Timestamp before which the link is valid.
"""
payload = json.loads(request.body)
url = payload.get("url")
t... | 2,469 |
def get_mapped_tracks_file(mode='r', **kwargs):
""" Returns a file descriptor-like object to the file containing the
raw track.
(A mapped track is a collection of tuples). Each tuple is:
- linking pairs
- paths
- linking pairs
- points
Arguments:
mode: r/w mode
driver_id: string, the id ... | 2,470 |
def edit_comment(comment_entity, new_comment_text):
"""Edits a comment on a blog entry"""
comment_entity.comment = new_comment_text
comment_entity.put() | 2,471 |
def ne_2beta(r, ne0, rc_outer, beta_outer, f_inner, rc_inner, beta_inner):
"""
Electron number density [cm^-3] in the double-beta profile of the hydrostratic equilibrium model.
r : distance from the center of the cluster [kpc]
ne0 : central electron number density [cm^-3]
rc_outer : core radius fro... | 2,472 |
def create_tables():
"""Recreate the database tables."""
from untracked_config.development_node import ON_DEV_NODE
lg.debug('Rebuilding database tables.')
# this section is to remove the old database table if the DefectModel table needs to be changed:
if ON_DEV_NODE:
fsa.drop_all() # TOD... | 2,473 |
def fast_fdividef(x, y):
"""
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_fdividef.html
:param x: Argument.
:type x: float32
:param y: Argument.
:type y: float32
:rtype: float32
""" | 2,474 |
def test_that_all_entries_dicts_match(load_template_test):
"""Test that the values of the dicts returned are the same as the control.
This test swaps place with the processed and reference variable so it's not run
in the same order as test_correct_data_in_entries to catch dicts with extra keys
This wi... | 2,475 |
def sell():
"""Sell shares of stock"""
"""Sell shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol")
amount = request.form.get("shares")
try:
amount = int(amount)
except:
return apology("enter a proper value")
... | 2,476 |
def log_error(e):
"""
It is always a good idea to log errors.
This function just prints them, but you can
make it do anything.
"""
print(e) | 2,477 |
def print_sentiments(sentences):
"""Given a list of sentences, prints sentiment information"""
for sentence in sentences:
print(sentence)
ss = sid.polarity_scores(sentence)
for k in sorted(ss):
print('{0}: {1}, '.format(k, ss[k]), end='')
print() | 2,478 |
def config_prime(input_file, output_file, \
index_first_dynamic_arg, num_dynamic_args, \
spec_only_globals):
"""
Execute the program until a branch condition is unknown.
index_first_dynamic_arg is a number starting at 1.
num_dynamic_args is a non-negative number.
""... | 2,479 |
def assemble_block(n_rows: Int, n_cols: Int, pdf: pd.DataFrame, cov_matrix: NDArray[(Any, Any),
Float],
row_mask: NDArray[Any]) -> NDArray[Float]:
"""
Creates a dense n_rows by n_cols matrix from the array of ... | 2,480 |
def calc_xixj_from_braggphi(
det_cent=None,
det_nout=None, det_ei=None, det_ej=None,
det_outline=None,
summit=None, nout=None, e1=None, e2=None,
bragg=None, phi=None,
option=None, strict=None,
):
""" Several options for shapes
de_cent, det_nout, det_ei and det_ej are always of shape (3,... | 2,481 |
def test_null_desc():
"""
The default descriptor is not actually defined, but should be NULL
"""
default = descriptor.build()
assert default == ffi.NULL | 2,482 |
def _check_index_good(X):
"""Check the index of X and return boolean."""
# check the first index elements for "__total"
tot_chk = np.any(X.index.get_level_values(level=0).isin(["__total"]))
return tot_chk | 2,483 |
def seguimientos_list_csv(request, codigo):
"""Lista todos los eventos de seguimiento para cada proyecto de ley.
---
type:
codigo:
required: true
type: string
parameters:
- name: codigo
description: código del proyecto de ley incluyendo legislatura, por ejemplo 00002... | 2,484 |
def endpoint_error(estimate, ground_truth):
"""Computes the average end-point error of the optical flow estimates."""
error = torch.norm(
estimate - ground_truth[:, :2, :, :], 2, 1, keepdim=False)
if ground_truth.size(1) == 3:
mask = (ground_truth[:, 2, :, :] > 0).float()
else:
m... | 2,485 |
def output(log_message=None, success_message=None,
fail_message=None):
"""This is a decorator to trap the typical exceptions that occur
when applying and removing modules. It returns the proper output
corresponding to the error messages automatically. If the function
returns output (success_f... | 2,486 |
def custom_mape(approxes, targets):
"""Competition metric is a slight variant on MAPE."""
nominator = np.abs(np.subtract(approxes, targets))
denominator = np.maximum(np.abs(targets), 290000)
return np.mean(nominator / denominator) | 2,487 |
def article_text_to_dict(article_text: str):
"""
Translates an article text into a dict.
"""
data = collections.defaultdict(list)
field = ''
for line in re.split(r'\n+', article_text):
# Fix little bug with isi files
if line.startswith('null'):
line = line[4:]
... | 2,488 |
def add_product(basket, price=None, quantity=1, product=None):
"""
Helper to add a product to the basket.
"""
if not hasattr(basket, 'strategy'):
basket.strategy = strategy.Default()
if price is None:
price = D('1')
if product and product.has_stockrecords:
record = produc... | 2,489 |
def frohner_cor_3rd_order(sig1,sig2,sig3,n1,n2,n3):
"""
Takes cross-sections [barns] and atom densities [atoms/barn] for
three thicknesses of the same sample, and returns extrapolated
cross section according to Frohner.
Parameters
----------
sig1 : array_like
Cross section of the ... | 2,490 |
def nodeInTree(root, k):
"""
Checks if the node exists in the tree or not
"""
if root == None:
return False
if root.data == k or nodeInTree(root.left, k) or nodeInTree(root.right, k):
return True
return False | 2,491 |
def read_xvec(path, base_type, N=-1):
"""
A utility function to read YAEL format files
(xxx.ivec, xxx.fvec, and xxx.bvec)
:param path: The path of xvec file
:param base_type: The type of xvec; 'f', 'i' or 'b'
:param N: The number of vectors to be read. If this is not specified, read all
:ret... | 2,492 |
def make_dir(path):
"""Make directory.
Args:
path (str): absolute path for directory
Raise error if error other than directory exists occurs.
"""
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise | 2,493 |
def test_init(app):
"""Test initialisation."""
auth = OktaOAuth(app)
assert auth.app is app | 2,494 |
def split_and_filter(intermediate_str, splitter):
"""
Split string with given splitter - practically either one of "," or "/'".
Then filter ones that includes "https" in the split pickles
:param intermediate_str : string that in the middle of parsing
:param splitter
:return: chunk of string(s) a... | 2,495 |
def test_hrf_deriv_timing():
"""Test some timing aspects of the HRF and its derivative."""
hrf = glm.GammaDifferenceHRF(temporal_deriv=True, oversampling=100)
y, dy = hrf.kernel.T
nt.assert_greater(np.argmax(y), np.argmax(dy))
npt.assert_almost_equal(dy[np.argmax(y)], 0, 4) | 2,496 |
def main(n, n_boulders, b_down, state_to_index, index_to_state, boulder_positions, state_reward, full_states):
"""Finds and saves optimal policy and values to json file.
Parameters:
n: number of rows/columns
b_down: possible next boulder states
state_to_index/index_to_state: dictionaries... | 2,497 |
def organism_code(genus, species):
"""Return code from genus and species."""
return (
f"{genus[:GENUS_CODE_LEN].lower()}{species[:SPECIES_CODE_LEN].lower()}"
) | 2,498 |
def verify_image(filename):
"""Verifies whether the file exists"""
image_extensions = ['tif', 'jpg', 'gif', 'png', 'jpeg']
if type(filename) is str:
extension = filename.split('.')
if len(extension) == 2:
if extension[1].lower() in image_extensions:
return os.path... | 2,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.