content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def download_preview_file_thumbnail(preview_file, file_path, client=default):
"""
Download given preview file thumbnail and save it at given location.
Args:
preview_file (str / dict): The preview file dict or ID.
file_path (str): Location on hard drive where to save the file.
"""
p... | 27a1420640af90cc174a479f8d835cee6b2cd34b | 72,625 |
def get_player_df(players,stat_type,stat,playoffs,player_labels):
"""
Get dataframe from basketball_scraper
:param players: list of player names
:return:
"""
if not player_labels:
player_labels=players
players_df=[]
for player,player_label in zip(players,player_labels):
... | d31ae11917aa23545a3210d662f4ffa6427a4fb9 | 72,626 |
def nearest_workday(dt):
"""
If holiday falls on Saturday, use day before (Friday) instead;
if holiday falls on Sunday, use day thereafter (Monday) instead.
"""
if dt.weekday() == 5:
return dt - timedelta(1)
elif dt.weekday() == 6:
return dt + timedelta(1)
return dt | f0f3ff6635ca08ec1b8ca4705b52481b2b8f7d7d | 72,627 |
def _manuscript_chapter_data(ms_id, bk, ch):
"""
Parse the request and return the data required to make the manuscript page
and also the correctors json blob
"""
ms = get_object_or_404(ManuscriptTranscription, pk=ms_id)
my_chapter = get_object_or_404(Chapter, num=ch, book__num=bk)
hands = Ha... | bd859bb50112864cbc1db024fe055d79149f3bce | 72,628 |
import warnings
from datetime import datetime
def read_GPM(infile: str, refl_min_thld: float = 0) -> xr.Dataset:
"""
Read GPM data and organize them into a Dataset.
Parameters:
-----------
gpmfile: str
GPM data file.
refl_min_thld: float
Minimum threshold applied to GPM reflec... | 58965e878402375ab48637c1980e66d7cc1cd055 | 72,629 |
def _world2fig(ff, x, y):
"""
Helper function to convert world to figure coordinates.
Parameters
----------
ff : `~aplpy.FITSFigure`
`~aplpy.FITSFigure` instance.
x : ndarray
Array of x coordinates.
y : ndarray
Array of y coordinates.
Returns
-------
coo... | 99df767d948bc1c0807b676e2178de1478a1ac71 | 72,631 |
def gauss(t, sigma):
""" Take sample from Gaussian function with the given sigma.
"""
return e ** (-t ** 2 / (2 * sigma ** 2)) | ed5bfb690fc0d1e936880276640bf55261ab2764 | 72,632 |
def log_normal_error(weights, z_alpha=1):
"""Returns the unnormalised errors on the estimation of the probability
density using the lognormal method.
Parameters
----------
weights: numpy.ndarray
Associated weights to the first-passage time data. Must be a one-to-one
correspondance b... | 43f617d4a44d1271a9cc38f64700f3dcea86baba | 72,634 |
def T(t):
"""The file name for target ``t`` of the current object."""
return _targetPrefix + _find_object_type() + "/{oid}/" + t | 9bffca11c52d60489eda10963b0e253c0708e3a8 | 72,635 |
from typing import List
async def list_users() -> List[UserOutGet]:
"""
Get users list.
:return: list users
"""
return await UserOutGet.from_queryset(Users.all()) | 89fdcab3a5f1dec1c39f76e036f38c2981a26b0b | 72,636 |
def default_for(python_type):
"""Sets a specified python type's default SQL type.
Args:
python_type (type): Python type to set the specified sqltype as default for.
"""
def func(sql_type):
_defaults[python_type] = sql_type
return sql_type
return func | 69c0338911df4b9d0e4f25be22f5ab783c3e7c63 | 72,637 |
def submit(syncselection_name, now=True, as_object=False, p5_connection=None):
"""
Syntax: SyncSelection <name> submit [<now>]
Description: Submits the sync selection for execution. You can optionally
override plan execution times by giving the <now> as one of the strings
"1", "t", "true", "True", "... | 214d334ed5e1bff2a717bb075e6f6d51cfc96af8 | 72,638 |
from typing import Optional
from typing import Union
def df_count(x: str, df: pd.DataFrame, hue: Optional[str] = None, sort_by_count: bool = True, top_nr: int = 5,
x_base: Optional[float] = None, x_min: Optional[float] = None, x_max: Optional[float] = None,
other_name: str = 'other', other_t... | c2385380494f5653406e9796e343a110e2fa90fd | 72,639 |
def is_palindrome(number):
""" Returns True if `number` is a palindrome, False otherwise.
"""
num_str = str(number)
num_comparisons = len(num_str) // 2
for idx in range(num_comparisons):
if num_str[idx] != num_str[-1-idx]:
return False
return True | 391aec57bba8366d7e7ef2c8187fda377f5a786d | 72,640 |
def _process_images_num_channels(image_arrays, expected_channels):
"""
Helper function for processing decompressed images with number of expected channels.
This is for old API without mapping provided. Use the first n channel, n=expected_channels.
"""
if expected_channels == 1:
# Convert to ... | b016c596412ae5cc3f40cb6cac9e8587d0258587 | 72,642 |
from typing import Iterable
def flatten_list(li: Iterable):
"""Flattens a list of lists."""
if isinstance(li, Iterable):
return [a for i in li for a in flatten_list(i)]
else:
return [li] | 306536fdadf231b0a0f752bb63d7e01317819674 | 72,643 |
def queryString_required(strList):
""" An decorator checking whether queryString key is valid or not
Args:
str: allowed queryString key
Returns:
if contains invalid queryString key, it will raise exception.
"""
def _dec(function):
@wraps(function)
def _wrap(request, *args, **kwargs):
for i in strList:
... | 34d69213f4f4bab4965af13beae4faf66d63b970 | 72,644 |
def listdetail(filename, itemtype, name="", header="default"):
"""List nodes and metadata in output file."""
obj = SwmmExtract(filename)
typenumber = obj.type_check(itemtype)
if name:
objectlist = [obj.name_check(itemtype, name)[0]]
else:
objectlist = obj.names[typenumber]
propn... | cb49f791a0fd76db9a4c24e75dbe71d2921ba40a | 72,645 |
def set_reverseXmatrix():
"""Reverse X axis using set_strechmatrix(-1.0, 1.0)
Returns
-------
reverse_X_matrix: matrix
"""
return set_stretchmatrix(-1.0, 1.0) | 7a39df1344cc8fdfd02a4b77d5fb999c01060e6b | 72,647 |
from typing import Tuple
def _get_final_vals(spacetime_matrix: np.array,
receiver_velocity_mx_mps: np.array,
source_velocity_mx_mps: np.array,
time_array_s: np.array,
receiver_position_vector_initial_xyz_m: np.array,
s... | 19f832c26c6f3998fb55ce35431d831ecff7ff20 | 72,648 |
def dataset_to_datavar(
ds: DataSetGAN,
n_convs: int,
kernel_size: int,
stride: int,
padding: int,
remove_diags: int,
add_diags: bool,
) -> DataVarGAN:
"""Convert a `DataSetGAN` into a `DataVarGAN`."""
# ds = pad_edges(ds, offset=offset)
seqs = push_seqs(ds.seqs)
adj = ds.adj... | 2e2b961bf2b162a2ab224b5836ddebd3bf48a4c4 | 72,649 |
def improve_ensemble(energy, positions, ensemble, ensemble_energies, unchanged_iterations):
"""
Given an energy and positions for a single pose, as well as the same data for a reference ensemble, this function "improves" the quality of the ensemble by identifying poses with the lowest potential energy.
... | ac1dcf2ec104a886b61e2abe4b4e090724d47ce7 | 72,650 |
def get_folds(X, y, cv_count: int, split_seed: int, stratify: bool = None):
"""Cross validationのインデックスを返す。
Args:
X: 入力データ。
y: 出力データ。
cv_count: 分割数。
split_seed: 乱数のseed。
stratify: StratifiedKFoldにするならTrue。
Returns:
list of tuple(train_indices, val_indices): イ... | aacefdf31188ac99d73fc82ce3b9f164b0daacd9 | 72,651 |
def get_static_welcome_message():
"""
Get the static welcome page.
"""
return \
"""
<h3>Search Help</h3>
<ul><li>The display below the line is an example of the output the browser
shows you when you enter a search word. The search word was <b>green</b>.</li>
<li>The search result shows for different par... | f630c67ab66069baf8b82b5b4c5fe111b9191a73 | 72,652 |
def bisearch(x, profile, epsilon=RT_EPSILON):
"""Use binary search to find index of equal or next higher x-value."""
idx = 0
hi = len(profile)
while idx < hi:
mid = (idx + hi) // 2
if x < profile[mid][0] or equals(x, profile[mid][0], epsilon):
hi = mid
else:... | 7c84325bd267e921b3f5d9f79d0f66f41fc52f91 | 72,653 |
def cmd_alias_create(module, cmd_path, alias, version, **kwargs):
""" gvm alias create <alias> <version>
"""
result, data = get_alias_list(module, cmd_path, **kwargs)
if not result:
module.fail_json(**data)
if alias in data["aliases"]:
if version == data["aliases"][alias]:
... | c8d9e550d82fd9b6b7a86c653dde6b04efac0205 | 72,654 |
def format_lines(statements, lines):
"""Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statemen... | 9e8f3d83df45134c5cd586a9323612b8516acdec | 72,655 |
def _get_raster_srs_str(fp):
"""Read a raster with GDAL and return its SRS or None."""
try:
tmp_ds = gdal.Open(fp, GA_ReadOnly)
# Get WKT projection from gdal
srs_str = tmp_ds.GetProjection()
if not srs_str:
raise Exception('GDAL failed to detect any projection.')
... | b45c5282e1727e61f84dbfba1a9d114202f1d072 | 72,656 |
def cos_zenith(ha, dec, latitude=None):
"""Calculate cos(zenith) for specified hour angle, DEC and latitude.
Combine with :func:`cos_zenith_to_airmass` to calculate airmass.
Parameters
----------
ha : astropy.units.Quantity
Hour angle(s) to use, with units convertible to angle.
dec : a... | 00c8d2ca71da833d7769e3b1fb6f8d5ca1664c69 | 72,659 |
def format_body(issue, empty_row, width_col):
""" Formats the body of an issue """
wrapper = TextWrapper(initial_indent=empty_row,
subsequent_indent=empty_row,
width=len(empty_row) + width_col,
replace_whitespace=False)
body = i... | 538129479099bca39fdaecf7561ac3ee42a687ef | 72,660 |
def get_single_feature_from_example(example: InputExample, config: Config) -> InputFeatures:
"""
Transfer an example to a feature. text -> ids list; labels -> label_id list;
Add padding if text is too long.
Parameters:
example: InputExample
Returns:
feature: InputFeature
"""
... | 1f0c35ddd1e6b92896ecb0acd8b98a181cc5a8c6 | 72,661 |
def parse_value(text, spec, max_value=None):
"""Finds a value embedded in a formatted string (spec) in the form of
'placeholder placeholder2 %v placeholder3' where placeholder text
helps locate the desired value denoted by %v"""
text = text.replace("|", "")
text = text.replace("]", "")
text = te... | 27c73999ca2483a754b1cf59c9717e85d7b2a458 | 72,663 |
def _make_history_monotone(df, target_col, direction="minimize"):
"""Create a monotone Series, i.e. the best so far instead of the current evaluation.
Args:
df (pandas.Dataframe): must contain ["problem", "algorithm", "n_evaluations"]
and the target_col as columns.
target_col (str):... | 5a7029206d93f615d28e573afb5919374bfa9f4d | 72,665 |
def _build_coords(arg):
"""Converts one or many lng/lat pair(s) to a comma-separated, pipe
delimited string. Coordinates will be rounded to 5 digits.
For example:
convert.build_coords([(151.2069902,-33.8674869),(2.352315,48.513158)])
# '151.20699,-33.86749|2.35232,48.51316'
:param arg: The l... | 8f06d98ea50402bb7650af118d7e96f5a049d1eb | 72,667 |
def predict(x_input: np.ndarray, model: np.ndarray, predicts: float = 7):
"""Model that return just arithmetical average from last few data points.
Args:
x_input (np.ndarray): Time series data inputting the models. Usually last few data points.
Structure depends on X in train function (usua... | 0577d2754b1be97f3b3675ee1be8de1386b1ce7a | 72,668 |
def platform_name(project, platform):
""""Get the untrusted platform name."""
return project.upper() + '_' + platform.upper() | 3f63ab210ef040114a536cac40efbad168631273 | 72,669 |
def length(input):
"""Creates a task that takes one object and returns its size"""
task = Task()
task.task_type = BASE_LENGTH
task.inputs = (input,)
return task | 4d368f541608bb749bf30fb571a88a77a45e4694 | 72,670 |
def _process_stmt(statement: dict) -> BaseStatement:
"""Receive statement dict and call the proper statement class.
The `name` attribute of the class is used to bind the statement
type to its class.
Parameters
----------
statement : dict
Dict from Validation Document representing statem... | 3857e74ec92cc983d50c258c0d6805219a3af5c0 | 72,671 |
def contact_infectivity_asymptomatic_50x60():
"""
Real Name: b'contact infectivity asymptomatic 50x60'
Original Eqn: b'contacts per person normal 50x60*infectivity per contact'
Units: b'1/Day'
Limits: (None, None)
Type: component
b''
"""
return contacts_per_person_normal_50x60() * i... | 10c6336aa0f922538ecf7856a0349706f1b9e7dd | 72,672 |
from typing import Tuple
def parse_item(item: str) -> Tuple[str, int]:
"""
Returns a pair: bag_color, count
"""
item_match = ITEM_PATTERN.match(item)
if not item_match:
raise Exception("Bad item: " + item)
return item_match.group(2), int(item_match.group(1)) | b933bb7dec450454f3da25ab6d736f3c556dfd77 | 72,674 |
def init(mainf):
""" initialize and shutsdown minesweeper"""
def initf():
setup()
mainf()
teardown()
return initf | b65668643393e5bca3ed17033f4c7efa0af70686 | 72,675 |
import numpy
def lat2g0(lat):
"""Calculate surface gravitational acceleration for latitude
This function is stolen from atmlab:
https://www.sat.ltu.se/trac/rt/browser/atmlab/trunk/geophysics/pt2z.m
From the original description:
Expression below taken from Wikipedia page "Gravity of Earth", tha... | 7c907a8016b6a579dd0a16a1662bf02358778d16 | 72,676 |
def specificity(y_true, y_pred):
"""Gets the specificity of labels and predictions.
Parameters
----------
y_true : torch.tensor
The true labels.
y_pred : torch.tensor
The prediction.
Returns
-------
numpy.ndarray
The specificity.
"""
y_true, y_pred = pr... | 93cf3c81504b56613257363dc3f603ce96453d65 | 72,677 |
def create_strategy(config):
"""
Create build strategy and exec strategy.
Args:
config(dict): config
Returns:
build_strategy: build strategy
exec_strategy: exec strategy
"""
build_strategy = paddle.static.BuildStrategy()
exec_strategy = paddle.static.ExecutionStrate... | f5677fc4b9c7d176d9a22862465f8debda95aa4d | 72,678 |
from typing import Any
from typing import Optional
def coerce_type(obj: Any, typ: Optional[type]) -> Any:
"""
Coerce object to the given type.
Type must be registered for this function to work.
"""
if typ is None or typ is type(obj):
return obj
fn = _coerce_fn.dispatch(typ)
resul... | 2fb7dce2e2f19a8790f7403b003c85581d393f97 | 72,679 |
def brevity_penalty(alpha: float, length: int) -> jnp.ndarray:
"""Brevity penalty function for beam search penalizing short sequences.
Args:
alpha: float: brevity-penalty scaling parameter.
length: int: length of considered sequence.
Returns:
Brevity penalty score as jax scalar.
"""
return jnp.p... | 88590e93bf47109bd7b333f6ca09336c0590dd33 | 72,680 |
def _imports(graph: mapry.Graph) -> str:
"""
Generate the import declaration.
:param graph: mapry definition of the object graph
:param go: Go settings
:return: generated code
"""
import_set = {'strings', 'fmt'}
if mapry.needs_type(a_type=graph, query=mapry.Integer):
import_set... | 473facecef56897bee7c67e7ecec8a3620597980 | 72,682 |
def p_qq(data,pv_index=0,alpha=0.05):
"""
This function plots all the raw p-values and compares them with a theoretical uniform distribution using a
qq plot. This plot is created with a negative log scale, letting
us visualize all the p-values, independent of their small magnitudes. The p-values deviate... | d857c54c91c8c4ec3541411b134839d836b9fbf3 | 72,683 |
def occlusion_reliability(forward_flow, backward_flow, gamma=1):
""" Calculates the flow variation reliability
Parameters
----------
forward_flow: numpy array
forward flow values
backward_flow: numpy array
backward flow values
gamma: float, optional
soft threshold
... | a67ff73a557ca1a3cc984d29218fa9251a869baf | 72,684 |
def leja(a):
"""
Leja ordering of given numbers:
* |a[0]| = max_j |a[j]|
* prod_{i=0}^{k-1} |a[k] - a[i]| = max_j prod_{i=0}^{k-1} |a[j] - a[i]|
When used as a preprocessing for np.poly it increases its numerical precision.
"""
n = len(a)
c = np.argmax(np.abs(a))
a[[c, 0]] = a[[0, ... | 60d989aaf92ac79ced364096701d7da0a4d9853e | 72,685 |
def is_dry_run() -> bool:
"""
Returns whether or not we are currently doing a preview.
"""
return bool(SETTINGS.dry_run) | 4ae0de410979b25fe94a169e3508e14cd797d02c | 72,686 |
def hockeydata_css(*args):
""" hockeydata css tag """
url = get_hd_attr('STATIC', '')
if url is None:
return mark_safe('Error: No HOCKEYDATA_STATIC in settings provided!')
default_css = get_hd_attr('DEFAULT_CSS', '')
if default_css is not None:
css_links = '<link href="{url}css/?{de... | 94eda4e80242fe7ee8dce77fa376c9e915bfcf88 | 72,687 |
def Add(left: Expr, right: Expr) -> BinaryExpr:
"""Add two numbers.
Produces left + right.
Args:
left: Must evaluate to uint64.
right: Must evaluate to uint64.
"""
return BinaryExpr(Op.add, TealType.uint64, TealType.uint64, left, right) | 13245e95637841f60cda88e8de2624bdde4e4aa3 | 72,688 |
def getArtistCompleter(year, country, label):
"""
Retrieve all artists of Discogs jazz release data within selected year, country, and label
Params: (year) array containing selected year(s)
(country) array containing selected country(s)
(label) arr... | 60a34656d25286a9cd3f59d62e227aae54b4e96d | 72,689 |
def rps(da_cmp, da_ref, bins, over_dims=None, ensemble_dim='ensemble'):
"""
Returns the ranked probability score
Author: Dougie Squire
Date: 10/05/2018
Parameters
----------
da_cmp : xarray DataArray
Array containing data to be compared to refere... | e6e30c902a3beb954079e1d54f019eeeeab34173 | 72,690 |
def m_order(freq,theta,lcandidat,k, id2word):
"""
Calculate the M-Order Relevance
Parameters:
----------
freq : Array containing the frequency of occurrences of each word in the whole corpus
theta : Array containing the frequency of occurrences of each word in each topic
lcandidat: Array co... | 2b57cbb4df82481bb4a6ad82b4ae3de1d4fc5875 | 72,691 |
def find_possible_swap_regions(genome, front_arm_sequence, back_arm_sequence, cassette):
"""
Computes all possible recombined region from arm sequences.
"""
front_arm_results = blast_genome(genome, 'blastn', front_arm_sequence)
back_arm_results = blast_genome(genome, 'blastn', back_arm_sequence)
... | f1a9822f399b15de4f1e16a3c419107901fcc480 | 72,692 |
def tpearson(x, y, axis=0):
"""Tensor-based pearson correlation."""
n = x.shape[axis]
xc = x - x.mean(axis=axis, keepdims=True)
yc = y - y.mean(axis=axis, keepdims=True)
xystd = x.std(axis=axis) * y.std(axis=axis)
cov = (xc * yc).sum(axis=axis) / n
corr = cov / xystd
return corr | 37da10d2e21f04296a2cc0b3f8b239e0fcba8957 | 72,693 |
def fermisign(projected_states, i, j, sigma, tau=None):
"""
Gounts how many fermions are sitting between sites i and j with spin sigma
in the state defined by stateprojection
Note: implicit spin-ordering for Fermi sign: all Up before all Down
Args:
projected_states - (2xN) list with the ferm... | cfb29337a4cc62fda37e8172d4834a7332fb2842 | 72,694 |
def circle_from_points_xy(a, b, c):
"""Create a circle from three points lying in the XY-plane
Parameters
----------
a : [float, float] or [float, float, float] | :class:`compas.geometry.Point`
XY(Z) coordinates of a 2D or 3D point (Z will be ignored).
b : [float, float] or [float, float, f... | e89f2b0aa937f00688db5162ae86a536fdf246a3 | 72,695 |
import unittest
def makeTestSuiteV201109():
"""Set up test suite using v201109.
Returns:
TestSuite test suite using v201109.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(ExperimentServiceTestV201109))
return suite | 779e276b765c363191fb31386ee915c3ab8a3f43 | 72,696 |
def get_entity_friendly_name(entity_id):
"""Get entity friendly name."""
return hass.states.get(entity_id).attributes["friendly_name"] | e944bdf63ab3292ffd386d21d5ed3d8607a33c16 | 72,697 |
import re
def remove_unwanted_chars(x: str, *chars: str, to_replace: str = "") -> str:
"""Remove unwanted characters from a string."""
return re.sub(f"[{''.join(chars)}]", to_replace, x) | 4a1e25b1ad12f47f835d4f6cdbac4a6e08413077 | 72,700 |
async def get_by_name(name : str, current_user: User = Depends(get_current_active_user)):
"""
Looks for an item in the database
"""
data = await fetch_item(name)
if data is None:
return HTTPException(404, "Item not found")
return data | 841cfa4854f54076d7e6bcf29ad321ccd73382f1 | 72,701 |
def readMatrix( infile,
format = "full",
separator = "\t",
numeric_type = numpy.float,
take = "all",
headers = True,
missing = None,
):
"""read a matrix from file ane return a numpy matrix.
formats a... | bb63ebf3319ef6a547794fe963fd3323b06a6da8 | 72,702 |
from typing import List
def ranked_followers(username: str, rank_by: str, value: str) -> List[Follower]:
"""
Rank followers based on specified criteria using db queries. Return a list
of ranked followers' user id and their screen names who have not already
been sent a DM.
params:
username... | 232ca94bed58a12b086fccc760fbfd73f5d19208 | 72,703 |
def get_entity_group_version(entity_or_key):
"""Returns the version of the entity group containing `entity_or_key`.
Args:
entity_or_key: a key or entity whose version you want.
Returns: The version of the entity group containing `entity_or_key`. This
version is guaranteed to increase on every change to t... | 11f6a3fa0f0ff93a3201e1208c2b591dd686a7c2 | 72,704 |
def get_first_shape(node):
"""
Returns the first active shape on a given transform
:param node: str, transform node to get shape from
:return: str
"""
shapes = get_shapes(node=node, non_intermediates=True, intermediates=False)
if shapes:
return shapes[0]
return None | c8dfdcbabfce591e9484c8023f6a1ab42b20a9cb | 72,705 |
def UDPOS(*args, **kwargs):
""" Universal Dependencies English Web Treebank
Separately returns the training, validation, and test dataset
Arguments:
root: Directory where the datasets are saved. Default: ".data"
vocabs: A list of voabularies for each columns in the dataset. Must be in an
... | fba09e0dbdeb79fab747ab39b990632563622174 | 72,706 |
def generate_openid_signature(openid):
"""对openid进行加密,返回加密后的openID"""
# 1.创建加密的实例对象
serializer = Serializer(settings.SECRET_KEY, 600)
# 2.调用dumps方法进行加密,返回bytes类型
data = {'openid': openid}
openid_sign = serializer.dumps(data)
# 3.返回
return openid_sign.decode() | 99203760d8e8efaae0731e3c9054898308072697 | 72,707 |
def write_the_species_tree(annotated_species_tree, output_file):
"""
this function writes the species tree to file
args:
annotated_species_tree : a string of annotated species tree in .newick format
output_file : a file name to write to
output:
a file containing the annotated sp... | 7db9d5fc10cd27b1e7a5e51427e7de6991a1157a | 72,708 |
import functools
def compose(*functions):
"""
A functional helper for dealing with function compositions. It ignores any None functions, and if all are None,
it returns None.
Parameters
----------
*functions
function arguments to compose
Returns
-------
function or None
... | 8a18b1e0beef43c0cfac4439fa158675a486b560 | 72,709 |
def pretty_print_list(lst, name = 'features', repr_format=True):
""" Pretty print a list to be readable.
"""
if not lst or len(lst) < 8:
if repr_format:
return lst.__repr__()
else:
return ', '.join(map(str, lst))
else:
topk = ', '.join(map(str, lst[:3]))
... | d199261e6b9fd226256a151601d0bd86e7458fe1 | 72,711 |
import json
def load_api_config():
"""Grab our config parameters from our provided config file (JSON format)."""
with open(Config.config_file, 'r', encoding="utf-8") as file_config:
conf = json.loads(file_config.read())
return OAuth2(client_id=conf["falcon_client_id"],
client_se... | 7c73cfd066e4f243c80cfc098c3950b4801f157f | 72,712 |
def factorial(n):
"""
:type n: int
:rtype: int
"""
f = n
for i in range(n - 1, 0, -1):
f = f * i
return f | 17d6e211911417507e5887232f181bf774396c73 | 72,713 |
def train_model(X_train, Y_train):
"""
This function takes in the training data and label arrays
and returns a clf classifier object
"""
n_estimators = 400
max_depth = 5
min_child_weight = 5
learning_rate = 0.1
clf = XGBClassifier(n_estimators=n_estimators,
max_d... | b4e0c26796b14ff1938f736f8dcb5420cccff9c2 | 72,714 |
def pairify(string):
"""Convert a string of the form "key: value" to a tuple ("key",
"value"). May raise a ParseError."""
items = string.split(":", 1)
try:
return items[0].strip(), items[1].strip()
except IndexError:
raise ParseError("'%s': Keys must be terminated with a colon." %
... | 1541e94b4fb6feba91c07f71445e719832afa687 | 72,715 |
def get_provenance_record(attributes, ancestor_files, plot_type):
"""Create a provenance record describing the diagnostic data and plot."""
caption = ("Correlation of {long_name} between {dataset} and "
"{reference_dataset}.".format(**attributes))
record = {
'caption': caption,
... | 3b813a500edd4e93becb469d5cb967a4e32465b4 | 72,716 |
def encryptCharacter(PQ, character, powers):
"""Encrypting a single given character"""
ascii = getAscii(character)
k = 0
powers.setPrevSQR(ascii, k)
modNum = ascii % PQ
powers.setModNum(modNum, k)
for x in range(0, powers.getLength() - 1):
k = k + 1
prevSQR = modNum * modNum
... | dd206c39e5fe80fec0290a226f8341b2fa9a475d | 72,717 |
def _resource_schema_base(available_resources, selected_resources):
"""Resource selection schema."""
known_available_resources = {
sensor_id: sensor[0]
for sensor_id, sensor in SENSOR_TYPES.items()
if sensor_id in available_resources
}
return {
vol.Required(CONF_RESOURC... | 0c41f907fea5792b586ad9bad90085c9ef248906 | 72,719 |
from typing import Optional
from operator import or_
def get_resource_holders_permissions(
db_session: Session, resource_id: UUID, holder_id: Optional[UUID] = None
) -> data.ResourceHoldersListResponse:
"""
Get list of permissions for exact holder.
"""
query = (
db_session.query(
... | a64f71eba95a0ab1852c8be097ace96f6361341e | 72,722 |
def delete_user(self):
""""
function to check if the user is deleted
"""
return User.user_list.remove(self) | 6fb17b7d5794174de44954243258d9c83782b8d5 | 72,723 |
def calcMaxEntPolicy(trans_mat, horizon, r_weights, state_features, beta):
"""
For a given reward function and horizon, calculate the MaxEnt policy that gives equal weight to equal reward trajectories
trans_mat: an S x A x S' array of transition probabilites from state s to s' if action a is taken
horizon: t... | 5615fbbc86a0a80cdeae59b5e5790f1b379ac6df | 72,724 |
def bed_count_region_overlaps(site_bed, region_bed, overlap_out,
only_incomplete=False,
intersectBed_f=False):
"""
Overlap sites with regions, and return number of sites overlapping for
each region. Also return the list of site IDs for each region.... | f456b4b0388e5e9c2b57fc1178ee25f9c13b9b64 | 72,725 |
def _generate_fake_input_arg_componentsdk(arg_spec):
"""Generate a fake argument value for inputs of module spec
Args:
arg_spec (dict) : argument specification from yaml module spec
Returns:
object: sample fake value
Raises:
NotImplementedError: if arg type is not implemented
... | 62d92059ff6df74f4f08e6c2d09186f48058b617 | 72,726 |
def get_matrix26():
"""
Return the matrix with ID 26.
"""
return [
[4.0, 4.0, 7.0, 7.0],
[3.0, 3.0, 7.0, 7.0],
[2.0, 2.0, 7.0, 7.0],
[1.0, 1.0, 7.0],
[0.0, 0.0, 7.0, 7.0],
] | 9650bda70c0b7818950d1165edaadc7a6e2df889 | 72,727 |
def get_shortest_path(start, goal):
"""
Returns shortest path. For this problem space
some of the problems have more than one problem
space. This function returns the first occurrence
it finds
:param start: node from
:param goal: node to
:return: list of the path with the shortest walk f... | a41bead86fb21bf99b2035568bc6fc035152de11 | 72,728 |
from typing import OrderedDict
def finalize_autosummaries() -> None:
"""Create the necessary ops to include autosummaries in TensorBoard report.
Note: This should be done only once per graph.
"""
global _finalized
tfutil.assert_tf_initialized()
if _finalized:
return None
_finaliz... | 50f5520dd9684c957d30bc470ef97f28102e75d9 | 72,730 |
def create_model(model_object, input_data, model_name: str = None) -> Model:
"""
Creates Model instance from arbitrary model objects and sample of input data
:param model_object: model object (function, sklearn model, tensorflow output tensor list etc)
:param input_data: sample of input data (numpy arr... | b54fe92a73bb22ca3da8a8845d364af385003d8b | 72,732 |
def make_disjunctive_chaum_pedersen_zero(
message: ElGamalCiphertext, r: ElementModQ, k: ElementModP, seed: ElementModQ
) -> DisjunctiveChaumPedersenProof:
"""
Produces a "disjunctive" proof that an encryption of zero is either an encrypted zero or one.
:param message: An ElGamal ciphertext
:param ... | 97b0b15b265b795bfcf0e2e8d3ca0737dda8c455 | 72,733 |
def get_conf_dfs(df, log=False):
"""Df is info df, return the collection of dfs in the confirmed_df_dict column with some extra information."""
df_all = pd.DataFrame()
for _, row in df.iterrows():
site = row["site"]
try:
df_frame = pd.DataFrame(row["confirmed_df_dict"])
... | 89e97635edd8062d1ec1cb0878114467e80298ae | 72,734 |
def vib_ent(temp, t_d_perov, t_d_brownm):
"""
Vibrational entropy based on the Debye model
:param temp: temperature
:param delta: non-stoichiometry delta
:return: vibrational entropy
"""
# integral for vibrational entropy using the Debye model
def s_int(temp, t_d... | aa4ceeadc9be5e6f1489c8f9cf6ebb10908d0d05 | 72,735 |
def Object_ClassName():
"""Object_ClassName() -> char const *"""
return _DataModel.Object_ClassName() | 54043519d451286642268c6c971e3cad60a176c2 | 72,737 |
def get_model_from_key(key: str) -> object:
"""
Get model from key
"""
class_name, pk = key.split(":", 1)
return apps.get_model(class_name) | fea798a3626bd516edcda64ad18e278537f3b159 | 72,738 |
def hernquist_profile_3d(cosmo, concentration, halo_mass, odelta, a, r):
"""Calculate the 3D Hernquist halo profile
at a given radius or an array of radii,
for a halo with a given mass, mass definition, and concentration,
at a given scale factor, with a cosmology dependence.
.. note:: Note that thi... | b7257e15408694220aa13d299ea4e346a30fb2c5 | 72,739 |
def masked_softmax(data, mask, dim=-1):
"""Computes the axis wise softmax over chosen elements.
Args:
data: 2-D float `Tensor` of size [n, m].
mask: 2-D boolean `Tensor` of size [n, m].
dim: The dimension over which to compute the softmax.
Returns:
masked_softmax: 2-D float `Tensor` of size [n, ... | befba39ab8a43d5b09618461aa9c46523fce6515 | 72,740 |
def bc(n, k):
""" return the binomial coefficient "n choose k". Can you figure out a method that is less likely to cause an overflow than using the formula(n*(n-1)*...*(n-k+1))/(k*(k-1)*...*2)? """
return special.binom(n, k) | 140b4b84fb370fb8ffd7ae61b3a8c67f4766c50a | 72,741 |
def get_data(lookup_key: str, location: str) -> pd.DataFrame:
"""Retrieves data from an appropriate source.
Parameters
----------
lookup_key
The key that will eventually get put in the artifact with
the requested data.
location
The location to get data for.
Returns
... | 217c9f4dae939f7f073a98885638b9bbc64f342b | 72,742 |
def handle_http_error(response):
"""
Check HTTP response for errors and process them accordingly.
:param response: HTTP response to check
"""
if response.status_code != 200:
# check if there is some info about error in json format
if response.headers.get("content-type") == "applicat... | ca2f9ecc414b1d6a60a29f5e10952acf2cd4ada7 | 72,743 |
import math
import copy
def golden_section_search(var1, func, point=True, e=EPSILON, idx=0, print_stats=False):
"""
Golden section search algorithm
:param var1: Can be list with two elements representing the interval or can be single number from which we find unimodal interval.
:param func: Function t... | 698aa3750dc7632c0e27cb2381da4731af7ba5ae | 72,744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.