content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_days_with_error(percent_error_threshold=PERCENT_THRESHOLD):
"""Returns the day, totalViews and errorViews grouped by day according
to the log"""
db = psycopg2.connect(dbname=DBNAME)
c = db.cursor()
c.execute("select * from errors_per_day " +
"where percentage > %s " +
... | 53b67686e5cdbc4f0a2ad4aea85dab147d98185a | 78,197 |
import logging
def hook_messagebox(emu, api_name, func, params):
"""
API hook that is installed to intercept MessageBox calls as an example
Args:
api_name: The full name including module of the hooked API
func: the real emulated function provided by the framework
Users can ca... | b4dc35a42ec526dbe290c82f121ded9ab34e49d1 | 78,199 |
import ast
def transform(root, visitor):
"""
Largely taken from the ast source. Works a bit differently because
it depends on the graph_walk which returns items leaf first and then to
root.
Note that if we come across an unknown node (_missing), we assume that
the fields were mutated in the n... | e1b42214aaca3aa5b51af8feac3b9f1fbf5e4e61 | 78,200 |
from typing import Optional
from datetime import datetime
from typing import List
from typing import Any
def get_daterange(
start_date: Optional[datetime.datetime], end_date: Optional[datetime.datetime], frequency: str
) -> List[Any]:
"""
Returns list of a fixed frequency Datetime objects between given bo... | 75095754cb1a715c9ea9494c193e1bbe00766a4d | 78,201 |
def is_bgp_neighbors_established(
device, neighbors, address_family, max_time=15, check_interval=5
):
""" Helper function for is_bgp_neighbors_state.
Verifies BGP neighbor is established
Args:
device('obj'): device to use
neighbors('list'): neighbors to verify are establ... | 81210dfb57ed96ea9d1e9ba0c7b6bc921f4a4ca9 | 78,202 |
def roll(*args, **kwargs):
"""
Calculates a given statistic across a rolling time period.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns (optiona... | dd484deb8c3f842da1f94210e8ff19344233ff3e | 78,203 |
from typing import Union
def get_symmetry_hash(
structure: Union[IStructure, SymmetrizedStructure], tight: bool = False
) -> str:
"""Hashes the symmetrical positions of the SymmetrizedStructure.
The tight setting also considers the ordering,
otherwise only the number and identity
of the elements i... | e40b15029827bc5c9d57d09dd068807db7418164 | 78,204 |
from typing import Union
from typing import List
import requests
def get_pokemon_in_region(region: Union[int, str]) -> List[dict]:
"""
Gets all pokemon in a provided region.
:returns: a list of all pokemon species. Refer to https://pokeapi.co/docs/v2#pokemonspecies
:raises: ValueError if the request ... | b4a631126bec21f70b3e74d376fa5d92bfb04b64 | 78,205 |
import configparser
def prep_dispatcher_supervisord_conf():
"""
Prepares the supervisord configuration for dispatcher.
:returns: supervisord configuration as a ConfigParser object
:rtype: ConfigParser
"""
config = configparser.ConfigParser()
env = 'PYTHONPATH=python:.,ZLOG_CFG="gen/dispatc... | 3385a6d6d18afeb1ce57386b4f9ad87da8abb9df | 78,206 |
def new_adata(adata, x, s, u, v=None,
new_v_key="new_velocity",
X_emb_key="X_umap",
g_basis="SU",
):
"""Copy a new Anndata object while keeping some original information.
Args:
adata (Anndata): Anndata object
x (np.ndarray): new trans... | 443a70a7ada4ceeefca45672286f6ebe3eb2e448 | 78,208 |
def dict_unnest(obj):
"""Flatten a dictionary containing other dictionaries by concatenating their keys.
Parameters
----------
obj : dict
A dictionary, which may or may not contain other dictionaries
Returns
-------
dict
A new dictionary, which has been reformatted
"""... | 5c2080dbdd229ba98d154b9efec1a946418e19e1 | 78,209 |
def build_app(mode):
""" Builds a new app instance with specified configuration
:param mode: Mode to use (choose one of ['dev', 'test', 'prod'])
:type mode: str
"""
app = Flask(__name__)
# add the configuration parameters to app instance
app.config.from_object(config[mode])
# add ro... | 041aa7a0391d82a939d022f6fd521a4fc8b67c7a | 78,211 |
def target_tensor(len, labels, scores):
""" create the target by labels and scores """
target = [0]*len
for id, l in enumerate(labels):
target[l] = scores[id]
return target | 982df10a69d0071a9a7ba06366b7f9cd13402bae | 78,212 |
import json
def create_deployment():
""" Create deployment. Returns newly created deployment dictionary or error.
"""
try:
if not request.data:
message = 'No data provided to create a deployment.'
raise Exception(message)
data = json.loads(request.data)
depl... | 40d3a7d27e48eccc70e07648928068c6acbc31b5 | 78,213 |
import logging
import pickle
def load_features_nogt(feat_file_table, max_len=10000,
pickle_only=False,
force_overwrite=False,
n_procs=1):
"""
Loads features for real datasets. Filters contigs with low coverage.
WARNING: `coverage` colum... | 378416c89b1cf01a4902eb32f42194be8a7dffe2 | 78,217 |
def get_X_Y(lockin):
"""
Get X and Y (Measure)
args:
lockin (pyvisa.resources.gpib.GPIBInstrument): SRS830
returns:
(tuple): X, Y
"""
X, Y = lockin.query("SNAP? 1,2").split("\n")[0].split(",")
X, Y = float(X), float(Y)
return X, Y | 3d56151042682f86350a499ab639852fc6387887 | 78,218 |
import calendar
def update_month(date, month):
"""Create a new date with a modified number of months."""
year = date.year + month // 12
month = month % 12 + 1
day = min(date.day, calendar.monthrange(year, month)[1])
return date.replace(year=year, month=month, day=day) | e9500f7daa65a04d09726ba0ea806fc76ba96e50 | 78,221 |
def can_be_merged(num1, num2):
"""
If two numbers can be merged.
Examples
-----
200 7000 -> True (207000)
250 7000 -> True (257000)
251 7000 -> False (251 7000)
-----
"""
if num2 > num1:
m = get_multiplexer(num2)
num = int(num2 / m)
if is_summable(num1, n... | e9a82c8e5d2f4417cda2aa9f1bb2279854c5c8eb | 78,222 |
import torch
def scatter(tensor, **kwargs):
"""Scatters a list of tensors to all processes in a group.
Each process will receive exactly one tensor and store its data in the
``tensor`` argument.
Arguments:
tensor (Tensor): Output tensor.
src (int): Source rank. Required in all proces... | 051154c5cff8542782f113b4f85a70a6638d5ec4 | 78,223 |
def error(tree, *, syntax, expander, **kw): # noqa: F811
"""[syntax, expr] Produce a test error, unconditionally.
Useful to e.g. indicate to the user that an optional dependency that could
be used to run some integration test is not installed.
Usage::
error["human-readable reason"]
See ... | f3d25c5cde646470ad4a55570babd8f1086178d5 | 78,224 |
import functools
import warnings
def deprecated(message = "Function %s is now deprecated"):
"""
Decorator that marks a certain function or method as
deprecated so that whenever such function is called
an output messaged warns the developer about the
deprecation (incentive).
:type message: Str... | 9c4812653bc74414bed3839e7654f09a114865a0 | 78,225 |
from typing import Optional
from typing import OrderedDict
def read_config(config_filepath: Optional[str] = None) -> ConfigParser:
"""Write the config from the config file.
Arguments:
config_filepath: The path of the config file to read.
Returns:
The config parser read from the config fi... | 33f4ce70923b2787e3979ff02eee7bdaeea7382e | 78,226 |
import torch
def densities(points, means, sigmas):
"""
Compute the unnormalized probability densities of a given set of points for a
given set of multivariate normal distrbutions (MVNs)
:param means: (b, n, c, r) tensor of n vectors of dimension r (in a batch of size b)
representing the means... | 1c3ee74f475bb766157e495aadfe0592dea64f93 | 78,227 |
def set_up_molecules(molecule, landscape, cation):
"""
Set up the List of molecules from Landscape by adding the cation on the
various points of the landscape.
:param molecule:
:param landscape:
:param cation:
:return:
"""
# Check if the molecule has a charge zero
if molecule.c... | b86784cfb2fa1f49940dcf222537833323f4af2b | 78,228 |
import json
def _add_new_point(dimensions, interval, period, count, time):
"""
:param dimensions: dict {"dimension_name": "dimension_value"}
:param interval: point's interval (seconds)
:param period: check period*interval seconds
:param time: point's time
"""
# only not converged item will... | f858144e3d8e807b5cc9da7cf8b9b8a6ad3f8b13 | 78,229 |
def comment(urls):
"""
Construct the bot comment reply for the given url or list of urls.
If urls is a string or a list containing a single string, construct
the single link reply. If urls is a list containing multiple
strings, construct the multi-link reply.
See resources.COMMENT_TEMPLATE_MUL... | 9ca003e39afbe3231a05540d8f08b495f49f3aaa | 78,230 |
def number_of_nodes(graph: Graph, level: int):
"""
Counts the number of nodes at a given level
:param graph: Graph
:param level: Level
:return: Number of nodes at a given level
"""
source = 0
visited = [0] * len(graph.graph)
queue = FifoQueue()
# mark the source node as visited... | 4dd7e347873d2d2475aeb22e485574f85e655712 | 78,231 |
def deduplicate_list_of_OBMols(mols, RMSD_threshold, symmetry) -> list:
"""Filter conformers based on their mutual RMSD, until all molecules have RMSD > threshold.
:param mols: list of OBMol objects
:param RMSD_threshold: RMSD threshold
:param symmetry: boolean, if True symmetry is taken into account w... | 495d714964b1b8ead8d90e712dd50a8af152d0ff | 78,232 |
def csrf_exempt(func):
"""Decorate a Controller to exempt it from CSRF protection."""
func.csrf_enabled = False
return func | 5660d6ef1a9a92a51c4c460f4e9afbe4d5624e0a | 78,233 |
import logging
def sort_in_sysuser(sort, sortOrder):
"""
:param sort:
:param sortOrder:
:return:
"""
logging.info('sort_in_sysuser')
if sortOrder == 'asc':
if sort == 'org_name':
return SysOrg.org_name.asc()
elif sort == 'tel':
return SysOrg.tel.asc... | ee64d79437e8367db2e0e0ec03d183657b2a1e58 | 78,234 |
def sphere(center,radius,imshape=None):
"""Returns an int array (size: n x len(center)) with the xyz... coords of a sphere(elipsoid) of radius in imshape"""
radius_=np.array(radius,dtype=float)
if len(radius_.shape)==0:
radius_ = np.array([radius]*len(center),dtype=np.int)
xyz = np.array(np.indi... | 7dee1cee2e598c751b2234da997d86e5cfe7f21a | 78,235 |
def eval_per_pos_step(model, batch, label_smoothing=0.0, use_bfloat16=False):
"""Calculate evaluation metrics on a batch."""
inputs, targets = batch['inputs'], batch['targets']
weights = jnp.where(targets > 0, 1.0, 0.0)
logits = model(inputs, targets, use_bfloat16=use_bfloat16, train=False,
cac... | c4a35fc182cde05fe105b8dc499eb78cc1942c7a | 78,236 |
import struct
def combine_u32_registers(registers):
""" combine two registers for 32-bit int output """
raw = struct.pack('>HH', registers[0], registers[1])
return struct.unpack('>I', raw)[0] | 67f245a9fada01a693a3cb46536a0df7baba433a | 78,237 |
def create_policy_comment_required(repository_id, branch,
blocking, enabled,
branch_match_type='exact',
organization=None, project=None, detect=None):
"""Create comment resolution required policy.
"""
or... | 780a13ba6745117127c53fc2a17b484a26e7a799 | 78,239 |
def get_gui_thread():
"""Get main (GUI) thread, or ``None`` if Application is not running."""
app=get_app()
return app and app.thread() | bfdc0c54ac4488f769a84cdc656a9888d307a21f | 78,240 |
def mitochondrial_genes(
org: str,
*,
attrname: str = "external_gene_name",
host: str = "www.ensembl.org",
use_cache: bool = False,
chromosome: str = "MT",
) -> pd.DataFrame:
"""\
Mitochondrial gene symbols for specific organism through BioMart.
Parameters
----------
{doc_or... | 67d6d0ccc7949252d0c5ad12d829ae1e3b08a7b9 | 78,241 |
def performDFS(outputs, execute):
"""
Traverses the forest of nodes rooted at outputs nodes and returns the DML script to execute
"""
for m in outputs:
m.output = True
m._visit(execute=execute)
return ''.join(matrix.dml) | 82deb25f35a482e555a8b2e2324673dafa9a2759 | 78,242 |
def exited_project(task_id):
"""
结束项目(休眠)
Args:
task_id:
Returns:
"""
try:
msg = exited_project_co(task_id, current_user.id)
return jsonify(msg)
except Exception as _e:
logger.exception(_e)
return jsonify({"code": -1, "msg": str(_e)}), 205 | 1cf4984a543cd4e434247ed85dc6e5e6bb790081 | 78,244 |
def get_spatial_features(img, size=(32, 32)):
"""Performs spatial binning, reducing size of image, and unravel into feature vector"""
spatial_features = cv2.resize(img, size).ravel()
return spatial_features | 47bbce05170d80774e68c9bb1fd373f671be752f | 78,246 |
def is_complete(status):
"""Returns whether the game has been completed"""
return status in GAME_STATE_COMPLETE | 9c838d538e315a668f724b696acf3785e5029422 | 78,247 |
def priority(priority):
"""
Lookup a syslog priority level.
Accepts either a string or integer priority level. If this is a string, the
value is looked up in the :data:`PRIORITY_NAMES` dictionry.
"""
if isinstance(priority, int):
return priority
elif str(priority) == priority:
... | 98f7a588df0995ff5c361b6cddd8cf9ca52c21bd | 78,248 |
def delete(organisation_id, grade_id):
"""Delete a Grade with a specific ID."""
grade = Grade.query.get_or_404(str(grade_id))
db.session.delete(grade)
try:
db.session.commit()
except Exception:
db.session.rollback()
raise InternalServerError
return Response(mimetype="ap... | a4d7d6d9aab0e40f5bf3ada35883ef6f698d4624 | 78,249 |
import torch
def load_pool5fn_vgg_weights( opt, pool5fn_model ):
"""
Load the weights of a pretrained VGG network into our model, under
the module 'x_conv_layers'. The pretrained model has the
weights saved in a single module, 'features'.
"""
model_fpath = opt.model_fpath
saved_obj = torc... | 582a0afd373486027f8cc5ea86c1753050b635d2 | 78,250 |
def mod_sqrt(a, p):
"""returns x s.t. x**2 == a (mod p)"""
a %= p
if a == 0:
return 0
assert pow(a, (p - 1) // 2, p) == 1
if p & 3 == 3:
return pow(a, (p + 1) // 4, p)
r = ((p - 1) & (1 - p)).bit_length() - 1
s, n = p >> r, 2
while pow(n, (p - 1) // 2, p) != p - 1:
... | aeb9790091293cce5bbc42462e7ed098bcf5507f | 78,251 |
from app.main import main_blu
from app.auth import auth_blu
def create_app(config_type):
""""app初始化"""
# 创建app对象
app = Flask(__name__)
# 获取传入环境对应的配置类,并进行配置设定
config_class = config_dict[config_type]
app.config.from_object(config_class)
# 数据库全局设定
global db, sr,login_manager
db = ... | c67c959566e67ce3d05518622a45f110dd39ef59 | 78,252 |
import webbrowser
import time
def get_oauth_pin(oauth_url, open_browser=True):
"""Prompt the user for the OAuth PIN.
By default, a browser will open the authorization page. If `open_browser`
is false, the authorization URL will just be printed instead.
"""
print('Opening: {}\n'.format(oauth_url)... | 74d7c691cfaa42d717e017fe227b73669ffe3a6d | 78,253 |
def exception_models_to_message(exceptions: list) -> str:
"""Formats a list of exception models into a single string """
message = ""
for exception in exceptions:
if message: message += "\n\n"
message += f"Code: {exception.code}" \
f"\nMessage: {exception.message}" \
... | 56f40ab1fe0d1a03abeaa08d1f9898c7abdb0552 | 78,254 |
def assign_range_end_vars(columns, variables):
"""
SQL component for passing session variables around when executing SELECT.
This will generate list with elements like:
@start_var:=`column_name`
"""
if not columns:
return ''
assign_array = []
for i in range(len(columns)):
... | 6abe917d0d4f031fc2351f494f3c39af678f398b | 78,255 |
def homofire_dwind():
"""Simulate fire on homogeneous field with constant wind which has a direction change with time."""
r_homo = [1]
n = 1
r = 1
while r > .1:
r = np.sqrt(n+1) - np.sqrt(n)
r_homo.append(r)
n = n + 1
radius = np.array(r_homo).cumsum()
pi = np.pi
... | 01dae3e97a38db3e02d2e7b2b14e86a6984e3a6b | 78,256 |
import time
import tqdm
def benchmark(frame_gen_config, number_of_cameras, show_img):
"""Measure performance of this implementation"""
print("Master process started.")
procs = setup_mp_resources(frame_gen_config, number_of_cameras)
time1 = time.time()
for _ in tqdm(range(1000)):
for camer... | 495f01f11fd09bcc8da342b67114a4aa2ae4331e | 78,257 |
def parse_records(database_records):
"""
A helper method for converting a list of database record objects into a list of dictionaries, so they can be returned as JSON
Param: database_records (a list of db.Model instances)
Example: parse_records(User.query.all())
Returns: a list of dictionaries, e... | ac3ea050697d6c0e0995b35079538e7df2db4d84 | 78,258 |
def list_path_responses_datafile(datafile, system_name):
"""
Returns the path_list and responses_list
path_list contains list of response_path tags under the comparison_mode
under the system with given system_name in the datafile
responses_list contains list of response_value tags un... | dec5ee4b7a97e0ccc93b3a5b976d17ab0a14a95d | 78,259 |
from typing import Tuple
async def get_ga4gh_permissions(token: str) -> Tuple[set, bool]:
"""Retrieve GA4GH passports (JWTs) from ELIXIR AAI and process them into tangible permissions."""
LOG.info("Handling permissions.")
# Return variables
dataset_permissions = set()
bona_fide_status = False
... | dd6c508d6361acb1f815bbe5666618055f359531 | 78,261 |
def resnet50(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])... | 6d07f576b309d523b623f823f097abad1f056c64 | 78,262 |
import re
def parse_version(str_):
"""
Parses the program's version from a python variable declaration.
"""
v = re.findall(r"\d+.\d+.\d+", str_)
if v:
return v[0]
else:
print("cannot parse string {}".format(str_))
raise KeyError | 7def768ec9790d610922774eb4aab22f4531b1d3 | 78,263 |
def vit_base_patch32_384(pretrained=False, progress=True, **kwargs):
"""
Constructs the ViT-Base-patch32-384 model.
.. note::
ViT-Base-patch32-384 model from `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https://arxiv.org/pdf/2010.11929.pdf>`_.
The required ... | 3f91bbadc199090139e907dafd2a7296bab157f3 | 78,264 |
import re
def parse_numex(entity, tag=numex_pfx):
"""
Parse numerical expression (Numex).
"""
normalized = []
unit = entity.pop()
while entity:
wform, lemma, morph = entity.pop()
if entity and 'NUMERAL' in morph:
normalized.append(get_partitive(wform, l... | 7aa4fbe306ccbbcae4daa5e6342c34ba39739847 | 78,265 |
def cut_string(string: str, length: int) -> list:
"""
每隔l个字符切分字符串
:param string: 字符串
:param length: 切分长度
:return: 切分后产生的list
"""
string = string.strip().replace('\n', ' ')
res, cur, cnt = [], '', 0
for i in string:
cnt += 2 if ord(i) > 255 else 1
if cnt <= length:
... | 830fdfad42c8c93d49eb2260e8f317b01c89b3dd | 78,266 |
def segment(sentence, cut_type='word', pos=False):
"""
切词
:param sentence:
:param cut_type: 'word' use jieba.lcut; 'char' use list(sentence)
:param pos: enable POS (词性标注)
:return: list
"""
if pos:
if cut_type == 'word':
word_pos_seq = posseg.lcut(sentence)
... | 4a5889827ad047c1adbdc8e59fba805d39bf4be8 | 78,267 |
from typing import Dict
def _json_list2dict(d:Dict)->Dict:
"""
Loop through all fields, and once it meet a list, it convert into a dict.
The converted output contains the index of the list as a key.
Conversion is done deeply to last level.
Parameters
----------
d : Dict
initia... | 246387cc4a9c9b384f7c4ddc29d17cd916875146 | 78,268 |
import json
import time
def get(identifier, namespace='cid', domain='compound', operation=None, output='JSON', searchtype=None, **kwargs):
""" Request wrapper that automatically handles async requests. """
if searchtype or namespace in ['formula']:
response = request(identifier, namespace, domain, Non... | 38aa30a0a73f8f6b1cd2c1e92c151d1bb7d88c44 | 78,270 |
def update(sample_id):
"""Update information about a sample."""
sample_obj = sample_or_404(sample_id)
sample_obj.sex = request.form["sample_sex"] or None
sample_obj.comment = request.form.get("comment")
for analysis in sample_obj.analyses:
analysis.sex = request.form["{}_sex".format(analysis... | 0dfa215416b143b1d5fa33fd9601d78dfc82305f | 78,271 |
def missing_percentage(ssnvs_matrix):
"""
Calculate missing percentage to detect correct folder name output from siclonefit
:return:
"""
missing_percent = str(ssnvs_matrix.isnull().sum().sum() /
(ssnvs_matrix.shape[0] * ssnvs_matrix.shape[1])).split(".")[1][0:2]
if len(mi... | a82c0252996db14c42143895ba87d58460ea797c | 78,272 |
def generating_destination(trips):
"""
lookup vlaues from next row for same bike
"""
trips.loc[(
(trips['bike_id'] == trips['bike_next_row']) &
(trips['dt_min_next_row'] > trips['dt_start'])
),
'trip_end_time'] = trips['dt_min_next_row']
trips.loc[(
... | 50c9549f42de7f5bba5c15430651e3c0d813b31f | 78,275 |
from typing import Any
def dynamic_unroll_fori_loop_universal(
fun: hk.TransformedWithState,
params: Any,
state: Any,
rng: jnp.ndarray,
skip_first: bool = False,
*args,
**kwargs,
):
"""Unroll a TransformedWithState function using fori_loop in an universal way.
Args:
fun : ... | 72384f83395e3f46d8083aba77622b13b918fae7 | 78,276 |
def update_user(id):
"""This API route modify an existing user."""
if g.current_user.id != id:
abort(403)
user = User.query.get_or_404(id)
data = request.get_json() or {}
if (
"username" in data
and data["username"] != user.username
and User.query.filter_by(username=d... | 3f8b6c5d10406c97a97e3aea1013b804d57bdc3b | 78,277 |
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
"""
Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
Arguments:
X -- data, numpy array of shape (number of examples, num_px * num_px * 3)
Y -- true "label" ... | f219bc87bf3a1d2e1f903dc074f08816cc45c732 | 78,278 |
def read_all(filename):
""" Read all file content """
try:
with open(filename, "r", encoding="utf-8") as input_file:
return input_file.read()
except FileNotFoundError:
LOGGER.error(f"{filename} does not exist.") | 38b29994d63215182d85d82981f09bdf61d33d26 | 78,279 |
def respond_telegram():
""" Handles the incoming messages and provides a response """
try:
# Get the msg in JSON and convert it into a Telegram obj.
update = telegram.Update.de_json(request.get_json(force=True), bot)
# Extract message's fields: user, chat_id, msg_id, text, entities... | 5932d922c4b484db9c1ec514fbe0fbef7f4f0ab0 | 78,280 |
def test(student_module):
"""Grade a student's entire solutions file.
10 points for problem 1
5 points for problem 2
5 points for problem 3
10 points for problem 4
10 points for problem 5
Inputs:
student_module: the imported module for the student's file.
Returns:
sc... | 72115d8d104df2ff0effdfd88c985dcaa551735d | 78,281 |
def crypt4gh_to_user_errors(func):
"""Convert Crypt4GH exceptions to User Errors decorator."""
@wraps(func)
def wrapper(*args):
try:
return func(*args)
except (crypt_exc.InvalidFormatError, crypt_exc.VersionError, crypt_exc.MDCError, PGPKeyError) as e:
LOG.error(f'Con... | c6b71a02426de8fc53bfe701e946389d954fc8f1 | 78,282 |
def _fetch_barcode_metadata(sample_barcode):
"""Query the private API to obtain per-sample metadata
Parameters
----------
sample_barcode : str
The barcode to request
Returns
-------
dict
The survey responses associated with the sample barcode
dict or None
Any er... | 16c29f443181032bf294e46fdc6d640f77673b12 | 78,283 |
def to_unicode(input):
"""
:param input:
:return:
"""
retstr = RE_ENTITY.sub(sub_entity, input)
return retstr | 54e61d23ab27f8fe3fa9d9b562eba4c7763a9874 | 78,284 |
def calc_V_matrix_adf(x):
"""
Calculate the lower triangle (row order)
of the diabatic matrix given adf input
"""
a0 = n2.constants.a0
RCC = x[0] / a0 # C--C bond length, convert angstroms to bohr
RCH = x[1] / a0 # C--H bond length, convert angstroms to bohr
theta = x[2] # C--C--... | c8848a3274dde915d1848d0b01269231f813fc6a | 78,285 |
def match_observed_and_imputed_snps_bgen(gts_f, par_gts_f, snp_ids=None, start=0, end=None):
"""
Used in get_gts_matrix_given_ped to match observed and imputed SNPs and return SNP information on shared SNPs.
Removes SNPs that have duplicated SNP ids.
in_obs_sid contains the SNPs in the imputed genotypes... | ac244db3cfadd59b5c659bd915ebc8dac7a2e11e | 78,286 |
def _all_rois(roidb, im_scale, batch_idx):
"""Pass all RoIs with labels.
"""
max_overlaps = roidb['max_overlaps']
# Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = np.where(
(max_overlaps < cfg.TRAIN.BG_THRESH_HI) &
(max_overlaps >= cfg.TRAIN.BG_THRESH_... | a35ea850436719e7a68ba35798b424a00992d57a | 78,288 |
from pathlib import Path
import numpy as np
import nibabel as nb
import nitransforms as nt
from scipy.ndimage.filters import gaussian_filter
def _conditional_downsampling(in_file, in_mask, zoom_th=4.0):
"""Downsamples the input dataset for sloppy mode."""
img = nb.load(in_file)
zooms = np.array(img.head... | df6f9203f17e333a325180da7f6032d30590bba0 | 78,289 |
def requery(args, kwargs):
"""
Re-query database models passed into function to enable
safer threaded operations. This is typically reserved
for api methods that submit asyncronous tasks to a separate
executor that uses a different database session.
"""
# get local db proxy
db = current_... | 0abcd570ef836b94881c886ab23dc108306dffaa | 78,290 |
def transform_pts(pts_coords_init, h_mat):
"""Transforms input points according to homography.
Args:
pts_coords_init : [...] X H X W X 3; pixel (u,v,1) coordinates.
h_mat : [...] X 3 X 3; desired matrix transformation
Returns:
pts_coords : [...] X H X W X 3; transformed (u, v, w) coordinates.
... | 0cd17cae4f26f27d5f73c920bf66112519b168f5 | 78,291 |
def purge_version(hostname=get_hostname()):
"""
You can select which pax version you want purge
in this way "vX.x.x" where X is the main pax version
and x.x are the different relase. i.e. pax_v1.2.3
"""
return get_config(hostname).get('pax_version_purge',
... | caf5ae9ffb3394d67c1fee0e7d09c10355c78157 | 78,292 |
def rshape(n_qnums):
"""Return a function that generates random shapes for symmetric tensors."""
def _rshape(n=None, chi=None, nlow=0, nhigh=5, chilow=0, chihigh=3):
"""Return a random shape for a symmetric tensor.
`n` is the number of indices, `chi` is the bond dimension of each
symme... | ca1c7128ab128638f41f72022ca14d46b376be26 | 78,293 |
import re
def clean_license_name(license_name):
"""Remove the word ``license`` from the license
:param str license_name: Receives the license name
:return str: Return a string without the word ``license``
"""
return re.subn(r'(.*)\s+license', r'\1', license_name, flags=re.IGNORECASE)[0] | 970d933911b69ba9a1f33a768bc68032334d41c3 | 78,294 |
import csv
def read_csv_wind_parameters(csv_uri, parameter_list):
"""Construct a dictionary from a csv file given a list of keys in
'parameter_list'. The list of keys corresponds to the parameters names
in 'csv_uri' which are represented in the first column of the file.
csv_uri - a URI to... | 80f8e46f8739975b51ab320b9e6ce747c7a642d7 | 78,297 |
def is_slice_notation(value):
"""Return True if the value is made up of multiple"""
return isinstance(value, str) and (":" in value) | 71926dfb60d018b56546d8c6b02985d5a8262ae5 | 78,298 |
def plot_forecast(x, y,
forecast_mean, forecast_scale, forecast_samples,
title, x_locator=None, x_formatter=None):
"""Plot a forecast distribution against the 'true' time series."""
colors = sns.color_palette()
c1, c2 = colors[0], colors[1]
fig = plt.figure(figsize=(1... | 8a53531340afe5dde07c2506013a7442374eef6c | 78,299 |
from unittest.mock import patch
def patch_connect(success):
"""Mock the `adb_shell.adb_device.AdbDeviceTcp` and `ppadb.client.Client` classes."""
def connect_success_python(self, *args, **kwargs):
"""Mock the `AdbDeviceTcpFake.connect` method when it succeeds."""
self.available = True
de... | 71591483fadd5a9619badaea720c4aacc93bcc5d | 78,300 |
def interp(t, meas, dt=0.5, t_min=-1, t_max=-1):
"""
Interpolates measurements from manually recorded data recorded over time.
PARAMETERS:
t : numpy array
Independent variable (typically time)
meas : numpy array
Dependent variable (typically a measurement)
dt ... | e733a7701b5cbfe82056660320507251e5665e6c | 78,301 |
from typing import Iterable
from typing import List
import copy
def replace_reversible_rxns(rxns: Iterable[Reaction]) -> List[Reaction]:
"""
Args:
rxns: list of :any:`Reaction`'s
Returns: list of :any:`Reaction`'s, where every reversible reaction in `rxns` has been replaced by
two irrever... | d96e2f8140c8cb9919aa59c0d3725881feeef834 | 78,302 |
def push_front(table, offset, X, Y, cur_context, base):
"""
Push base to the end of the current context to find the new X/Y/context
"""
print(f"Context [{X}, {Y}) '{cur_context}' -> pushing {base}")
Xa = table[X][4][LETTERS.index(base)]
Ya = table[Y][4][LETTERS.index(base)]
Xb = Xa + offse... | 0ccd7e7e1ee6ac54c803b02040cdfa58c6475cec | 78,303 |
def moneyfmt(val, curr=None, places=-1, grouping=True, wrapcents='', current_locale=None):
"""Formats val according to the currency settings in the current locale.
Ported-and-modified from Python 2.5
"""
conv = get_locale_conv(current_locale)
if places < 0:
places = conv['int_frac_digits']
... | b3bc262ede1e5c304e219de159b1a88f33bbda09 | 78,304 |
def _specfiledata_getdoc(method):
""" to get the docstring of method inside a class """
s = SpecfileData('DUMMY!')
head = "\n Docstring from {0}:\n -------------------\n".format(method)
return head + getattr(getattr(s, method), '__doc__') | 98dd79ea5d03b3735ed9f6fb9256728d82a2e789 | 78,305 |
def parse_reactions(reaction_filename, df):
""".
Cre.ate the reactions described in reaction_filename, from the parsed molecules.
"""
# Sort so the order for the reactions are correct
df.sort_values(['functional', 'basis', 'unrestricted', 'molecule'], inplace=True)
# make new dataframe for the r... | ceb7312912f8a1617e83ce980c0aa8c97a3bcbc3 | 78,307 |
def encode(message):
"""
Encodes the message
:param message: String message to be encoded
:return: encoded message
:rtype str
"""
normalize_text = normalize(message)
square_size = get_square_size(normalize_text)
c, res = 0, []
while c < square_size:
for segment in get_seg... | 8ab316a3c819b5812d29c6736768bb303602a2c0 | 78,308 |
from typing import Optional
import functools
def until_thold_exceeded(thold: float, max_rep: Optional[int] = None):
"""
Designed to wrap a function and repeat it until the return value exceeds a threshold.
.. note::
The wrapped function must accept the kwarg `cnt_rep`. This can be useful to trigg... | 920e84b241b87ca403548356f16731562d6f425a | 78,309 |
def open_serial_port(port,
baud_rate,
to):
"""
Opens a connection to the serial port and return the resource.
"""
# Open the device
s = serial.Serial(port,
baud_rate,
timeout=to)
# Serial port should h... | f1adbb515697d3aa4466a362668c54b484c15013 | 78,310 |
def simpleln(theta, xi, yi, ei):
""" Simple chisquare model with only measurement
uncertainties """
f0, t0, gamma = theta
if 0 <= f0 < 3 and -14 <= t0 < 4 and -2 <= gamma < 9:
model = f0 * np.exp(-np.exp(t0) * (1 + xi) ** gamma)
return -0.5 * np.sum((yi - model) ** 2 / ei ** 2)
retur... | 58090adf3c2a7383f37c6bee7383934dc58cbaa7 | 78,311 |
from typing import Optional
from typing import Sequence
def plot_regret_group_nosmooth(df_in: pd.DataFrame,
group_col: str,
sweep_vars: Optional[Sequence[str]] = None,
regret_col: str = 'total_regret',
... | 196d6bbc7bd55040333cfe19815f0dbd0304a52f | 78,312 |
import requests
def get_cached_data(url):
"""Wrap requests with a short cache."""
source_data = requests.get(url).json()
return source_data | c1cd251db1b915024bad6bc590160c38e61c38bb | 78,313 |
def show_role_binding(name, namespace="default", **kwargs):
"""
Return the kubernetes RoleBinding defined by name and namespace
CLI Examples::
salt '*' kubernetes.show_role_binding kube-proxy kube-system
salt '*' kubernetes.show_role_binding name=kube-proxy namespace=kube-system
"""
... | 0c751d621603854196f1453b5d304ebc11650d56 | 78,314 |
def render(fragment, data, mode, context=None):
"""Render the fragment after exanping it using given data and parameters
This creates a text-rendered expanded fragment.
:param fragment: [required] fragment to be expanded
:type fragment: MelangeFragment object
:param data: [required] data with data... | 17cc65cc925f51c3ce4efa561c01882fb43ef36e | 78,315 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.