content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def json_dumps(value, indent=2):
"""
JSON dumps that supports Unicode and the :code:`as_raw` property of objects
if available.
"""
return json.dumps(value, indent=indent, ensure_ascii=False, cls=JsonAsRawEncoder) | e3b505cdf0e94419c15aa5b102c35691b91ac7cd | 3,608,135 |
import ast
def parse_version(fpath):
"""
Statically parse the version number from a python file
"""
if not exists(fpath):
raise ValueError('fpath={!r} does not exist'.format(fpath))
with open(fpath, 'r') as file_:
sourcecode = file_.read()
pt = ast.parse(sourcecode)
class F... | 71f0f8f63cf8ef289188c9499d8d7c4ccf3128c4 | 3,608,136 |
def _get_setting(setting=False,host=False,hostTag=False):
""" Returns the host's settings (or the specified one) """
if not host:
if not hostTag:
host = env.host
else:
for hostName in env.settings_by_host:
if _has_tag(hostTag, hostName):
... | 8bff7901ba6bc355789f20d9a914faa7b2a6ef20 | 3,608,138 |
async def get_userinfo(request):
"""
Return a dict with session informations
{
"username" <Std>
"user_id" <Int>
"is_admin" <Bool>
}
"""
username = request.cirrina.web_session.get("username")
if username:
user = (
request.cirrina.db_session.query(... | dc0f8e789331d02dec51e59bfb8bf90fd2e1d6e5 | 3,608,139 |
def update_batch_entry(db_path, id, status, start_time, end_time):
"""
Update the status and the start/end time of a specified batch entry
Return True if update succeeded, False otherwise
Parameters
----------
db_path : string
id : integer
status : string
start_time : datetime strin... | 0a1ac1d4014003a756962a1111c8b3d228cffac0 | 3,608,140 |
import re
def split_element_symbol(element):
"""
From element symbol, split charge and occupancy
symbol, occupancy, charge = split_element_symbol('Co3+')
Any numbers appended by +/- are taken as charge, otherwise they are counted as occupancy.
e.g. element > symbol | occupancy | ... | 97496f26ea68f5ccd8d3c2be90f651990a3084e2 | 3,608,141 |
def stable_rs(r):
"""Calculates r_s from r under stable population variance, where
r^2 + r_s^2 = 1"""
return np.sqrt(1 - np.square(r)) | 1987d7941c30763ea517a95b9e9ccc4e5fc536ff | 3,608,142 |
import time
def GALE2(n_proc=10,frontSize=100,iters=1000,model=DTLZ2(n_dec=30, n_obj=3)):
"""
WHY do threads take more time than single processors?? FIX THIS!!!
:param n_proc:
:param frontSize:
:param iters:
:param model:
:return:
"""
t = time()
collect=[]
final = []
popSize = [int(frontSize/n... | dee916e3bff91a45d92a7e821fad461f5d556028 | 3,608,143 |
def pmm_compute(pmm, x):
"""For a given PMM object and x-coordinate, compute the probability matched
value (i.e. the x-coordinate for which the target CDF has the same value as
the source CDF).
Parameters
----------
pmm: dict
A PMM object returned by pmm_init.
x: float
The c... | 1ccc6dd4f8ca3872fcdf8fbb5a47303c4aa9ef51 | 3,608,144 |
from subroutines import Factorizer, euler_totient
def euler_problem_69(bound=10 ** 6):
"""
Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of numbers less than n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine an... | 3cc53510f51ea72b7599e2db726513095ce5bcdf | 3,608,145 |
def lp_nonempty_eqs(boxsize):
"""Linear equations (as lists of coefficients) which correspond to
every cell having one symbol."""
return [lp_nonempty_eq(cell, boxsize) for cell in cells(boxsize)] | 06c8f573851f468d7bd51818a1c0219fd0931c4f | 3,608,146 |
def mask_large_samples(data, thres, obs_min, static=None, return_mask=False):
"""Remove outliers by cutoff in order to fit data into memory (one outlier patient has 11k observation values)."""
result_data = []
n = len(data) #number of data views of compact format (values, times, indices, ..)
mask = data... | 0657841ccc7c0357f83c23d1d05393b77e419968 | 3,608,147 |
def shortid(obsid):
"""
Compact format for the observation id, like QPT
Parameters
----------
obsid : string
Program id string
Returns
-------
shortid : string
Compact format
"""
idvals = obsid.split('-')
shortid = idvals[0][-1] + idvals[1][2:] + '-' + idv... | cb163886e7612fa46d016f2037b110526967c61f | 3,608,148 |
def make_metrics(predictions, labels, encoded_variants):
"""Creates our evaluation metrics."""
# Define the metrics we'll get for each variant selection:
raw_metrics = {
'Accuracy': tf.metrics.accuracy,
'Precision': tf.metrics.precision,
'Recall': tf.metrics.recall,
'FPs': tf.metrics.false... | d31a97ef70001674ae99f2864d171ae5e96c9fb5 | 3,608,150 |
def make_figure(df,pa):
"""Generates figure.
Args:
df (pandas.core.frame.DataFrame): Pandas DataFrame containing the input data.
pa (dict): A dictionary of the style { "argument":"value"} as outputted by `figure_defaults`.
Returns:
A Plotly figure
"""
#UPLOAD ARGUM... | 2e1be9d1268c17bc4a247e7b6d30b760a8b050fc | 3,608,152 |
from typing import Optional
def get_automation(automation_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAutomationResult:
"""
The security automation resource.
API Version: 2019-01-01... | 21c4568ac5fc99e52a33cd56d6156bd7bd613d64 | 3,608,153 |
from typing import Counter
def find_children(dancing_brigade):
"""
"aAbaBb" => "AaaBbb".
"""
new = ''
s = [x.lower() for x in dancing_brigade]
d = Counter(sorted(s))
for x in d:
new += (x * d[x]).title()
return new | 81d7dd9661fc73e6fcb24bc0e5318e298c41c3e5 | 3,608,154 |
def get_type_code(stage: ImportStage, value: ir.Value) -> ir.Value:
"""Gets the TypeCode (see C++ BuiltinTypeCode) associated with a value.
This always returns an integer<32>, which is expected by macros which
operate on type codes.
"""
return d.GetTypeCodeOp(d.IntegerType.get_explicit(32), value).result | caf0fc6f8ef81961d576138073317cdba60bbb53 | 3,608,156 |
def _sequential_gaussian_tensordot(gaussian):
"""
Integrates a Gaussian ``x`` whose rightmost batch dimension is time, computes::
x[..., 0] @ x[..., 1] @ ... @ x[..., T-1]
"""
assert isinstance(gaussian, Gaussian)
assert gaussian.dim() % 2 == 0, "dim is not even"
batch_shape = gaussian.... | 0e5142fcce3d4b967b3b1f7291bbc0f791b6d596 | 3,608,158 |
import struct
def read_fmt(fmt, fp):
"""
Reads data from ``fp`` according to ``fmt``.
"""
fmt = str(">" + fmt)
fmt_size = struct.calcsize(fmt)
data = fp.read(fmt_size)
try:
assert len(data
) == fmt_size, 'read=%d, expected=%d' % (len(data), fmt_size)
except A... | 3bcee164ca137d64f0a97621f6b3917b7ad60899 | 3,608,159 |
def _is_slot_attr(a_name, base_attr_map):
"""
Check if the attribute name comes from a slot class.
"""
return a_name in base_attr_map and _is_slot_cls(base_attr_map[a_name]) | 58810031dee5ff0e3ff390e7cf17f0b55166f966 | 3,608,160 |
def get_root_url(link_string):
"""
Will always return a string with a correct trailing slash or None for invalid string
link: a string of a url in the form https://help.github.com/enterprise/2.7/user/
utilized tld to obtain the subdomain and tld of the string in order to return a string
of t... | 086364752974d0af88273e016e578e3e5d986443 | 3,608,161 |
import re
import warnings
def parse_url(url, warning=True):
"""Parse URLs especially for Google Drive links.
file_id: ID of file on Google Drive.
is_download_link: Flag if it is download link of Google Drive.
"""
# test=url.split('drive')
# print(test)
# if len(test)>1:
# url='https://drive.{}'.format(test... | a3ddd648e455474986449f71060cf138df84fd9d | 3,608,162 |
def compute_bt(bx, by, bz, bx_err, by_err, bz_err, mask, bitmask, nx, ny):
"""function: compute_bt
This function calculates B_t, the total field, in units of Gauss.
(The magnetic field has native units of Gauss since the filling factor = 1).
"""
bt = np.zeros([ny,nx])
bt_err = np.zeros([n... | d77a1748852462373bc19d18ca9da8d58676108e | 3,608,163 |
def stdin(pattern, starting_string=None, grep_args=None,
format_chained=True, chained=None, chained_status=None):
"""
Given a target string, call ``grep`` to search for for ``pattern`` in that
string.
By default, the ``starting_string`` will have ``.format()`` called on it with
``chained`... | dbd89d70b14c7ed7a0722489f66eadfa5a863f75 | 3,608,164 |
def fib_g(n) :
"""
The function fib_g is used to find the nth fibonacci number using the golden
ratio i.e. 1.618033 by using the formula :
fibonacci = (phi**n) / 5**(0.5).
This results in a floating answer hence we use round function to round it
off to the nearest integer.
"""
phi ... | 062cd16968eb34cc5135cd79120ea16fd81f486a | 3,608,165 |
from typing import Tuple
import shutil
def user_id_folder(request: FixtureRequest) -> Tuple[str, str]:
"""Create return a test user folder and the fitting user_id as Tuple.
A finalizer is added to remove the created user folder at the end of the test.
"""
user_id = "test-user"
folder = create_use... | d4263aedfd7700906938df036db171af249ded63 | 3,608,167 |
def RSI(df, n):
"""
相对强弱指标
Args:
df (pandas.DataFrame): Dataframe格式的K线序列
n (int): 周期n
Returns:
pandas.DataFrame: 返回的DataFrame包含1列, 是"rsi", 代表计算出来的相对强弱指标
Example::
# 获取 CFFEX.IF1903 合约的相对强弱指标
from tqsdk import TqApi, TqSim
from tqsdk.ta import RSI
... | 27dfe34d5659ee1577a481c7c5bb0072b2b4570d | 3,608,168 |
def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers.
"""
# Find all instances of naked twins
for uni... | 5a14f73c2e055be0c1d03fd6145c83c7f8b73f4b | 3,608,169 |
def show_all():
""" 显示所有用户微博"""
resp = make_response(redirect(url_for('.index')))
resp.set_cookie('show_followed', '', max_age=30*24*60*60)
return resp | 196f7a23d08155d34e25d9163916d72402954d20 | 3,608,170 |
def nacl_bindings_pick_scrypt_params(opslimit, memlimit):
"""Python implementation of libsodium's pickparams"""
if opslimit < 32768:
opslimit = 32768
r = 8
if opslimit < (memlimit // 32):
p = 1
maxn = opslimit // (4 * r)
for n_log2 in range(1, 63): # pragma: no branch... | 509b011c75bd3c62add012b6808521bacba7c5ea | 3,608,171 |
import copy
import re
def parse_metadata(notebook_metadata):
"""Parse the Notebook's metadata and update it when needed.
Args:
notebook_metadata (dict): metadata annotated by Kale.
Refer to DEFAULT_METADATA for defaults
Returns (dict): updated and validated metadata
"""
# check f... | f770e54d80d61d9f49b375d6a025e34b0ca1355f | 3,608,172 |
import re
def columns_to_add(column_names):
"""Subsets the list for elements that contain mean and then rename them
so they aren't called mean, these will be the new names for columns
to be simluated probabilistically
Inputs:
column_names - a list of parameter names / df indexes
... | 227dc85dab3fe35f999e416a44208a37d7e77665 | 3,608,173 |
def forcefield(x_lims, basis, force_coeffs):
"""Compute and save the force field that have been fitted
Parameters
----------
x_lims: array, shape (dim_x,3)
Bounds of the plot
basis: GLE_BasisTransform instance
The instance of the basis projection
force_coeffs: array-like
... | a7e809a9243d74e62fcc476b2497e4642388e67e | 3,608,175 |
def get_email_password():
"""Helper function that returns the tuple of defaul email and password"""
email = 'test@greatsoft.uz'
password = 'password1234'
return email, password | 80fe300fa0e7c316dc484b2d8ed2cb031d0215f1 | 3,608,177 |
def polyfit(dates, levels, p):
"""
Function that finds the least-square fit polynomial from
Args:
dates (list): The list of dates for the x-axis.
levels (list): The corresponding water level for each date, y-axis.
p (int): The degree of polynomial that is desired.
Retur... | 98b483de29537a479c3ee318c6bcf09b8333da3c | 3,608,178 |
def guided_grad_cam(grad_cam_mask, guided_backprop_mask):
"""
Guided grad cam is just pointwise multiplication of cam mask and
guided backprop mask, returns this multiplication
GRAD_CAM_MASK: Class activation map mask
GUIDED_BACKPROP_MASK:Guided backprop mask
Attribution: https://github.com/utku... | 203916a5f49b7c94874a67d2e0486c16f125171d | 3,608,179 |
from typing import Dict
from typing import Any
import configparser
import ast
def parse_config(config_string: str) -> Dict[str, Dict[str, Any]]:
"""Parse config for pipeline.
Args:
config_string: Configuration file rendered as a string.
Returns:
A dictionary mapping parameters for each p... | 36ad0258335de406cc9fa2cc9535c681a815e5ff | 3,608,181 |
def parse_type_line(type_line, rcb, loc):
"""Parses a type annotation specified as a comment.
Example inputs:
# type: (Tensor, torch.Tensor) -> Tuple[Tensor]
# type: (Tensor, Tuple[Tensor, Tensor]) -> Tensor
"""
arg_ann_str, ret_ann_str = split_type_line(type_line)
try:
arg... | fb79e6d42c13b452994f9eaed39a38b0652fcaa2 | 3,608,183 |
def get_unique_words():
"""
Runs a COUNT DISTINCT on the word_details table
"""
return _execute_query(_GET_WORD_COUNT_QUERY)[0][0] | 1c8564854f94eb286de6e201d6dd814cf4bb2374 | 3,608,184 |
def unit_of_work(func, *args, **kw):
"""
Decorator that handles beginning and ending a unit of work.
"""
with inline_unit_of_work():
return func(*args, **kw) | d7e8d4b1cf940eacf90873d4a6993bdeb6ff0495 | 3,608,186 |
def UserUrlToUserId(user_url: str) -> int:
"""用户个人主页 Url 转用户 ID
Args:
user_url (str): 用户个人主页 Url
Returns:
int: 用户 ID
"""
AssertType(user_url, str)
AssertUserUrl(user_url)
json_obj = GetUserJsonDataApi(user_url)
result = json_obj["id"]
return result | f6ef535aafe2351964fc8214bc53554afbd29dd6 | 3,608,187 |
from typing import OrderedDict
def job_prep_release_status_list_table_format(result):
"""Format job prep-release-status list as a table."""
table_output = []
for item in result:
table_row = OrderedDict()
table_row['Pool Id'] = item['poolId']
table_row['Node Id'] = item['nodeId']
... | 5b93ade505b166cd45539bfde49e8f51f2ffb9fb | 3,608,188 |
import torch
def log_likelihood(a: Tensor,
b_lower: Tensor,
b_upper: Tensor,
t: Tensor) -> Tensor:
"""
Graded Response Model の log likelihood を計算する。
Σ log( sigmoid(a * (t - b_lower)) - sigmoid(a * (t - b_upper)) )
だが、素朴に計算すると桁落ちで誤差が大きくなったりするので対... | a5c4f61c1cb8ff7b8e30f2ea7ba750afb186a507 | 3,608,189 |
def rinko_p_prime(N, t, A, B, C, D, E, F, G, H):
"""
Per RinkoIII manual: 'The film sensing the water is affect by environment
temperature and pressure at the depth where it is deployed. Based on experiments,
an empirical algorithm as following is used to correct data dissolved oxygen.'
Parameters
... | 482f2286819af3d147cde4dd258c36c04624a6e8 | 3,608,190 |
def resnet_v2_101(inputs,
num_classes=None,
global_pool=True,
reuse=None,
scope='resnet_v2_101'):
"""ResNet-101 Model of [1]. See resnet_v2() for arg and return description."""
blocks = [
Block(
'block1', bottleneck, [(256, 64, ... | 9a67ffc2cb40decab15d1007b7738d70e2e8a09e | 3,608,191 |
def Mh(a: float, mu: float, t_r: float, t: float) -> float:
"""
Mh = sqrt(mu / a ** 3) * (t - t_r)
:param a: semi-major axis
:type a: float
:param mu: G * (m1 + m2)
:type mu: float
:param t_r: reference time
:type t_r: float
:param t: time
:type t: float
:return: Mh angle
... | 05fbb11f4b189be97569bd9b72f160e7c3253c76 | 3,608,192 |
def NotationRole(role, rawtext, text, lineno, inliner, options={}, content=[]):
#pylint: disable=unused-argument, dangerous-default-value
"""Any text using the notation syntax (``@id``, ``{+, …}``, etc.).
Use this to explain tactic equivalences. For example, you might write
this::
:n:`generali... | e5669827a365f9377c8d68950e883283ce6fb29b | 3,608,193 |
def _index(i, size, Cartesian=True):
"""If Cartesian=True, index 0 is swapped with index 1."""
if Cartesian:
if i == 1:
return 0
if i == 0:
if size >= 2:
return 1
return i | ace0ff4431b64b545f2857eddce85d555a0cf5f3 | 3,608,195 |
import re
def find_meta(meta):
"""
Extract __*meta*__ from META_FILE.
"""
meta_match = re.search(
r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M
)
if meta_match:
return meta_match.group(1)
raise | 0a8706c7d6e712578178a33542692437aa9545be | 3,608,196 |
def test_inject_prent(injector):
"""Dependencies must not be providable via parent class"""
class A:
pass
class B(A):
pass
b = B()
@injector.consumer
def consume(a_: B):
assert a_ is b
@injector.provider
def bean() -> A:
return b
with pytest.raise... | 8dd8607c08fa885251bd0913163c94277ae33a64 | 3,608,197 |
def client_request_unauthenticated():
"""
gets a mock client request object which is unauthenticated.
:rtype: CoreRequestMock
"""
test_session_services.clear_current_request()
test_session_services.inject_new_request()
payload = DTO(sub=400, auth='test')
access_token = token_services.g... | b1a4f6ebd9de8b88016ab262e52793d9dcd2767d | 3,608,199 |
def teamtsv(req):
"""
Creates teams.tsv on server drive for use with DomJudge.
"""
if req.method == 'GET':
ExportCSV("Team")
return HttpResponseRedirect('/createtsv') | e4d1a154e8f1fad4fd22be1e6a97a74c44347086 | 3,608,201 |
def binary_search(
array: list, element, start_idx: int = None, stop_idx: int = None
) -> int:
"""Code based on https://stackabuse.com/binary-search-in-python/"""
if start_idx is None:
start_idx = 0
if stop_idx is None:
stop_idx = len(array) - 1
if start_idx > stop_idx:
rai... | 03bd00b811f6a8895221fdc7697e96a0d4ae0cd5 | 3,608,202 |
def _urlnode_render_replacement(self, context):
"""Replacement for django's {% url %} block.
This version uses WSGIApplication's url mapping to create urls.
Examples:
<a href="{% url MyPageHandler "overview" %}">
{% url MyPageHandler implicit_args=False %}
{% url MyPageHandler "calendar" %}
{% url MyPa... | 932e38d500aada0cd975a40c8c5b05bf62aa3815 | 3,608,203 |
def InitNN(num_inputs, num_hiddens, num_outputs):
"""Initializes NN parameters.
Args:
num_inputs: Number of input units.
num_hiddens: List of two elements, hidden size for each layer.
num_outputs: Number of output units.
Returns:
model: Randomly initialized n... | f4ca73802e933df7a99fb936029ee4d75d679f5c | 3,608,204 |
def evaluate_and_save_in_background(query, target_directory=None, target_file=None):
"""Like evaluate_and_save, but returns immediately and runs in the background.
Note that the saving occurs on o worker. Eventual remote workers will save the results in their local filesystem.
"""
global _worker_config
... | ea485262b24bf5577c4260849abe71dd85e6f056 | 3,608,205 |
def get_element(dict, key, default=None):
"""" if dict[key] present, return that. Otherwise return default value"""
value = dict[key] if key in dict else default
return value | ac3cc2ea1ff38a42c0e674fee56a43bcb2b71660 | 3,608,206 |
def nmap(value, fr=(0, 1), to=(0, 1)):
"""
Map a value from a two-value interval into another two-value interval.
Both intervals are `(0, 1)` by default. Values outside the `fr` interval
are still mapped proportionately.
"""
value = (value - fr[0]) / (fr[1] - fr[0])
return to[0] + value * (t... | d7968d7661c2535f5c820087b79b7a8e3667e8e8 | 3,608,207 |
def giphy(config, terms):
""" Return giphy for given terms. """
terms = ' '.join(terms)
if terms:
img = translate(terms, api_key=config['giphy']['api_key'])
else:
img = translate('random', api_key=config['giphy']['api_key']) # hack
url = img.fixed_height.downsampled.url
return [... | a4e534bcad8695dacc2943cb7155641eda3e1952 | 3,608,209 |
def get_best_outputs(problem_dir, problem, user):
"""
Gets outputs of best submission.
:param problem_dir: main directory of submissions
:param problem: id of problem
:param user: user who wants to see submission for problem
:return: -1 if no file found, otherwise array of be... | a012b849ec76056067a75a71d80ea2911b2b91fc | 3,608,210 |
import time
def computeStatistics(sqlContext,df):
"""Compute all of the statistics for a given dataframe
Input: sqlContext: to perform SQL queries
df: dataframe with the fields
Station(string), Measurement(string), Year(integer), Values (byteArray with 365 float16 numbers)
returns... | d11f1ab6e462e5d6c48e66a70afddc770df8859c | 3,608,211 |
def ambiguous_count(seq):
"""count the number of possible sequences from ambiguous DNA input"""
d = IUPAC.IUPACData.ambiguous_dna_values
return np.prod([len(d[base]) for base in seq]) | 438970004eeabba3c44b1a33ed28871b15766b62 | 3,608,212 |
import torch
def bmv(mat, vec):
"""batch matrix vector product"""
return torch.einsum('bij, bj -> bi', mat, vec) | e6f2d95a0aec5239eaa96fe0a6dd371216eb741b | 3,608,214 |
import typing
def dc2avsc(
schema,
*,
request=None,
include_fields: typing.List[str] = None,
exclude_fields: typing.List[str] = None,
namespace="inverter",
ignore_required=True,
):
"""
Converts ``dataclass`` to Avro Schema JSON dictionary
:param schema: ``dataclass`` class
... | 4291bd6a7eeb5f5f946bdea2ca7399899ba77ad4 | 3,608,215 |
def initialize(L, H, R,
interface_thickness, solutes, restart_folder,
field_to_subspace,
inlet_velocity, concentration_left,
enable_NS, enable_PF, enable_EC,
**namespace):
""" Create the initial state.
The initial states are specified in... | 2db98a7fab70eda819520c7d820bdfc248cc26bd | 3,608,216 |
def encode_path(file_path):
"""Returns a URL-encoded version of a path
"""
return quote(file_path) | d0d945534cba5400378d6bc83d2d75bedc8914b7 | 3,608,217 |
def log_data_controller(request):
"""
:param request:
:return:
"""
# if request.method == "GET":
# json_log_data = get_log_data()
# return HttpResponse(json.dumps(json_log_data),
# content_type='application/json')
return cc_helper_function_one(request... | 3c9381da3446b15da52b9297e2d1d413f3fa775e | 3,608,219 |
import time
def generate_hash():
"""
Function to generate the attendance token hash.
"""
token = hash(time.time()) % 100000000
return token | 2825549e551e574de5292be1f7b73bc4e180f748 | 3,608,220 |
import weasyprint as weasy # type: ignore
from typing import Optional
from pathlib import Path
def publish_pdf(
page: "Page", filepath: str = "./esparto-doc.pdf", return_html: bool = False
) -> Optional[str]:
"""Save page to PDF.
Args:
page (Layout): A Page object.
filepath (str): Filepath t... | 710b79d0b6d3a617c4192063c9b75c14b03b4644 | 3,608,221 |
def _validate_data_header(X: np.ndarray, y: np.ndarray, n_samples: int,
n_features: int, y_names: np.ndarray) -> bool:
"""
Checks if read-in data are consistent with their csv header.
For details on valid header formatting see the
:func:`fatf.utils.datasets.load_data` document... | 0a8ad0598094a00dc49ecffe9bd275f1e984bf31 | 3,608,222 |
def estimate_centroids(X, k, assoc):
"""
Recalculates centroids.
Inputs
------
X : `np.array`, shape (n, d)
Input data, where rows are examples and columns are features.
k : `int`
Number of k clusters to generate.
assoc : `np.array`, shape (n, )
Index of closest cent... | 30c7f193a814495a35aef4cae556ff7d18f5a8d4 | 3,608,223 |
def get_slackWH():
"""Return a valid SlackWebhook object."""
return SlackWebhook(auth='https://testurl.com', body='message',
attachments=['https://url1.com', 'https://url2.com']) | 2937ec5f4404136546f2f0299cf46071e2c499d8 | 3,608,224 |
from datetime import datetime
def _add_delay(team_id: str, time: str) -> str:
"""Update Modron reminder state
Args:
team_id (str): Name of the team to adjust
time (str): How long to snooze for
Returns:
(str) A reply to give to the user about the status
"""
# Parse the dura... | 076933103318be74bfafd08cac06fcc57d505153 | 3,608,225 |
def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2 ** np.arange(3, 6)):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size]) - 1 # [0,0,15,15]
rati... | 54754295eb0e6571cff25a626e08247d5ee02adb | 3,608,226 |
def mad(data):
""" Calculate the Median Absolute Deviation from the data.
:param data: The data to analyze.
:type data: list(number)
:return: The calculated MAD.
:rtype: float
"""
data_median = median(data)
return float(median([abs(data_median - x) for x in data])) | 565875f252563e4b8cd91c85d4090c1f07f14cb1 | 3,608,227 |
def run_gear_ratios_detections_on_cycle_data(ngears, cycle_df):
"""
Invoke this one if you want to draw the results.
:param pd.DataFrame cycle_df: it must contain (at least) `N` and `V` columns (units: [rpm] and [km/h] respectively)
:return: a list of all :class:`Detekt` tuples sorted with the most pro... | f4169fd37431d94df1533fdbdc96a697967004f9 | 3,608,228 |
import json
def get_user_params(job_id, job_data):
""" Gets User parameters from the input job id and data , sent from codepipeline
:param job_id: Job ID
:param job_data: Job data sent from codepipeline
:return: Parameters sent from codepipeline
:exception: Call put_job_failure to send failure to ... | 49c032ab8d3d3f026e9d2745f38220236235a5d6 | 3,608,229 |
async def async_setup_integration(
hass, wizlight=None, device=None, extended_white_range=None, bulb_type=None
):
"""Set up the integration with a mock device."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id=FAKE_MAC,
data={CONF_HOST: FAKE_IP},
)
entry.add_to_hass(hass)
... | d38550ea3257f2df0a91f84b6a441563c7127671 | 3,608,230 |
import torch
def topk_accuracy(output, target, topk = (1,)):
"""Compute accuracy over top "k" predictions."""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size()[0]
_, pred = output.topk(maxk, dim = 1, largest = True, sorted = True)
pred = pred.t()
correc... | 84f8b38cb7176f752cbd0b63baddc4d4914313ed | 3,608,231 |
def argmax_from_adj(vals, vertex_inds, adj_inds):
""" Indices of local maxima from `vals` given adjacent points
See ``reconstruction_performance`` for optimized versions of this
routine.
Parameters
----------
vals : (N,) array-like
values at all vertices referred to in either of `v... | 5a125c9a26e3280878894fd2076ecf8b6434832b | 3,608,232 |
import torch
def initialize_scrc_transform(is_training):
""" Initialize the scrc transformation.
Args:
is_train: whether is training or evaluation
"""
angles = [0, 90, 180, 270]
def random_rotation(x: torch.Tensor) -> torch.Tensor:
angle = angles[torch.randint(low=0, high=len(an... | 5565161aff24f832158eed7ea5bc7e5853bcc0b6 | 3,608,234 |
def getThreatStatus(cursor, cd_tax):
"""
Get the threat status of a taxon, with the associated references and links
Parameters
-----------
cursor: psycopg2 cursor
cursor of the current operations in the postgres database (need to be of psycopg2.extras.RealDictCursor type, in order to ob... | 0da9214393d9d9c143d09d4b8f6af1dc6fadd0ab | 3,608,235 |
import math
def tokens_del_row(corpus_id, token_id):
"""
:param corpus_id: Id of the corpus
:param token_id: Id of the token
:return:
"""
corpus = Corpus.query.get_or_404(corpus_id)
token = WordToken.query.filter_by(**{"corpus": corpus_id, "id": token_id}).first_or_404()
page = math.f... | ecffc6edf1327019bc7c95f9b2094bb728961638 | 3,608,236 |
def create_formula(rep, add_formula):
"""
Returns the temporal formula corresponding the given theory term.
Throws an error if rep it is not a valid formula.
Arguments:
rep -- Theory term to translate.
add_formula -- Callback to add resulting formuals.
"""
if rep.type == _cling... | 29d8bd40ed8201882cc48d548160fb5534f7b261 | 3,608,237 |
from pecan import conf
def stamp(uri):
"""
Used to stamp the URI of a static resource with a revision-specific
identifier so that when updates are deployed, browser caches are broken,
and users are forced to re-download the latest static resources.
"""
return "%s%s?%s" % (cdn_host(), uri, conf... | f8e5cc2a77b52f3826f9e686e186bb7eb48a4ed6 | 3,608,238 |
def computeFraction(feature_1, feature_2 ):
"""
Parameters:
Two numeric feature vectors for which we want to compute a ratio
between
Output:
Return fraction or ratio of feature_1 divided by feature_2
"""
fraction = 0.
if feature_1 ==... | fbce06ab1fea604a3c0e4f0e427dd6560acf80fe | 3,608,240 |
def get_connection():
"""
Get a connection to the database.
This method assumes that you have a tunnel to the database open. See
project readme for an explanation of how to open the tunnel.
Information for the connection read from our config system. This allows
to use the connection e.g. with ... | 73a36c072500177e34c5f62f579ec1eaf8258489 | 3,608,241 |
def isLNM(filename):
"""
Checks whether a file is ASCII Laser-Niederschlags-Monitor file (Thies).
"""
try:
fh = open(filename, 'rt')
temp = fh.readline()
except:
return False
try:
if not temp.startswith('# LNM '):
return False
except:
retu... | a94bc44910ed8924f7e0332ef28155634b2eb7ce | 3,608,242 |
def trivial_detokenize(s,lang='hi'):
"""
Trivial tokenizer for languages in the Indian sub-continent
"""
if lang=='ur':
raise IndicNlpException('No detokenizer available for Urdu')
else:
return trivial_detokenize_indic(s) | 95b3636112831c553869da3af20ab3db299c8cc4 | 3,608,243 |
import inspect
def cluster_stats(hdb, X, n, p=0.0):
"""Compute individual cluster statistics.
Parameters:
-----------
hdb : hdbscan.HDBSCAN object
Trained clustering model with labels.
X : array_like
Input data for clustering.
n : int
Cluster index (must be < len(hdb.l... | 863b422967e898641df9ab84b9726435cf5fbd8d | 3,608,244 |
def generate_all_chart_tables(overview_page):
"""Converts a OverviewPage proto to gviz DataTables."""
return [
generate_overview_page_analysis_table(overview_page.analysis),
input_pipeline_proto_to_gviz.generate_step_breakdown_table(
overview_page.input_analysis),
generate_run_environmen... | d6437882ea4b5bcf0b59e055698022f1665f7bca | 3,608,246 |
def fastfit_negbin(observed, tol=1e-4, max_iterations=100):
"""Fit Negatove Binomial.
Parameters
----------
observed: array_like
Observed values
tol: float
Tolerance criterion for stopping
iterations when difference between sucessive estimates
drops below t... | 8410ce43e50d9bf441165a6cb4f3eedda0a9b315 | 3,608,247 |
def _update(dOld, dNew, dType):
"""Function to update the 'prevState' in dOld with the 'prevState' in dNew
Unfortunately this is really similiar to '_rotate', but I didn't want to
jam a square peg in a round hole.
"""
c = 0
# Loop through dictionary
for _d in dOld:
# Loop throu... | 7be61238e7338c591b094dd9e4e346f9dc836f44 | 3,608,248 |
def set_default_labels(func):
"""
Helper decorator to set default labels to X and Y axes for matplotlib plots.
"""
@wraps(func)
def decorator(*args, **kwargs):
f = func(*args, **kwargs)
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
return f
return decorator | de70bd44b989909d05372f092642d2f9479254d3 | 3,608,249 |
def select_option(options, message='', val=None):
""" CLI selection given options. """
while val not in options:
val = input(message)
if val not in options:
logger.error('Invalid choice.')
return val | b17cfa5c4516ba444acd40d4e758307507f2ff83 | 3,608,250 |
def interpolate_np(grid, samples, world2grid):
"""Returns the trilinearly interpolated SDF values using the grid.
Args:
grid: numpy array with shape [depth, height, width].
samples: numpy array with shape [sample_count, 3].
world2grid: numpy array with shape [4,4]. Rigid body transform.
Returns:
... | 341cef96c6339df6bdd4e12c387a0b536168fd5e | 3,608,251 |
def write_column(f, data, selement, compression=None):
"""
Write a single column of data to an open Parquet file
Parameters
----------
f: open binary file
data: pandas Series or numpy (1d) array
selement: thrift SchemaElement
produced by ``find_type``
compression: str, dict, or ... | 462e38b39d4abb151fa7d2c8a1de100629d850f3 | 3,608,252 |
import time
def read_fit(filename):
"""Read Flexible and Interoperable Data Transfer file (FIT).
Parameters
----------
filename : str
Filename
Returns
-------
metadata : dict
Activity metadata
path : dict
Trackpoint data
"""
fitfile = FitFile(filename... | d3b766b7effd52cb4271b5d257b3e2a658aba3f0 | 3,608,253 |
def norm(vals, norm_min=None, norm_max=None, axis=(0,1)):
"""
For visualization purposes scale image with `(vals-norm_min)/(norm_max-norm_min),
with norm_min and norm_max either specified or within 0.01 and 0.99 quantiles of all values
"""
norm_min = ifnone(norm_min, np.quantile(vals, 0.01, axis=axi... | dbefaff2160e74246864b619cd7bdb2665774c18 | 3,608,254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.