content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def do_flake8() -> str:
"""
Flake8 Checks
"""
command = "flake8"
check_command_exists(command)
command_text = f"flake8 --config {settings.CONFIG_FOLDER}/.flake8"
command_text = prepinform_simple(command_text)
execute(*(command_text.split(" ")))
return "flake 8 succeeded" | 1ffaf0ecfd5905f68a9136c597f56c6c86b8d5cb | 24,577 |
def counter_current_heat_exchange(s0_in, s1_in, s0_out, s1_out,
dT, T_lim0=None, T_lim1=None,
phase0=None, phase1=None,
H_lim0=None, H_lim1=None):
"""
Allow outlet streams to exchange heat until either the give... | e5654666a56ebd0e32fd3abcde472e138a510d6e | 24,578 |
def ReadCOSx1dsumSpectrum(filename):
"""
filename with full path
Purporse is to have other variation
of files and differnet way of reading in.
"""
wave,flux,dfp,dfm = np.loadtxt(filename,unpack=True,usecols=[0,1,4,5])
return np.array([wave,flux,dfp,dfm]) | a74a76a787ba3f0665c8f73d602e5259fa4828ac | 24,579 |
import cmath
import math
def op_atanh(x):
"""Returns the inverse hyperbolic tangent of this mathematical object."""
if isinstance(x, list):
return [op_atanh(a) for a in x]
elif isinstance(x, complex):
return cmath.atanh(x)
else:
return math.atanh(x) | 515da3d653f9ab4df6d87f5cec7d021ac2c98da9 | 24,581 |
from typing import Mapping
from typing import Any
from typing import Callable
import warnings
def find_intersections(
solutions: Mapping[Any, Callable],
ray_direction: Array,
target_center: Array,
) -> dict:
"""
find intersections between ray_direction and target_center given a mapping
of func... | a738fd0521a853c0be52bbf26d63ef515208b37a | 24,582 |
def Circum_O_R(vertex_pos, tol):
"""
Function finds the center and the radius of the circumsphere of the every tetrahedron.
Reference:
Fiedler, Miroslav. Matrices and graphs in geometry. No. 139. Cambridge University Press, 2011.
Parameters
-----------------
vertex_pos :
The positio... | 800ee6e56088a1c4df7149e911d4acbc175e2771 | 24,583 |
def reverse_one_hot(image):
"""
Transform a 2D array in one-hot format (depth is num_classes),
to a 2D array with only 1 channel, where each pixel value is
the classified class key.
#Arguments
image: The one-hot format image
#Returns
A 2D array with the same width and height a... | 912d4a5f9fbb3711b1af9dcd9c2092e6d71869bd | 24,584 |
import torch
def get_feature_clusters(x: torch.Tensor, output_size: int, clusters: int = 8):
""" Applies KMeans across feature maps of an input activations tensor """
if not isinstance(x, torch.Tensor):
raise NotImplementedError(f"Function supports torch input tensors only, but got ({type(x)})")
... | a43c2b98239f7474bf70747f464e29f4800159d8 | 24,585 |
def get_phone_operator(phonenumber):
"""
Get operator type for a given phonenumber.
>>> get_phone_operator('+959262624625')
<Operator.Mpt: 'MPT'>
>>> get_phone_operator('09970000234')
<Operator.Ooredoo: 'Ooredoo'>
>>> get_phone_operator('123456789')
<Operator.Unknown: 'Unknown'>
"""... | 01ec72a935b6fec466ab3113a61959d316d8f4b4 | 24,586 |
def projectpoints(P, X):
""" Apply full projection matrix P to 3D points X in cartesian coordinates.
Args:
P: projection matrix
X: 3d points in cartesian coordinates
Returns:
x: 2d points in cartesian coordinates
"""
X_hom = cart2hom(X)
X_pro = P.dot(X_hom) # 像素坐标系 齐次三维坐标
x = hom2cart(X_... | a16df6083a567215b474ec29d2b065c8a200c22c | 24,587 |
def mdot(a,b):
"""
Computes a contraction of two tensors/vectors. Assumes
the following structure: tensor[m,n,i,j,k] OR vector[m,i,j,k],
where i,j,k are spatial indices and m,n are variable indices.
"""
if (a.ndim == 3 and b.ndim == 3) or (a.ndim == 4 and b.ndim == 4):
c = (a*b).sum... | 36b8242bf8c643ff35362c4d19f3a222297a1eee | 24,589 |
def sample_duration(sample):
"""Returns the duration of the sample (in seconds)
:param sample:
:return: number
"""
return sample.duration | 9aaddb69b106ad941e3d1172c8e789b4969da99d | 24,590 |
def fetch_commons_memberships(from_date=np.NaN,
to_date=np.NaN,
on_date=np.NaN):
"""Fetch Commons memberships for all MPs.
fetch_commons_memberships fetches data from the data platform showing
Commons memberships for each MP. The memberships are ... | 0c9f72f9b2b1bdc090597a69a598ef638383fcf1 | 24,591 |
import win32com.client as win32
def excel_col_w_fitting(excel_path, sheet_name_list):
"""
This function make all column widths of an Excel file auto-fit with the column content.
:param excel_path: The Excel file's path.
:param sheet_name_list: The sheet names of the Excel file.
:return: File's col... | 57de5aa63317d4fae4c1f60b607082b8de1f5f91 | 24,592 |
def padding_reflect(image, pad_size):
"""
Padding with reflection to image by boarder
Parameters
----------
image: NDArray
Image to padding. Only support 2D(gray) or 3D(color)
pad_size: tuple
Padding size for height adn width axis respectively
Returns
-------
ret: N... | eb9f00bee89cb9a13fef0aa77e2c3eb0bfc8c92c | 24,594 |
def check_if_all_elements_have_geometry(geodataframes_list):
"""
Iterates over a list and checks if all members of the list have geometry
information associated with them.
Parameters
----------
geodataframes_list : A list object
A list object that contains one or more geopandas.GeoDataF... | 4ca7bcdd405c407a0a15be81876627e88a0d9c80 | 24,595 |
def conference_schedule(parser, token):
"""
{% conference_schedule conference schedule as var %}
"""
contents = token.split_contents()
tag_name = contents[0]
try:
conference = contents[1]
schedule = contents[2]
var_name = contents[4]
except IndexError:
raise t... | 037e000488a204a9d0094ccda72067ed70e5aa53 | 24,596 |
from typing import Tuple
import http
def run_delete_process() -> Tuple[str, http.HTTPStatus]:
"""Handles deleting tasks pushed from Task Queue."""
return _run_process(constants.Operation.DELETE) | 94a8c459ed67695894c28973f4a04faa2f2782aa | 24,597 |
def annotate(f, expr, ctxt):
"""
f: function argument
expr: expression
ctxt: context
:returns: type of expr
"""
t = f(expr, ctxt)
expr.type = t
return t | d8fb524f6ca2fbddef78aa150733e768d0e3da01 | 24,598 |
def _clip_boxes(boxes, im_shape):
"""Clip boxes to image boundaries."""
# x1 >= 0
boxes[:, 0::4] = np.maximum(boxes[:, 0::4], 0)
# y1 >= 0
boxes[:, 1::4] = np.maximum(boxes[:, 1::4], 0)
# x2 < im_shape[1]
boxes[:, 2::4] = np.minimum(boxes[:, 2::4], im_shape[1] - 1)
# y2 < im_shape[0]
... | 6b0e412f4aa8d4204530ebeca8a45928213847aa | 24,599 |
def gen_api_url(endpoint):
"""Construct a Wger API url given the endpoint"""
# type: (str) -> str
return WGER["host_name"] + WGER["api_ext"] + endpoint | 70623f9130b4dbde277a8c15b3f43a5168e4e487 | 24,600 |
from typing import Literal
def create_inputs(
data: np.ndarray,
input_type_name: Literal[
"data",
"data_one_column",
"one_in_one_out_constant",
"one_in_one_out",
"one_in_batch_out",
"sequentions",
],
input_type_params: dict,
mode: Literal["validate",... | bdb916915d561aa87435c2af5ea2f8b892f3c4b1 | 24,601 |
def CDLKICKINGBYLENGTH(df):
"""
函数名:CDLKICKINGBYLENGTH
名称:Kicking - bull/bear determined by the longer marubozu 由较长缺影线决定的反冲形态
简介:二日K线模式,与反冲形态类似,较长缺影线决定价格的涨跌。
python API
integer=CDLKICKINGBYLENGTH(open, high, low, close)
:return:
"""
open = df['open']
high = df['high']
low =... | e3a0c62627e8b4866580f232b5199570768c5197 | 24,602 |
def report_count_table_sort(s1, s2):
""" """
# Sort order: Class and scientific name.
columnsortorder = [0, 2, 3, 6] # Class, species, size class and trophy.
#
for index in columnsortorder:
s1item = s1[index]
s2item = s2[index]
# Empty strings should be at the end.
if... | cf207e4e8f524e48f99422017b17e643b66a9e78 | 24,603 |
import urllib
def serch_handler(msg):
"""
处理音乐搜索结果
:param msg: 搜索信息
:return:
"""
# url = 'https://www.ximalaya.com/revision/search?core=all&kw={0}&spellchecker=true&device=iPhone'
url = 'https://www.ximalaya.com/revision/search?kw={0}&page=1&spellchecker=false&condition=relation&rows=50&de... | e91620dce4d4b6e7d79ab0e8cbf612322f0248b3 | 24,604 |
def random(start: int, end: int) -> int:
"""Same as `random.randint(start, end)`"""
return randint(start, end) | 473f27e528d13cdb649b6e6d6e5ba32498a96cc1 | 24,605 |
def zero_check(grid):
"""Take a 2d grid and calculates number of 0 entries."""
zeros = 0
for row in grid:
for element in row:
if element == 0:
zeros += 1
return zeros | 0d69a948eef96937f8a5033256c3c4d9f22ce14d | 24,606 |
from typing import List
def get_channel_clips(channel: Channel) -> List[Clip]:
"""
Uses a (blocking) HTTP request to retrieve Clip info for a specific channel.
:param channel: A Channel object.
:returns: A list of Clip objects.
"""
clips = []
pagination = ""
while True:
query = gql.GET_CHANNEL_CLIPS_QUERY... | 7b5d5c19b0ac5f7ec665e8e453a529c5556cbadd | 24,607 |
def tensorflow2xp(tf_tensor: "tf.Tensor") -> ArrayXd: # pragma: no cover
"""Convert a Tensorflow tensor to numpy or cupy tensor."""
assert_tensorflow_installed()
if tf_tensor.device is not None:
_, device_type, device_num = tf_tensor.device.rsplit(":", 2)
else:
device_type = "CPU"
i... | 81bb8bea01e2e108c21022699005cb17cab12f0e | 24,608 |
def __str__(self, indent=0, func_role="obj"):
"""
our own __str__
"""
out = []
out += self._str_signature()
out += self._str_index() + ['']
out += self._str_summary()
out += self._str_extended_summary()
out += self._str_param_list('Parameters')
out += self._str_options('Options')... | 3e55fccb76f8e200ef7e57366c2ccd9609975959 | 24,609 |
def worker_years_6_download(request):
"""
纺织类通信带条件查询,然后下载对应结果文件
:param request:
:return:
"""
return download.worker_years_6_download(request) | 2250828132dff114665c4d6b3c4c6eb2a21840ce | 24,611 |
def set_autoscaler_location(autoscaler, is_regional, location):
""" Sets location-dependent properties of the autoscaler. """
name = autoscaler['name']
location_prop_name = 'region' if is_regional else 'zone'
autoscaler['type'] = REGIONAL_LOCAL_AUTOSCALER_TYPES[is_regional]
autoscaler['properties'... | 2e663856d4b4d9a3a477de9ce330cc5fe42502a1 | 24,612 |
from typing import Dict
from typing import Iterable
def _define_deformation_axes() -> Dict[str, Iterable[str]]:
"""Defines object sets for each axis of deformation."""
rgb_objects_dim = {}
for a in DEFORMATION_AXES:
rgb_objects_dim[a] = []
for v in _DEFORMATION_VALUES:
obj_id = f'{v}{a}'
# T... | d50384ca1261a312f48f9f6540252fa5f265cf80 | 24,613 |
def ldns_rr2buffer_wire_canonical(*args):
"""LDNS buffer."""
return _ldns.ldns_rr2buffer_wire_canonical(*args) | 5012bf22889ab0cd8375750bab8f54ca2ecb0da0 | 24,614 |
def get_stretch_factor(folder_name, indices, **kwargs):
""" Computes the stretch factor using the (16-50-84) percentile estimates
of x0 - x1 for each restframe wavelength assuming orthogonality
Parameters:
folder_name: folder containing the individual likelihoods and their
perc... | 17d61ba5205aada23b8f6b6a57c1920770a43408 | 24,615 |
def zonal_length(lat, nlon):
""" length of zonal 1/nlon segment at latitude lat"""
return R_earth * 2*np.pi/nlon * np.cos(lat*np.pi/180) | cf539ec73cae803a187d913c84ef7cb739cf8952 | 24,616 |
def create_gw_response(app, wsgi_env):
"""Create an api gw response from a wsgi app and environ.
"""
response = {}
buf = []
result = []
def start_response(status, headers, exc_info=None):
result[:] = [status, headers]
return buf.append
appr = app(wsgi_env, start_response)
... | 73dd8459cbf9b79655137536ff42195ba62c1372 | 24,618 |
def Squeeze(parent, axis=-1, name=""):
"""\
Dimension of size one is removed at the specified position (batch
dimension is ignored).
:param parent: parent layer
:param axis: squeeze only along this dimension
(default: -1, squeeze along all dimensions)
:param name: name of the output layer... | 3c8e6d6292e29d857412db1c74352b02aab99654 | 24,619 |
import attrs
def parse_namespace(tt):
"""
<!ELEMENT NAMESPACE EMPTY>
<!ATTLIST NAMESPACE
%CIMName;>
"""
check_node(tt, 'NAMESPACE', ['NAME'], [], [])
return attrs(tt)['NAME'] | 70a2f4e0ad0f8f98e38fde1892e9d40a34653af1 | 24,620 |
def clean(val, floor, ceiling):
"""Make sure RH values are always sane"""
if val > ceiling or val < floor or pd.isna(val):
return None
if isinstance(val, munits.Quantity):
return float(val.magnitude)
return float(val) | 6bf2822dc47a0b50cd88f05e2c127d97c5d71c0f | 24,621 |
from typing import Union
from typing import List
from typing import Tuple
def count_swaps_in_row_order(row_order: Union[List[int], Tuple[int]]) -> int:
"""
Counts the number of swaps in a row order.
Args:
row_order (Union[List[int], Tuple[int]]): A list or tuple
of ints representing the o... | c96fcb26fac03d252918f7cfa1dd3048eaf22320 | 24,622 |
def evaluate(ast, env):
"""Evaluate an Abstract Syntax Tree in the specified environment."""
print(ast)
if is_boolean(ast):
return ast
if is_integer(ast):
return ast
if is_string(ast):
return ast
if is_symbol(ast):
return env.lookup(ast)
if is_list(ast):
... | c9e5da8c9b073f72a2b27bfbb84a7939fbcec134 | 24,623 |
from datetime import datetime
import json
def load_data(
assets: tp.Union[None, tp.List[tp.Union[str,dict]]] = None,
min_date: tp.Union[str, datetime.date, None] = None,
max_date: tp.Union[str, datetime.date, None] = None,
dims: tp.Tuple[str, str] = (ds.TIME, ds.ASSET),
forward... | 83bd4221b92e2697bc79a416d0d5108fdb79ef27 | 24,624 |
def create_model(values):
"""create the model basing on the calculated values.
Args:
values (dict): values from the get_values_from_path function
Raises:
ValueError: if the loss function doesnt excist
Returns:
torch.nn.Module: model the network originally was trained with.
... | 9750fa13042572c8ca7a5f81ef73c87134a08431 | 24,625 |
def loss(logits, labels):
"""Calculates the loss from the logits and the labels.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
loss: Loss tensor of type float.
"""
loss = tf.reduce_mean(
tf.nn.softmax_cross... | 5d86168b8cffba3feb822120fd112835593a8d36 | 24,626 |
def create_pattern_neighbors_ca2d(width, height, n_states=2):
"""
Returns a list with the weights for 'neighbors' and 'center_idx' parameters
of evodynamic.connection.cellular_automata.create_conn_matrix_ca1d(...).
The weights are responsible to calculate an unique number for each different
neighborhood patte... | 53ce7cd0afb9f9b590754d299ba2d621489bc4e6 | 24,628 |
def by_colname_like(colname, colname_val):
"""
Query to handle the cases in which somebody has the correct
words within their query, but in the incorrect order (likely
to be especially relevant for professors).
"""
def like_clause_constructor(colname, colname_val):
"""
Helper fu... | 256f5e952fdff02f8de44c45b3283013547d0287 | 24,629 |
import json
def decode_classnames_json(preds, top=5):
"""
Returns class code, class name and probability for each class amongst top=5 for each prediction in preds
e.g.
[[('n01871265', 'tusker', 0.69987053), ('n02504458', 'African_elephant', 0.18252705), ... ]]
"""
if len(preds.shape) != ... | 807bed051300801a5e6a92bbc96324a66050f6c0 | 24,630 |
import math
def prime_decomposition(number):
"""Returns a dictionary with the prime decomposition of n"""
decomposition = {}
number = int(number)
if number < 2:
return decomposition
gen = primes_gen()
break_condition = int(math.sqrt(number))
while number > 1:
current_prime ... | 67062c15676e02747385e64e2dc177ea95d48de1 | 24,632 |
def levenshtein(s1, s2):
"""
Levenstein distance, or edit distance, taken from Wikibooks:
http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if not s1:
return len(s2)
previous_row = ... | 58ef88e60e454fda4b1850cc800f75a1d711a9af | 24,634 |
from typing import Tuple
from typing import Optional
def configure_mpi_node() -> Tuple[RabbitConfig, Celery]:
"""Will configure and return a celery app targetting GPU mode nodes."""
log.info("Initializing celery app...")
app = _celery_app_mpi
# pylint: disable=unused-variable
@app.task(
n... | bbc1c04ac8372ff8f5478d39d3f210e14b284c51 | 24,635 |
def customizations(record):
"""
Use some functions delivered by the library
@type record: record
@param record: a record
@rtype: record
@returns: -- customized record
"""
record = type(record)
# record = author(record)
record = convert_to_unicode(record)
# record = editor(r... | 32e47923e194a5fcb0540d9c2953be8d4dab019e | 24,636 |
def _has_letter(pw):
"""
Password must contain a lowercase letter
:param pw: password string
:return: boolean
"""
return any(character.isalpha() for character in pw) | 2f8eea521e8ca88001b2ecc3bc2501af8b14bbc8 | 24,638 |
import math
def closest_power_of_two(n):
"""Returns the closest power of two (linearly) to n.
See: http://mccormick.cx/news/entries/nearest-power-of-two
Args:
n: Value to find the closest power of two of.
Returns:
Closest power of two to "n".
"""
return pow(2, int(math.log(n, 2) + 0.5)) | 50d78d2a6de4f689ce268a95df97aae72dbd81ac | 24,639 |
def get_product(barcode, locale='world'):
"""
Return information of a given product.
"""
return utils.fetch(utils.build_url(geography=locale,
service='api',
resource_type='product',
param... | 409cfd2702ee06bab3e02bb446f0ce9d7e284892 | 24,640 |
def score(y_true, y_score):
""" Evaluation metric
"""
fpr, tpr, thresholds = roc_curve(y_true, y_score, pos_label = 1)
score = 0.4 * tpr[np.where(fpr>=0.001)[0][0]] + \
0.3 * tpr[np.where(fpr>=0.005)[0][0]] + \
0.3 * tpr[np.where(fpr>=0.01)[0][0]]
return score | b561e3cb3bd84d00c78dbd7e906e682c8758859d | 24,641 |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
list = []
x = 0
for var in range(0, num):
x = x + 1
if num % x == 0:
list.append(x)
return list | 848ed77fa92ae1c55d90a5236f0d9db6ae2f377c | 24,642 |
def files_page():
"""Displays a table of the user's files."""
user = utils.check_user(token=request.cookies.get("_auth_token"))
if user is None:
return redirect(location="/api/login",
code=303), 303
return render_template(template_name_or_list="home/files.html",
... | 58e627297c2d7b881c18459dc47a012b016cee3d | 24,643 |
def GetCodepage(language):
""" Returns the codepage for the given |language|. """
lang = _LANGUAGE_MAP[language]
return "%04x" % lang[0] | 7c84552d6b2f2747ee8365d89ba29bc7843054b7 | 24,644 |
def NumVisTerms(doc):
"""Number of visible terms on the page"""
_, terms = doc
return len(terms) | a6b762f314732d90c2371adf9472cf80117adae5 | 24,645 |
def replace_inf_price_nb(prev_close: float, close: float, order: Order) -> Order:
"""Replace infinity price in an order."""
order_price = order.price
if order_price > 0:
order_price = close # upper bound is close
else:
order_price = prev_close # lower bound is prev close
return ord... | 6b3581e31d69236c950a3ad812bb95eebbedcf10 | 24,646 |
def get_trend(d):
"""
Calcuate trend for a frame `d`.
"""
dv = d.reset_index(drop=True)
dv["minutes"] = np.arange(dv.shape[0], dtype=np.float64)
covariance = dv.cov()
return (((covariance["minutes"]) / covariance.loc["minutes", "minutes"])[d.columns]
.rename(lambda cl: "_".join(... | b649e60b8ef74b0a64ec935fde35271b68b0dad7 | 24,647 |
def getIpAddress():
"""Returns the IP address of the computer the client is running on,
as it appears to the client.
See also: system.net.getExternalIpAddress().
Returns:
str: Returns the IP address of the local machine, as it sees it.
"""
return "127.0.0.1" | d6aefaa4027a899344c762bc7df5ce40a5dbde4e | 24,648 |
def line(x, y, weights=None, clip=0.25):
"""Fit a line
Args:
x (numpy.array): x-values
y (numpy.array): y-values
clip (float, optional): Fit only first part. Defaults to 0.25.
Returns:
pandas.Series: fit parameters
"""
if 0 < clip < 1:
clip_int = int(len(x) ... | cfc794095e1b60f608b94d44480cb79ece0af653 | 24,649 |
def one_hot(data):
"""
Using pandas to convert the 'data' into a one_hot enconding format.
"""
one_hot_table = pd.get_dummies(data.unique())
one_hot = data.apply(lambda x: one_hot_table[x] == 1).astype(int)
return one_hot | fed9c171ae5b3bcdb78311afa47017c21e1c4b59 | 24,650 |
def update_set(j, n):
"""Computes the update set of the j-th orbital in n modes
Args:
j (int) : the orbital index
n (int) : the total number of modes
Returns:
Array of mode indexes
"""
indexes = np.array([])
if n % 2 == 0:
if j < n / 2:
indexes = np.a... | c1d91f245710b1e11aa7178db490f050827d5683 | 24,651 |
def chunklist(inlist: list, chunksize: int) -> list:
"""Split a list into chucks of determined size.
Keyword arguments:
inList -- list to chunk
chunkSize -- number of elements in each chunk
"""
if not isinstance(inlist, list):
raise TypeError
def __chunkyield() -> list:
# ... | 1351f0fa2ca208095a35ac0806a625f3227b24ef | 24,652 |
def getLocation(seq, meifile, zones):
""" Given a sequence of notes and the corresponding MEI Document, calculates and returns the json formatted list of
locations (box coordinates) to be stored for an instance of a pitch sequence in our CouchDB.
If the sequence is contained in a single system, only... | 18297c74cb867e018e7a4f3147cdd50ba1eb8225 | 24,653 |
import warnings
def calculate_A0_moving_LE(psi_baseline, psi_goal_0, Au_baseline, Au_goal, deltaz,
c_baseline, l_LE, eps_LE):
"""Find the value for A_P0^c that has the same arc length for the first bay
as for the parent."""
def integrand(psi_baseline, Al, deltaz, c ):
... | 9a01a8c02aa51db0a675e94bf32d6a4b26a13206 | 24,654 |
def create_train_val_set(x_train, one_hot_train_labels):
"""[summary]
Parameters
----------
x_train : [type]
[description]
y_train : [type]
[description]
"""
x_val = x_train[:1000]
partial_x_train = x_train[1000:]
y_val = one_hot_train_labels[:1000]
partial_y_tr... | dd0b3ca06b3d8bdae8e75284b17eb60ba6bbe36b | 24,655 |
def update_dataset_temporal_attrs(dataset: xr.Dataset,
update_existing: bool = False,
in_place: bool = False) -> xr.Dataset:
"""
Update temporal CF/THREDDS attributes of given *dataset*.
:param dataset: The dataset.
:param update_exist... | 99bb1a638e275a4788e2bd99122b67d3f0d5b536 | 24,658 |
def py_cpu_nms(dets, thresh):
"""Pure Python NMS baseline."""
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
## index for dets
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i... | 78d5b3c672142dc1861a2df11e6f1a4671467fd4 | 24,659 |
import itertools
def _split_iterators(iterator, n=None):
"""Split itererator of tuples into multiple iterators.
:param iterator: Iterator to be split.
:param n: Amount of iterators it will be split in. toolz.peak can be used to determine this value, but that is not lazy.
This is basically the same a... | 25b9409941eaf958aef755c0124d4aee4a3a67e5 | 24,660 |
def get_league_listing(**kwargs):
"""
Get a list of leagues
"""
return make_request("GetLeaguelisting", **kwargs) | 5b5fb9ee4f06a0ede684f6584fd3af0638c807a4 | 24,661 |
async def perhaps_this_is_it(
disc_channel: disnake.TextChannel = commands.Param(lambda i: i.channel),
large: int = commands.Param(0, large=True),
) -> PerhapsThis:
"""This description should not be shown
Parameters
----------
disc_channel: A channel which should default to the current one - us... | 158d9d6b278c5142d13e392becd9df35c2844961 | 24,662 |
def maybe_setup_moe_params(model_p: InstantiableParams):
"""Convert a FeedforwardLayer to a MoE Layer for StackedTransformer."""
if model_p.cls == layers.StackedTransformerRepeated:
model_p = model_p.block
if model_p.num_experts == 0:
return model_p
ff_p = model_p.transformer_layer_params_tpl.tr_fflay... | 2ba82eb85ca85f8c16b3ee5de2d8ac3edb90275a | 24,663 |
import re
def verify_message( message ):
"""Verifies that a message is valid. i.e. it's similar to: 'daily-0400/20140207041736'"""
r = re.compile( "^[a-z]+(-[0-9])?-([a-z]{3})?[0-9]+/[0-9]+" )
return r.match( message ) | f25a37a5e3f076a647c0a03c26d8f2d2a8fd7b2e | 24,664 |
def get_all_unicode_chars():
"""Get all unicode characters."""
all_unicode_chars = []
i = 0
while True:
try:
all_unicode_chars.append(chr(i))
except ValueError:
break
i += 1
return all_unicode_chars | da63b26dd082987937b17fdfffb1219726d9d2c6 | 24,665 |
def get_east_asian_width_property(value, binary=False):
"""Get `EAST ASIAN WIDTH` property."""
obj = unidata.ascii_east_asian_width if binary else unidata.unicode_east_asian_width
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['eastasianwidth'].get(negate... | 9eb8f70229a6d53faae071b641a39b79d8807941 | 24,666 |
def ModifyListRequest(instance_ref, args, req):
"""Parse arguments and construct list backups request."""
req.parent = instance_ref.RelativeName()
if args.database:
database = instance_ref.RelativeName() + '/databases/' + args.database
req.filter = 'database="{}"'.format(database)
return req | fde5a06cde30ed1cf163299dc8ae5f0e826e3f9d | 24,667 |
from datetime import datetime
def day_start(src_time):
"""Return the beginning of the day of the specified datetime"""
return datetime(src_time.year, src_time.month, src_time.day) | 2bcc7b136e5cb1e7929e6655daf67b07dbbaa542 | 24,669 |
def _construct_corrections_dict(file):
"""Construct a dictionary of corrections.
Given the name of a .ifa corrections file, construct a dictionary
where the keys are wavelengths (represented as integers) and the values
are measures of the instrument sensitivity (represented as floats).
Intensi... | 972db28c3609357a0ce742bf6679fbb46b86ef7c | 24,670 |
def get_activation_func(activation_label):
""" Returns the activation function given the label
Args:
activation_label: Name of the function
"""
if activation_label == 'sigmoid':
return tf.nn.sigmoid
elif activation_label == 'identity':
return tf.identity
elif activation_l... | cfa1a46b9c40fe2680bfa49831ed09e222ef3335 | 24,671 |
def sim_share(
df1, df2, group_pop_var1, total_pop_var1, group_pop_var2, total_pop_var2,
):
"""Simulate the spatial population distribution of a region using the CDF of a comparison region.
For each spatial unit i in region 1, take the unit's percentile in the distribution, and swap the group share
wit... | cc7857d6deb81e7224e4e21fe6908376c963169a | 24,672 |
def fixextensions(peeps, picmap, basedir="."):
"""replaces image names with ones that actually exist in picmap"""
fixed = [peeps[0].copy()]
missing = []
for i in range(1, len(peeps)):
name, ext = peeps[i][2].split(".", 1)
if (name in picmap):
fixed.append(peeps[i].copy())
... | d2af911aacea80f7e25cbdde0f5dfad0f1757aee | 24,673 |
def do_divide(data, interval):
"""
使用贪心算法,得到“最优”的分段
"""
category = []
p_value, chi2, index = divide_data(data, interval[0], interval[1])
if chi2 < 15:
category.append(interval)
else:
category += do_divide(data, [interval[0], index])
category += do_divide(data, [index,... | 2e25f913c664dd1cc3d60e4c3f89146b81476e3b | 24,674 |
import json
def get_config(key_path='/'):
"""
Return (sub-)configuration stored in config file.
Note that values may differ from the current ``CONFIG`` variable if it was
manipulated directly.
Parameters
----------
key_path : str, optional
``'/'``-separated path to sub-configurati... | 075b3cd021be67c5c2f23203236f839fc47a678b | 24,675 |
def _get_options():
"""
Function that aggregates the configs for sumo and returns them as a list of dicts.
"""
if __mods__['config.get']('hubblestack:returner:sumo'):
sumo_opts = []
returner_opts = __mods__['config.get']('hubblestack:returner:sumo')
if not isinstance(returner_opt... | 3d4d491b12f89501e7f5cdadda1d983676027367 | 24,678 |
from typing import Any
from typing import Optional
def convert_boolean(value: Any) -> Optional[bool]:
"""Convert a value from the ToonAPI to a boolean."""
if value is None:
return None
return bool(value) | d479898afe1bb8eaba3615a9e69a7a38637c6ec6 | 24,679 |
def Split4(thisBrep, cutters, normal, planView, intersectionTolerance, multiple=False):
"""
Splits a Brep into pieces using a combination of curves, to be extruded, and Breps as cutters.
Args:
cutters (IEnumerable<GeometryBase>): The curves, surfaces, faces and Breps to be used as cutters. Any othe... | 74009e33a3da88c7d096e6835952014bc8b40ef9 | 24,680 |
def generate_passwords_brute_force(state):
"""
String Based Generation
:param state: item position for response
:return:
"""
if state is None:
state = [0, 0]
k, counter = state
password = ''
i = counter
while i > 0:
r = i % base
password = alphabet[r] + pa... | 11e503e53903c884545c2324e721ebcbad1eb7c2 | 24,681 |
from typing import Tuple
import ctypes
def tparse(instring: str, lenout: int = _default_len_out) -> Tuple[float, str]:
"""
Parse a time string and return seconds past the J2000
epoch on a formal calendar.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html
:param instring: Inp... | 33b322062e7756d9bc1d728d9655adafd1c4d989 | 24,682 |
def align_decision_ref(id_human, title):
""" In German, decisions are either referred to as 'Beschluss' or
'Entscheidung'. This function shall align the term used in the
title with the term used in id_human.
"""
if 'Beschluss' in title:
return id_human
return id_human.replace('Be... | ac4f584b8e008576816d9a49dba58bc9c9a6dbc4 | 24,683 |
def get_headers(soup):
"""get nutrient headers from the soup"""
headers = {'captions': [], 'units': []}
footer = soup.find('tfoot')
for cell in footer.findAll('td', {'class': 'nutrient-column'}):
div = cell.find('div')
headers['units'].append(div.text)
headers['captions'].append... | 5e7772a8830271f800791c75ef7ceecc98aba2bb | 24,684 |
def table2rank(table, transpose=False, is_large_value_high_performance=True, add_averaged_rank=False):
"""
transform a performance value table to a rank table
:param table: pandas DataFrame or numpy array, the table with performance values
:param transpose: bool, whether to transpose table (default: Fal... | 36b313b8c19f6767690b4ef6d76fcc4b5633865c | 24,685 |
def F_z_i(z, t, r1, r2, A):
""" Function F for Newton's method
:param z:
:param t:
:param r1:
:param r2:
:param A:
:return:
F: function
"""
mu = mu_Earth
C_z_i = c2(z)
S_z_i = c3(z)
y_z = r1 + r2 + A * (z * S_z_i - 1.0) / np.sqrt(C_z_i)
F = (y_z / C_z_i) ** 1.... | ca4af99f8722d8e932f58896120883f09e73fb1a | 24,686 |
from tayph.vartests import typetest
import numpy as np
from astropy.stats import mad_std
def sigma_clip(array,nsigma=3.0,MAD=False):
"""This returns the n-sigma boundaries of an array, mainly used for scaling plots.
Parameters
----------
array : list, np.ndarray
The array from which the n-sig... | e62e76c0a92dde4de324a31ecc03968da18de7d3 | 24,687 |
def points_distance(xyz_1, xyz_2):
"""
:param xyz_1:
:param xyz_2:
:return:
"""
if len(xyz_1.shape) >= 2:
distance = np.sqrt(np.sum((xyz_1 - xyz_2)**2, axis=1))
else:
distance = np.sqrt(np.sum((xyz_1 - xyz_2)**2))
return distance | 0acc6bf45c03ed554cb13c4375095871dee482fb | 24,688 |
from typing import Optional
def ensure_society(sess: SQLASession, name: str, description: str,
role_email: Optional[str] = None) -> Collect[Society]:
"""
Register or update a society in the database.
For existing societies, this will synchronise member relations with the given list of ... | 49700a80ab23b0f4211c8bf5f0bc2c1d68c2f1cb | 24,689 |
def odd_numbers_list(n):
""" Returns the list of n first odd numbers """
return [2 * k - 1 for k in range(1, n + 1)] | 2066cf07e926e41d358be0012a7f2a248c5987a7 | 24,690 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.