content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def _ne(t1: 'Tensor', t2: 'Tensor', isnew: bool) -> 'Tensor':
"""
Also see
-------
:param t1:
:param t2:
:param isnew:
:return:
"""
data = t1.data != t2.data
requires_grad = t1.requires_grad or t2.requires_grad
depends_on: List[Dependency] = []
... | 73649c3e7d90024eff5ce2dcdc0ef1fb55c8d6ce | 3,596,152 |
def edit_distance(list1, list2):
# To compute the Levenshtein distance between two entries,
# say entries 92 and 94,
# try this in interactive mode after running this script:
# edit_distance(results_list[92].split(',')[1:], results_list[94].split(',')[1:])
"""Ref: https://bit.ly/2Pf4a6Z"""
#p... | 15b1d1e495bbbfa39c07043fe97735da0a495222 | 3,596,153 |
import math
def normStdevMask(img,mask):
"""
normalize an image with mean = 0 and stddev = 1.0 only inside a mask
"""
n1 = mask.sum()
if n1 == 0:
return img
sum1 = (img*mask).sum()
sumsq1 = (img*img*mask).sum()
avg1 = sum1/n1
std1 = math.sqrt((sumsq1 - sum1*sum1/n1)/(n1-1))
std2 = img.std()
retu... | b5493d1e8a0f6594badb97c9376777117263eb0b | 3,596,154 |
def embed_metadata(fp, meta):
# type: (str, iss.IsccMeta) -> Optional[str]
"""
Embed metadata into a copy of the media file and return path to updated file.
:param str fp: Filepath to source media file
:param IsccMeta meta: Metadata to embed into media file
:return: Filepath to the new media fi... | 7be82a0456fafdcfef6957185de0b1fc7842fd39 | 3,596,155 |
def return_title(video_ID):
"""
- Returns the title of the video with the corresponding video ID.
"""
if request.method == 'GET':
return db.get_video_title(video_ID) | 026fee2ace5ef6560323a6bd31861ec701f4f364 | 3,596,157 |
def evaluate_number(st):
"""
Returns evaluated number
Errors out if invalid
"""
m = get_number(st)
if m:
data = m.groupdict()
if data["float"]: return float(data["float"])
elif data["integer"]: return int(data["integer"])
return None
else:
error() | b797876ae298ba95cc4d88df17a61b70a5cd5847 | 3,596,159 |
def sg_add_ingress(pub_ip, sg):
"""Add ingress rule for SSH TCP/22 to the designated SG"""
response = EC2_CLIENT.authorize_security_group_ingress(
GroupId=sg,
IpProtocol='tcp',
FromPort=22,
ToPort=22,
CidrIp=pub_ip
)
return response | 0460cbaca715f87461ad85d960daeb478958fba4 | 3,596,160 |
def u_ang_mom_cons(lats, max_lat, rot_rate=ROT_RATE_EARTH, radius=RAD_EARTH):
"""Angular momentum conserving zonal wind."""
coslat = cosdeg(lats)
return rot_rate*radius*coslat*((cosdeg(max_lat) / coslat)**2 - 1) | 063c376a2ff61e5d006c960c92dddf833272e557 | 3,596,161 |
def getRandomArmors(numArmors):
"""Returns a random list of armor of numArmors size.
Armors will not overlap protected locations.
"""
armor = []
filter_base = {"random_count": 1}
for aIdx in range(0, numArmors):
filter = getArmorFilter(armor)
filter.update(filter_base)
r... | 1dd634c556f23c739bddd6d606150c3cb8865481 | 3,596,162 |
from django.contrib.auth.views import redirect_to_login
from django.core.xheaders import populate_xheaders
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login... | a20026d801e5a5b8f61e7e559dffbff5477435a7 | 3,596,163 |
from typing import Iterator
def equal_lines(expected: Iterator[str], actual: Iterator[str]) -> bool:
"""Compares each line of expected input against the actual input,
where the inputs may differ in their type (i.e., opposite);
returns true if and only if the sequences have the same number of elements
... | fd2debf0a142cdbb8c39ca8ade6f4fb9d28b59aa | 3,596,164 |
import pkg_resources
def get_gene_id_mapping_df():
"""
Get dataframe representing the id mapping for genes.
The function cache the results to prevent unnecessary calculations.
Returns:
pd.DataFrame: dataframe for id mapping.
"""
filepath = pkg_resources.resource_filename(
'ipc... | 519cd1973ca597b64dd7a47da0660239ed43728a | 3,596,165 |
from typing import Optional
from typing import List
from typing import Dict
from typing import Any
def get_state_change_with_balance_proof_by_locksroot(
storage: SerializedSQLiteStorage,
canonical_identifier: CanonicalIdentifier,
locksroot: Locksroot,
sender: Address,
) -> Optional[StateChangeRecord]:... | ba54b4fa5ce80564f9c811faa9ff16b66bc856bf | 3,596,166 |
def smtp_recipient_remove(handle, email):
"""
Clears the smtp recipient with given email address
Args:
handle (ImcHandle)
email (int): SMTP recipient email address
Returns:
MailRecipient object
Raises:
ImcOperationError
Example:
smtp_recipient_remove(h... | ddc812eeb3feff972abc548cbbffec72ef009da2 | 3,596,167 |
from typing import Any
def knob(name:str, value:Any=None, getType:int=None, getClass:str=None):
"""
knob(name, value, getType, getClass) -> None
@brief Returns or sets the entire state of a knob.
Each individual control on a control panel is called a 'knob'. A
knob's name is a dot-separated list... | 0606807824089b54d960074bf6776ee6378d146d | 3,596,169 |
def generate_checker(value):
"""Generate state checker for given value."""
@property
@wraps(can_be_)
def checker(self):
return self.can_be_(value)
return checker | 210dabf00bc35f8fd178faa4a961a918ccec06c3 | 3,596,170 |
def read_piis(piis):
"""Return texts extracted from articles with given PIIs.
Parameters
----------
piis : list[str]
A list of PIIs to extract texts from.
Returns
-------
texts : dict
A dictionary representing PIIs as keys and extracted texts as values.
"""
texts = ... | ba5dae0dd3d917cf6f2604ed250c9a1bdb80f75b | 3,596,171 |
from apysc._html import html_util
from apysc._jslib import jslib_util
from typing import List
def _append_head_to_html_str(
*, html_str: str, js_lib_dir_path: str,
embed_js_libs: bool) -> str:
"""
Append head tag section to specified html string.
Parameters
----------
html_str : s... | 9317ddcd6c9979a63d57243d0f4db27f1d351840 | 3,596,172 |
def l2(a, b):
"""L2 norm"""
return np.sqrt((abs(a - b) ** 2).sum() / (abs(a) ** 2).sum()) | 47f7d6eb3152547301227809b23cfa594571fa27 | 3,596,173 |
from typing import Dict
import json
def get_player_clubs(username: str) -> Dict:
"""Public method that returns list of clubs the player
is a member of.
Parameters:
username -- username of the player
"""
r = _internal.do_get_request(f"/player/{username}/clubs")
return json.loads(r.data... | 6c17035b710cccc76da8f813dfce35f13eeb8e17 | 3,596,174 |
from typing import Dict
from datetime import datetime
def inject_now() -> Dict:
"""Inject current datetime into request context."""
return dict(request_datetime=datetime.now()) | e186d4b478a5da5bcdf83e2e34cd381de8d039be | 3,596,176 |
def pretty_picks_info(picks):
"""Formats a detailed overview of the current live scores for a team in a Gameweek"""
fields = ["Gameweek score", "Automatic subs", "Active chip", "Average Gameweek score",
"Highest Gameweek score", "Game updated", "Gameweek finished"]
table = PrettyTable(field_na... | 49cade515b459395354177e25b1342cb62df6f2d | 3,596,177 |
def _make_eof_producer(producer):
"""
Send a special EOF byte sequence to terminate the request.
Args:
producer (Callable[[str, socket.socket], None]):
Request producer.
Returns:
Callable[[str, socket.socket], None]:
Request producer that sends 'END-OF-FILE' at ... | 9c035b1f790cab96c9cffc91e6dcf8a13017a4cc | 3,596,181 |
def process_structure():
"""
Process a structure (uploaded from POST request)
"""
if flask.request.method == "POST":
# check if the post request has the file part
if "structurefile" not in flask.request.files:
return flask.redirect(flask.url_for("input_data"))
structu... | 9d30ec56a713abd142a693fd30939745ce6aaf7d | 3,596,183 |
import math
def rotation_matrix_to_euler_angles(R):
""" calculates rotation matrix to euler angles
referred from https://www.learnopencv.com/rotation-matrix-to-euler-angles
"""
assert(is_rotation_matrix(R))
sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0])
singular = sy < 1e-6
if ... | dbfa5c0ec4f788de5e241b1a56d63aef4df2fd69 | 3,596,184 |
def get_instructor_schedule_by_term(request, term=None, summer_term=None):
"""
:return: the instructor's class schedule (uw_sws.models.ClassSchedule) of
the given quarter/term and corresponding summer term.
:param Term term: None uses current term related to the given request
:param str summer_term:... | 0db5a0c22a6e2cbd281465c1a40073f2edf38b73 | 3,596,185 |
import time
import functools
import asyncio
def duration(func):
""" decorator that can take either coroutine or normal function
I cannot get this to work w/ FastAPI async methods
"""
@contextmanager
def wrapping_logic():
start_ts = time.time()
yield
dur = time.time() - sta... | a7bfb9be9b0d3e574c877119dccafe68e791ba30 | 3,596,186 |
def in_key_rd_dicts( key_rd_dict, key_rd_dicts ):
"""Return True if key_rd_dict is contained in the list of key_rd_dicts."""
k = key_rd_dict.keys()[ 0 ]
v = key_rd_dict[ k ]
for key_rd_dict in key_rd_dicts:
for key, val in key_rd_dict.items():
if key == k and val == v:
... | 04c691a1a78834c7d660ae3036e97ea0e78393de | 3,596,187 |
def compute_audio_features_with_phonemes(audio,
n_fft=2048,
sample_rate=16000,
frame_rate=250):
"""Compute features from audio."""
audio_feats = {'audio': audio}
audio = squeeze(audio)
audio_feats['loudness_db'] = ddsp.spectral_op... | 96dc8cfd7df6b0db22908660bbbd7d8047d2b837 | 3,596,188 |
from typing import Tuple
from typing import Union
from typing import Optional
from typing import Callable
from typing import Any
import warnings
import ctypes
def alloc_array(shape: Tuple[int, ...],
dtype: Union[str, np.dtype],
layout: Tuple[int, ...],
alignment: int = ... | d0b1e09f4adfb021ff9abc2bf5524247e000d2b8 | 3,596,189 |
def sequence_predicting(model, tokenizer, text, labels):
""" Sequence-prediction for tasks like text classification, ... """
text = cleanize(text)
inputs = tokenizer.encode(text, return_tensors="tf", max_length=128)
logits = model(inputs)[0]
outputs = tf.keras.backend.softmax(logits)
prediction... | 93d87191703a40ec286206802eb92728d99e9bbe | 3,596,190 |
import requests
def archive_whatsapp_conversation(org, wa_id, message_id, reason):
"""
Archives the whatsapp conversation
Args:
org (Organization): The organisation that this request belongs to
wa_id (str): The ID of the user to archive the conversation for
message_id (str): the I... | 2db4566320b1bb292de4dee347e7f658a256ccf0 | 3,596,191 |
def get_bprop_correction_mul(self):
"""Generate bprop for CorrectionMul for Ascend and GPU"""
grad_dx = Q.CorrectionMulGrad(self.channel_axis)
grad_d_batch_std = Q.CorrectionMulGradReduce(self.channel_axis)
def bprop(x, batch_std, running_std, out, dout):
dx, d_batch_std = grad_dx(dout, x, batc... | dfbe0f5ed289e711e09eb3da8d3c536e4ded5044 | 3,596,192 |
from typing import List
def get_rules() -> List[BaseRule]:
"""Get plugin rules."""
return [Rule_Comments_L001] | 1caea024d2baefa2581f815d58cb84778f229c2f | 3,596,193 |
def delete_file(collection_name: str, file_name: str):
"""
Delete a file given its collection and file name.
:param collection_name: The name of the collection containing the file.
:param file_name: The name of the file to be deleted.
"""
try:
fs.collection_manager(collection_name).delet... | 13abf963080163732652fe819a21140e341bd56f | 3,596,194 |
def ZIPConstraint(Params):
"""Constraint for ZIP modeling. Ensure "fractions" add up to one.
a1, b1 = Z%cos(thetaZ), Z%sin(thetaZ)
a2, b2 = I%cos(thetaI), I%sin(thetaI)
a3, b3 = P%cos(thetaP), P%sin(thetaP)
"""
# Extract parameters from tuple.
# a1, a2, a3, b1, b2, b3 = Params
# De... | dd7db6d4b5c9a7aec90c22d75db06ae3d3853c81 | 3,596,195 |
from datetime import datetime
def otp_open(request):
"""开启两步认证"""
user = request.user
user_otp = models.UserOTP.get_user_otp(user)
if user_otp.is_bind:
raise exceptions.PermissionDenied
context = dict(request=request)
serializer = serializers.UserOTPChangeSerializer(
data=re... | 3aa191ef895d87f31a8c8f55afc32a022d7a30ae | 3,596,196 |
def getFoodDistList(data):
"""
getFoodDistList returns None (no food) or a list of tuples ((x, y), dist)
where (x,y) are the coords of the food, and dist is distance
"""
head = getHead(data)
listFood = listDictToTuple(data['board']['food'])
if not listFood:
return None
tree =... | 99086146144fedf33238311c3969d77bc47fb512 | 3,596,197 |
import types
async def _resolve_entities(message: str, entities: list) -> dict:
"""Don't even bother trying to figure this mess out"""
messages = []
while entities:
end = 100 if len(entities) >= 100 else len(entities)
if len(message) > MAXLIM:
end, _ = min(enumerate(entities[:e... | 78d2da616cb19deced82fa379498ef5b6b834fdd | 3,596,198 |
def medical_covered_by_1(responses, derived):
""" Return whether the children are covered under Claimant 1's plan """
if responses.get('medical_coverage_available', 'NO') == 'YES':
return 'My plan' in responses.get('whose_plan_is_coverage_under', '')
return False | a5116dbe07fa97e95a349acfe926b228a6829488 | 3,596,199 |
import re
def split_text(text, pattern=r";|。|;|,|,"):
"""split text by pattern
Args:
text (str): text
pattern (regexp, optional): expression. Defaults to r";|。|;|,|,".
Returns:
str: text split by pattern
Examples:
>>> s = String()
>>> text = "收快递的时候最怕收不到货,所以购... | 080b63c947f5b9aca749e2ec4981f64c09e2ad43 | 3,596,200 |
def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1] | 7d83eb861141f6beb0885439738cc788f36aab1d | 3,596,201 |
def mixedomatic(cls):
""" Mixed-in class decorator. """
classinit = cls.__dict__.get('__init__') # Possibly None.
# Define an __init__ function for the class.
def __init__(self, *args, **kwargs):
# Call the __init__ functions of all the bases.
for base in cls.__bases__:
bas... | 3891a748a5cd6ee5e31c1441a7645343c0862135 | 3,596,202 |
def _make_xml_object(root_name, **attributes):
"""
Create a new xml root object with a given root name, and attributes
Parameters
----------
root_name - str
The name of the xml root.
attributes - dict
Dictionary of attributes and values (as strings) for the xml file
Returns... | 58212ffc5f6953730d6d1b2e61f9c38631076eb1 | 3,596,203 |
def verifier_update(verifier_id, **properties):
"""Update a verifier record.
:param verifier_id: verifier name or UUID
:param properties: a dict with new properties to update verifier record
:raises ResourceNotFound: if verifier does not exist
:returns: the updated dict with verifier data
"""
... | afa8c42c4f3c93632aa92ee8f42990ddc608e9d4 | 3,596,204 |
def user_is_full_member(self):
""" user is full member of CommonSpaces if has a complete profile
and is member of a Community (Project membership is not enough """
if self.is_superuser:
return True
profile = self.get_profile()
if not profile:
return False
if not profile.get_compl... | 1edf3debd1bb08f1ea88ad58722630a11a3af762 | 3,596,205 |
def expanded_indexer(key, ndim):
"""Given a key for indexing an ndarray, return an equivalent key which is a
tuple with length equal to the number of dimensions.
The expansion is done by replacing all `Ellipsis` items with the right
number of full slices and then padding the key with full slices so tha... | 4e6914db0a5468bd51ca9bf89e83defe82f161c7 | 3,596,206 |
def sphere_sre(solution):
"""
Variant of the sphere function. Dimensions except the first 10 ones have limited impact on the function value.
"""
a = 0
bias = 0.2
x = solution.get_x()
x1 = x[:10]
x2 = x[10:]
value1 = sum([(i-bias)*(i-bias) for i in x1])
value2 = 1/len(x) * sum([(i... | 38987c77a6586a0bfab1d94cc4a1511e9418349f | 3,596,207 |
from typing import Union
import pytz
from datetime import datetime
def localnow(tz: Union[pytz.BaseTzInfo, str] = "US/Central") -> datetime:
""" Get the current datetime as a localized datetime object with timezone information
Keyword Arguments:
tz {Union[pytz.timezone, str]} -- localize datetime to ... | 3dd9132c4adebacf5d348ec34523584642f7140b | 3,596,208 |
def mapped(headers):
"""S3到COS参数的一个映射"""
_headers = dict()
for i in headers:
if i in maplist:
if i == 'Metadata':
for meta in headers[i]:
_headers[meta] = headers[i][meta]
else:
_headers[maplist[i]] = headers[i]
else... | 7c068c3b651e4e9c9128f9a1a26eeff565d302f0 | 3,596,209 |
def get_increment(msg_list):
"""
:param msg_list: list of on/off midi signals
:return: minimum time of all signals
"""
result = float('inf')
for msg in msg_list:
if msg.time != 0.0 and msg.time < result:
result = msg.time
return result | 5b41d4a26b91c6c98d191867f0a968b1a389ba2b | 3,596,211 |
import timeit
def tic():
""" Default timer
Example: t = tic()
... code
elapsed = toc(t)
print( '{0}: {1:.4f}ms'.format(message, elapsed) )
"""
global lastticstamp
t = timeit.default_timer()
lastticstamp = t
return t | 7b68cde350e931d9e8f479151ed3c142298a6366 | 3,596,212 |
def env(key=None):
"""function for accessing the globally shared and mutable 'env' dictionary.
When called without a `key` it returns the whole dictionary."""
_env = api(fab_api.env, threadbare.state.ENV)
return _env[key] if key is not None else _env | 9c2b19cd8d9b12c07f0067f5b7e698af2ebae533 | 3,596,213 |
def add_node_index(node: StrDict, n: int = 0) -> int:
""" Add an index to the node and all its children """
node["index"] = n
for child in node.get("children", []):
n += 1
n = add_node_index(child, n)
return n | 25d129ded8df01cfec749ca534b7a7ba394d8036 | 3,596,214 |
from typing import List
import torch
from typing import Tuple
def collate_fn(batch: List[torch.Tensor]) -> Tuple[Tuple[torch.Tensor]]:
"""[summary]
Args:
batch (List[torch.Tensor]): [description]
Returns:
Tuple[Tuple[torch.Tensor]]: [description]
"""
return tuple(zip(*batch)) | 798d12485f5e1b258b2bd3fe7137bfe1fe352a1b | 3,596,215 |
def ts_gsmooth_line(ax,df,obsvar,modvar,start_date,end_date,L=50,region='',station='',sepvar='',sepvals=([]),lname='',sepunits='', ocols=('blue','darkviolet','teal','green','deepskyblue'),
mcols=('fuchsia','firebrick','orange','darkgoldenrod','maroon'),labels=''):
""" Plots the daily avera... | 8f325876119535d0c4fd9d01f416406829ce5330 | 3,596,216 |
from datetime import datetime
def get_current_timestamp():
"""
Get current datetime as formatted string
@return:
"""
now = datetime.now()
return now.strftime("%d-%m-%Y %H:%M:%S") | ca8aeb46c867b65358c7e707da3d5a24df7e4d66 | 3,596,218 |
def add(x, y):
"""Add Function"""
return x + y | 15a9f22d804cf3347f6d44463ed493dbd3efd049 | 3,596,219 |
def getServices():
"""Return a list of service names from cuebot."""
return [service.name() for service in opencue.api.getDefaultServices()] | 01c8fad056ec10da6e12fe67db6d4dd258c076ce | 3,596,220 |
def _build_biosample_embedded_list():
""" Helper function intended to be used to create the embedded list for biosample.
All types should implement a function like this going forward.
"""
modification_embeds = DependencyEmbedder.embed_defaults_for_type(base_path='modifications',
... | 2e44903f8e3d1d58f0a3eb6856551428b166543b | 3,596,221 |
def permute_optimize_keys(fixed_letters, fixed_letter_indices, open_letter_indices,
all_letters, keys, data_matrix, bigrams, bigram_frequencies,
min_score=0, verbose=False):
"""
Find all permutations of letters, optimize layout, and generate output.
"""
... | ac400a41e0fa918aac99a7ac6f595e4c8e42e900 | 3,596,223 |
def _get_upsampling_layer(upsampling_factor):
"""Creates layer for 2-D upsampling.
:param upsampling_factor: Upsampling factor (integer >= 1).
:return: layer_object: Instance of `keras.layers.Upsampling2D`.
"""
try:
return keras.layers.UpSampling2D(
size=(upsampling_factor, ups... | a09e2c8fefaa25c01a197c3daf7cb10c63e54015 | 3,596,224 |
def vizMatches(params1,angles1,params2,angles2,row_ind,col_ind,device):
""" Method used to visualize matches from the assignment algorithm"""
def vizWavelet(wavelet,mode):
if mode =='fourier':
x = np.fft.fftshift(wavelet.squeeze().cpu().detach().numpy()).real
elif mode == 'real':
... | a12eace1ad44aec1c5abe8326e584f6c5798b983 | 3,596,225 |
def save_k8s_local_template_definition_as_metadata(
client, catalog_name, catalog_item_name, template_definition,
org_resource=None, org_name=None):
"""Save definitions of a templates in a catalog as metadata on the item.
:param pyvcloud.vcd.Client client: A sys admin client to be used to
... | 89f573107fa91c51f520258e32c9cfb92ad275b6 | 3,596,226 |
import aiohttp
async def get_board_dates(
session: aiohttp.ClientSession,
board: str = DEFAULT_BOARD,
market: str = DEFAULT_MARKET,
engine: str = DEFAULT_ENGINE,
) -> client.Table:
"""Получить интервал дат, доступных в истории для рынка по заданному режиму торгов.
Описание запроса - https://i... | dff4e53a27761db4c49df5c688f00afc28dcd0a0 | 3,596,227 |
def main():
"""First function to be called"""
# Clear the screen by using module function.
clear_screen_module.clear_screen()
# Print purpose of the script.
print("This script will print * multiple times in single line.\n")
print("The pattern is as below,\n")
# Need to take upper limit as 6 ... | 74f80c423d53b85e9e021a7daab171ab851c874f | 3,596,228 |
def matrix_to_nt(seq_matrix):
"""converts back a matrix of integers into a list of nucleotide
sequences."""
seq_list = []
for line in seq_matrix:
seq_list.append("".join([num_to_nt[x] for x in line]))
return seq_list | e9999af5b18e2718fdd3d750804ea0eef4bdef97 | 3,596,229 |
def rs_direct_interpolation_pass2(*args):
"""
rs_direct_interpolation_pass2(int n_nodes, int Ap, int Aj, float Ax, int Sp, int Sj,
float Sx, int splitting, int Bp, int Bj,
float Bx)
rs_direct_interpolation_pass2(int n_nodes, int Ap, int Aj, double Ax, int Sp, int Sj,
double Sx, int ... | c23366290c7ba724729af4d0acaaf3e168ef8be6 | 3,596,230 |
def does_resource_exist(resource):
"""Use boto3 to check if a resource exists."""
try:
resource.load()
return True
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'ValidationError':
return False
else:
raise e | 9bc884ae9b7de5aa69a3d519148dcbc89cc4d1d3 | 3,596,231 |
def get_fee_interactive(source_address, keys, destinations, redeem_script, input_txs):
"""
Returns a recommended transaction fee, given market fee data provided by the user interactively
Because fees tend to be a function of transaction size, we build the transaction in order to
recomend a fee.
retu... | 658f44761c80f5cfdb4a9405438447dcb256fa15 | 3,596,232 |
def get_AUC_list(df_list, set):
"""
"""
auc_list = []
for df in df_list:
set_list = df.set.values
scores = df.ad_score.values[set_list == set]
labels = df.abnormal_XR.values[set_list == set]
body_part = df.body_part.values[set_list == set]
auc_list_tmp = [roc_auc... | b29e0f8a7622862bce4ec4e28385689d0764e7b7 | 3,596,233 |
import torch
def threshold_mask(weights, threshold):
"""Create a threshold mask for the provided parameter tensor using
magnitude thresholding.
Arguments:
weights: a parameter tensor which should be pruned.
threshold: the pruning threshold.
Returns:
prune_mask: The pruning mas... | 43ca3f018f047e2ac46a83c36c368798b69e104a | 3,596,234 |
from typing import Union
def get_object_from_hit(hit: Hit) -> Union[Chapter, Heading, SubHeading, Commodity]:
"""Returns the commodity object related to a hit."""
alias = get_alias_from_hit(hit)
model_class = INDEX_TO_MODEL_CLASS_MAP[alias]
try:
model = model_class.objects.get(
go... | 29f4c3407aa3143a6e54f55bd95d3a8ad234f115 | 3,596,235 |
from typing import Tuple
def indices(local_shape: Tuple):
""" Returns arrays of shape local_shape storing the respctive column
and row indices of each local matrix element within the mathematical
matrix.
Args:
local_shape: Shape of the matrix block on each processor.
Returns:
rows, cols: The mathema... | fa31e8a5eb57d87a62a589f45b1bdfec8bf04400 | 3,596,236 |
def sigmoid(attrs, in_xlayers):
""" Return sigmoid registration information (shape) """
assert len(in_xlayers) == 1
shape = in_xlayers[0].shapes[:]
return {'shape': shape} | 5637c532ed9eda6ec14abac0cf5e360a47c7333b | 3,596,237 |
def getFlags(*args):
"""getFlags(ea_t ea) -> flags_t"""
return _idaapi.getFlags(*args) | b40efc24b10f4b9e5c6ae26d3252a3c84957b94a | 3,596,238 |
def batch_rodrigues(theta):
"""computes rotation matrix for given angle (x, y, z)
see equation 2 of SPML (http://files.is.tue.mpg.de/black/papers/SMPL2015.pdf)
for more information about this implementation see
(https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angl... | 00d7cc14801979ea011ee2f86a750bcb84378d93 | 3,596,239 |
def cuboid() -> PointGroup:
"""Symmetry group of a cuboid with edges aligned with the Cartesian axes."""
return Dh(2) | 1c0a8ef602d2bb05e0b16562d23bbebd77699b3b | 3,596,240 |
def search(request, query):
""" search for a reference """
if request.method == "POST":
query = request.POST.get('q')
return redirect('/references/search/' + str(query))
refs = References.objects.filter(title__icontains=query).values_list('id', 'title').order_by('title')
return render(r... | 9e7b71520cf765542fd9910caed349c2b3040e70 | 3,596,242 |
def classify(dataset,classifier,feat_mask=None):
"""
Performs a standard classification test with the given classifier.
Parameters
----------
dataset : TextDataset
TextDataset with train/val/test splits.
classifier : object
Classifier must have fit(X,y) & predict(X) methods.
... | 6f5ee88c68b25e6c4d606c43891eef3f16e46f38 | 3,596,243 |
async def async_unload_entry(hass: HomeAssistantType, config_entry: config_entries.ConfigEntry) -> bool:
"""Unload Mosenergosbyt entry"""
log_prefix = _make_log_prefix(config_entry, 'setup')
entry_id = config_entry.entry_id
unload_ok = await hass.config_entries.async_forward_entry_unload(
confi... | 2430b52618f9e625d8ae70ac8daac94b8d011bb4 | 3,596,244 |
import torch
def roc_auc_score(y_pred, y_true):
"""
Computes the area under the ROC curve.
Parameters
----------
y_pred: torch.FloatTensor [N]
The (binary) predictions made by the model.
y_true: torch.LongTensor [N]
The actual classes.
Returns
-------
torch.FloatT... | 0af0d37ef243a553a4a7b4c3d13419c683f07aaa | 3,596,245 |
from uroborosqlfmt.sql import MergeUpdateInsertClause
def is_mergeupdateinsertclause(token):
"""
MERGEの内のDML判定
"""
return isinstance(token, MergeUpdateInsertClause) | dcc16887baed82566f99c5eaf745bd6809c9a8cf | 3,596,246 |
import tqdm
def filterCellBCs(moleculetable, outputdir, umiCountThresh = 10, verbose=True):
"""
Filter out cell barcodes thmt have too few UMIs
:param moleculetable: allele table
:param outputdir: file pmth to output directory
:return: filtered allele table, cellBC to number umis mapping
"""
... | ab27dd5492e16d6fdedf72b33dfb4faf9924b033 | 3,596,248 |
def sampled_places(block_size, length):
"""returns randomly sampled positions with block_size to make a new vector
with length
"""
# Main condition is to identify when a draw would run off end, we want to
# draw from beginning
num_seg, remainder = divmod(length, block_size)
vector = range(le... | f425291ee8bbe01bf1a41357a7b726582d91af88 | 3,596,249 |
def is_too_large(usr_file: str) -> bool:
"""
Return True is the file is higher than the max allowed,
False otherwise.
:param usr_file: (str) path of user file
:return: (bool)
"""
if usr_file.file_size >= MAX_FILESIZE_DOWNLOAD:
return True
else:
return False | 1f069a18fe2616c9913a35ef7d912f30475d200e | 3,596,250 |
from typing import Union
def gamerule(self: Client, rule: str, value: Union[bool, int] = None) -> str:
"""Sets or queries a game rule value."""
return self.run('gamerule', rule, value) | 6dc7741e70e493f66f3561935adf7c30ed742f9d | 3,596,253 |
def get_answer(file_answer):
"""
"""
with open(file_answer, 'r') as f:
return [x.split(';')[0].rstrip() for x in f.readlines()] | 0acfa654a328a5d4ac3a7c5cd291577be52b707b | 3,596,254 |
def feature_selection_chi2(vectorizer, X_train, y_train, X_test, k=5000):
"""feature selection based on chi2
"""
feature_names = vectorizer.get_feature_names()
# Feature reduction with Kbest features based on chi2 score
ch2 = SelectKBest(chi2, k=k)
X_train = ch2.fit_transform(X_train, y_train)
... | 718682d048ba29559b256b96b60c8fc3ec32b556 | 3,596,255 |
def effectivepotential_plus(S, J, r, q, chi1, chi2):
"""
Upper effective potential.
Call
----
chieff = effectivepotential_plus(S,J,r,q,chi1,chi2)
Parameters
----------
S: float
Magnitude of the total spin.
J: float
Magnitude of the total angular momentum.
r: flo... | 79133fb4c2f8682a027ffcb726ceab06d7f00a04 | 3,596,256 |
def atom_to_move(o, p):
"""
Return the coordinates xyz of an atom just above acceptor/donor atom o
"""
# It will not work if there is just one dimension
p = np.atleast_2d(p)
return o + normalize(-1. * vector(o, np.mean(p, axis=0))) | 49e3f7593dc76f38b68b825d52a5476992833ce0 | 3,596,257 |
def string_is_yes(string, default=None):
"""
Mapping of a given string to a boolean.
If it is empty or None (evaluates to False), and `default` is set, `default` is returned.
If the lowercase of the string is any of ['y', '1', 'yes', 'true', 'ja'], it will return `True`.
Else it will return `False`... | 68482f78f8d4464891f14c19953e1a4785fe0811 | 3,596,258 |
def bi_count_helper(df, i, j):
"""
tools for multy thread bi_count
"""
df['bicount_{}_{}'.format(i,j)] = df.groupby([i,j])[i].transform('count')
return df[['bicount_{}_{}'.format(i,j)]].fillna(-99999).astype(np.int32) | 55c430fce4b4c75a43526b6db8d488937fc0e4ec | 3,596,259 |
from typing import Counter
def ld0230(coord: np.ndarray, weights: np.ndarray, count: Counter):
"""Get 230 point angular Lebedev-Laikov grid."""
v = -0.5522639919727325e-1
genOh1(count, coord, weights, v)
v = 0.4450274607445226e-2
genOh3(count, coord, weights, v)
a = 0.4492044687397611e0
v... | 0987f1b658aeb098555f87d75c437c4bcc4f4488 | 3,596,261 |
import json
def get_target_assays(identifier, identifier_type, attempts=10):
""" Get assay ids and name for a given target
Parameters
----------
identifier : str
Identifier of the target. Can be GI, Gene ID, or gene symbol.
identifer_type : {"genesymbol", "geneid", "g... | 7bac829a3c8e970e00352a39bc88c1c36f7369ba | 3,596,262 |
def new_show_result_21(img, result, class_names, score_thr=0.3, mask_index = 5):
"""Visualize the detection results on the image.
Args:
img (str or np.ndarray): Image filename or loaded image.
result (tuple[list] or list): The detection result, can be either
(bbox, segm) or just bbo... | 4b66e7ffd1bdd5b2aee07875eae45b4f4731905e | 3,596,264 |
def default_cards_encoding() -> Feature:
"""
Default encoder for the card-level features.
Encodes a `Player`.
"""
return CombinedFeature([
ListOfFeatures(
lambda player: [LocatedCard(card, CardLocation.STORE) for card in player.store],
default_card_encoding(), MAX_EN... | 03f086c07c055d49fc9e3f8505dc8fa01a23de8c | 3,596,265 |
def look_and_say(string):
"""
Expand a string of digits according to look-and-say process in the problem.
Keyword arguments:
string --- a string to be processed
"""
result = ""
last = ""
count = 0
for digit in string:
if digit != last:
if(count):
result += str(count) + last
l... | cd8fcce76302cdb1c9af10d9481559c1eb098e43 | 3,596,267 |
def patchDefaultDelim(st:str):
"""
:param s:
- if not None, returns self
- else returns the default delimiter in :attr:`~k1lib.settings`"""
return settings.defaultDelim if st is None else st | 41152cbf3daf092836bbf76abdac3518b3c6462b | 3,596,269 |
def check_random_transform_ops(method):
"""Wrapper method to check the parameters of RandomChoice, RandomApply and Compose."""
@wraps(method)
def new_method(self, *args, **kwargs):
arg_list, _ = parse_user_args(method, *args, **kwargs)
type_check(arg_list[0], (list,), "op_list")
if ... | 9094ad033a4a48392a7ae969c6e5d56c4ff00417 | 3,596,270 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.