content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def writeData(filename, data):
"""
MBARBIER: Taken/adapted from https://github.com/ChristophKirst/ClearMap/blob/master/ClearMap/IO/TIF.py
Write image data to tif file
Arguments:
filename (str): file name
data (array): image data
Returns:
str: tif file name
... | cc4414b9f52413bebc422032f796cd242ecc8ef4 | 3,656,000 |
def get_trigger_function(trigger_message, waiter):
"""Función auxiliar que genera un activador
Args:
trigger_message: mensaje o instruccion para continuar.
waiter: función que pausa el flujo de instrucciones.
"""
def trigger_function():
# Se imprime la instrucción par... | b389dd93631ae396c65d5653da6cea3ec91b3556 | 3,656,001 |
def find_peaks(amplitude):
"""
A value is considered to be a peak if it is higher than its four closest
neighbours.
"""
# Pad the array with -1 at the beginning and the end to avoid overflows.
padded = np.concatenate((-np.ones(2), amplitude, -np.ones(2)))
# Shift the array by one/two value... | 192f25bbc491c7e880ff5363098b0ced29f37567 | 3,656,002 |
from typing import Optional
def sync(
*,
client: Client,
json_body: CustomFieldOptionsCreateRequestBody,
) -> Optional[CustomFieldOptionsCreateResponseBody]:
"""Create Custom Field Options
Create a custom field option. If the sort key is not supplied, it'll default to 1000, so the option
app... | 6215e704be4bbc32e52fb03817e00d7fd5338365 | 3,656,003 |
def decrypt_with_private_key(data, private_key):
"""Decrypts the PKCS#1 padded shared secret using the private RSA key"""
return _pkcs1_unpad(private_key.decrypt(data)) | f1dac9113fb97f62afab524239e38c6cb196c989 | 3,656,004 |
import os
import re
def loadvars(builddir):
"""if builddir does not exist or does not have a cache, returns an
empty odict"""
v = odict()
if builddir is None or not os.path.exists(builddir):
return v
c = os.path.join(builddir, 'CMakeCache.txt')
if os.path.exists(c):
with open(c... | 6069461706d88f3dee96eb6b9aece29b3f47c77b | 3,656,005 |
import warnings
def deprecated (func):
"""
This is a decorator which can be used to mark functions as deprecated. It
will result in a warning being emitted when the function is used.
:param func: original function
:type func: :any:`collections.Callable`
:return: decorated func
:rtype: :any:`collections... | ba237c30d97013080bd84569af1817685023dab6 | 3,656,006 |
import re
def prediction():
"""
A function that takes a JSON with two fields: "text" and "maxlen"
Returns: the summarized text of the paragraphs.
"""
print(request.form.values())
paragraphs = request.form.get("paragraphs")
paragraphs = re.sub("\d+", "", paragraphs)
maxlen = int(request... | a1bdf996908e65e3087ed4ffe27402c9763b4d69 | 3,656,007 |
def is_reviewer(user):
"""Return True if this user is a financial aid reviewer"""
# no need to cache here, all the DB lookups used during has_perm
# are already cached
return user.has_perm("finaid.review_financial_aid") | e3c599f78eb51c33ab48e3760c0f2965ba305916 | 3,656,008 |
def getLogMessage(commitSHA):
"""Get the log message for a given commit hash"""
output = check_output(["git","log","--format=%B","-n","1",commitSHA])
return output.strip() | 2d42e587da57faff5366fc656e8d45a8fa797208 | 3,656,009 |
def get_old_stacks(cfn, old_instances, debug=True):
""" Gets all of the stacks for the old RDS instances """
old_stacks = get_cfn_stack_for_rds(cfn, old_instances, debug)
if debug:
print("DEBUG: Old stacks found: %s" % len(old_stacks))
return old_stacks | 0512b9b9f6043ba5db31a88786e23296ae4c03dc | 3,656,010 |
def sup(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", translat... | dff8635d98f68e5b024fe23cbeaa6a1a9884222f | 3,656,011 |
def isnonempty(value):
"""
Return whether the value is not empty
Examples::
>>> isnonempty('a')
True
>>> isnonempty('')
False
:param value: string to validate whether value is not empty
"""
return value != '' | 0250cb455d8f77027d5cde9101a24683950bbdb2 | 3,656,012 |
def InstallSystem(config, deployment, options):
"""Install the local host from the sysync deployment configuration files."""
installed = {}
# Create fresh temporary directory
Log('Clearing temporary deployment path: %s' % config['deploy_temp_path'])
run.Run('/bin/rm -rf %s' % config['deploy_temp_path'])
... | 642eda86228e5575bc7267d9b3a5c3ddc055daf4 | 3,656,013 |
def preprocess_input(x):
"""前処理。"""
return tf.keras.applications.imagenet_utils.preprocess_input(x, mode="torch") | 6795c5e571d67a7908edbe3c3ca0ed5e3412d2f0 | 3,656,014 |
def attribute_to_partner_strict(partner, partner_string_or_spec, amount):
"""Return the amount attributable to the given partner."""
spec = (
partner_string_or_spec
if isinstance(partner_string_or_spec, dict)
else parse_partner_string(partner_string_or_spec)
)
if partner not in s... | d7e00b50e8be010d7896b6c51e1e3fcfe73438d2 | 3,656,015 |
import math
def drawLines(img, lines, color=(255,0,0)):
"""
Draw lines on an image
"""
centroids = list()
r_xs = list()
r_ys = list()
for line_ in lines:
for rho,theta in line_:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0... | 5918bb1a81d8efae2874f294d927f7b01527d1d1 | 3,656,016 |
import numpy
def moments_of_inertia(geo, amu=True):
""" principal inertial axes (atomic units if amu=False)
"""
ine = inertia_tensor(geo, amu=amu)
moms, _ = numpy.linalg.eigh(ine)
moms = tuple(moms)
return moms | 34153dba5ea49d457ee97d4024a103b0d05c6bd0 | 3,656,017 |
def greenblatt_earnings_yield(stock, date=None, lookback_period=timedelta(days=0), period='FY'):
"""
:param stock: ticker(s) in question. Can be a string (i.e. 'AAPL') or a list of strings (i.e. ['AAPL', 'BA']).
:param date: Can be a datetime (i.e. datetime(2019, 1, 1)) or list of datetimes. The most recen... | 333b12b609523ab16eeb1402d0219264a3a159e3 | 3,656,018 |
import shutil
def remove_directory(dir_path):
"""Delete a directory"""
if isdir(dir_path):
try:
shutil.rmtree(dir_path)
return ok_resp(f'Directory removed {dir_path}')
except TypeError as err_obj:
return err_resp(f'Failed to remove directory. {err_obj}')
... | c174568c024cff1948bdf78206e49c2ca40c6b25 | 3,656,019 |
def new_eps_after(since_ep):
"""
:param since_ep: Episode instance
:return: Number of episodes since then
"""
session = Session.object_session(since_ep)
series = since_ep.series
series_eps = session.query(Episode).join(Episode.series).\
filter(Series.id == series.id)
if series.id... | 218d19672d0fe3b0b14fa6443c6c00bbd12ba495 | 3,656,020 |
from pathlib import Path
from typing import Iterator
import os
def parse_json_main_index(out_dir: Path=OUTPUT_DIR) -> Iterator[Link]:
"""parse an archive index json file and return the list of links"""
index_path = os.path.join(out_dir, JSON_INDEX_FILENAME)
if os.path.exists(index_path):
with ope... | 237b3887cbba40734b820b59200513d614697862 | 3,656,021 |
from re import DEBUG
import sys
def header_maxperdisc(ctx, institution, requirement_id):
"""
header_maxperdisc : maxperdisc label? ;
"""
if DEBUG:
print(f'*** header_maxperdisc({class_name(ctx)=}, {institution=}, {requirement_id=}',
file=sys.stderr)
return_dict = {'label': get_label(ctx)}... | f0e0d35b75692ec7daae12acedadd0b834994b7e | 3,656,022 |
def set_route_queue(path_list,user_position,sudden_id,sudden_xy,pi):
"""
最後の患者が一番近い医師が行くようにする
"""
minimum_dis = 100
minimum_idx = 0
for i in range(len(path_list)):
dis = np.sqrt((user_position[path_list[i][-2]][0] - sudden_xy[0])**2 + (user_position[path_list[i][-2]][1] - sudden_xy[1])**... | 0425c3edf2d488680ccb54661e79698a506e4fe4 | 3,656,023 |
def add(x, y):
"""Add two numbers together."""
return x+y | 92015156eac5bc9cc0be3b1812f9c0766f23020c | 3,656,024 |
import tempfile
import os
def _get_thintar_prefix(tarname):
"""
Make sure thintar temporary name is concurrent and secure.
:param tarname: name of the chosen tarball
:return: prefixed tarname
"""
tfd, tmp_tarname = tempfile.mkstemp(
dir=os.path.dirname(tarname),
prefix=".thin-... | e893309972742ffb52fd13911b5805e51b2baadc | 3,656,025 |
import requests
def retry_session(tries=2,
backoff_factor=0.1,
status_forcelist=(500, 502, 504),
session=None):
"""
Parameters
----------
tries : int, number of retires.
backoff_factor : A backoff factor to apply between attempts after the
... | 5766c4623e0e53f4353de1e58080c1ad5c9b4080 | 3,656,026 |
def vc(t, delta, beta):
"""velocity correlation of locus on rouse polymer. beta = alpha/2."""
return ( np.power(np.abs(t - delta), beta)
+ np.power(np.abs(t + delta), beta)
- 2*np.power(np.abs(t), beta)
)/( 2*np.power(delta, beta) ) | 89eff8a8cdb0e84a69e7990ebf0c128ca27ecea8 | 3,656,027 |
def algorithm(name):
"""
A function decorator that is used to add an algorithm's Python class to the
algorithm_table.
Args:
A human readable label for the algorithm that is used to identify it in
the GUI
"""
def decorator(class_):
algorithm_table[name] = class_
r... | 8f67fec3f1933dc0ea041322fcf041f2247bc638 | 3,656,028 |
def comp_easy():
"""Get easy components."""
return Components(ewlaps, gi_setting.DEFAULT_EASY) | d15093dce67657b05665d7a9373d1328b4171f91 | 3,656,029 |
def play(player1, player2, rounds=1, verbose=False, symdict=None):
"""Play a number of `rounds` matches between the two players and return
the score $S = sum_j a_j$, where
a_j = 1 if player1 wone --or-- -1 if player2 wone --or-- 0 otherwise.
"""
if player1 is player2:
raise AttributeEr... | 28e0cc41d664a6681b4af1216d0de6f1a2871f04 | 3,656,030 |
def calc_deltabin_3bpavg(seq, files, bin_freqs, seqtype = "fastq"):
"""
At each position (starting at i), count number of sequences where
region (i):(i+3) is mutated. This is sort of a rolling average and not critical
to the result. It just ends up a bit cleaner than if we looked at a single
base pa... | 5ea614e7280d6ed288ea03e63e86e3129d4e4994 | 3,656,031 |
def make_right_handed(l_csl_p1, l_p_po):
"""
The function makes l_csl_p1 right handed.
Parameters
----------------
l_csl_p1: numpy.array
The CSL basis vectors in the primitive reference frame of crystal 1.
l_p_po: numpy.array
The primitive basis vectors of the underlying lattic... | 3b5e3f21e6da5292fb84eb632ddcfa2ec52507ee | 3,656,032 |
import logging
def process_task(f, module_name, class_name, ftype, f_parameters, f_returns,
task_kwargs, num_nodes, replicated, distributed,
on_failure, time_out):
"""
Function that submits a task to the runtime.
:param f: Function or method
:param module_name: Name ... | 3527b5eb51c1ed5b5a9000e48ff940a63f1610db | 3,656,033 |
def company(anon, obj, field, val):
"""
Generates a random company name
"""
return anon.faker.company(field=field) | 95580147817a37542f75e2c728941a159cd30bd3 | 3,656,034 |
def delete_schedule():
"""
При GET запросе возвращает страницу для удаления расписания.
При POST запросе, удаляет выбранное расписани
(Запрос на удаление идэт с главной страницы(func index), шаблона(template) функция не имеет).
"""
if not check_admin_status():
flash(f'У вас нет прав для ... | 1e73c757956d4bd78f3a093e2a2ddfde894aeac5 | 3,656,035 |
import json
def dict_from_JSON(JSON_file: str) -> dict:
"""
Takes a WDL-mapped json file and creates a dict containing the bindings.
:param JSON_file: A required JSON file containing WDL variable bindings.
"""
json_dict = {}
# TODO: Add context support for variables within multiple wdl files... | 98deccce943e5506233f1e20d73c4d03eda16858 | 3,656,036 |
def show(id):
"""Renderiza a página de um político específico."""
p = Politico.query.get_or_404(id)
# Aplica os filtros de mes, ano e a paginação
mes, ano, tipo, page = (request.args.get("mes"),
request.args.get("ano", 2020, type=int),
request.args... | b06ce6275819d32e9dff1945e97425ee696c1313 | 3,656,037 |
def map_datapoint(data_point: DATAPOINT_TYPE) -> SFX_OUTPUT_TYPE:
"""
Create dict value to send to SFX.
:param data_point: Dict with values to send
:type data_point: dict
:return: SignalFx data
:rtype: dict
"""
return {
"metric": data_point["metric"],
"value": data_point[... | cf5d7eb1bded092adb2b002ee93ad168e696230a | 3,656,038 |
def write_obs(mdict, obslist, flag=0):
"""
"""
# Print epoch
epoch = mdict['epoch']
res = epoch.strftime("> %Y %m %d %H %M %S.") + '{0:06d}0'.format(int(epoch.microsecond))
# Epoch flag
res += " {0:2d}".format(flag)
# Num sats
res += " {0:2d}".format(len(mdict)-1)
res += '\n'
... | 5a91b02fce07f455f4442fe6fbf76d3609f5a74e | 3,656,039 |
from typing import Optional
from typing import Union
import fsspec
def open_view(
path: str,
*,
filesystem: Optional[Union[fsspec.AbstractFileSystem, str]] = None,
synchronizer: Optional[sync.Sync] = None,
) -> view.View:
"""Open an existing view.
Args:
path: View storage directory.
... | b12471f59ef78e444a43c0e766cb6b4237e65338 | 3,656,040 |
def smi2xyz(smi, forcefield="mmff94", steps=50):
"""
Example:
utils.smi2xyz("CNC(C(C)(C)F)C(C)(F)F")
returns:
C 1.17813 0.06150 -0.07575
N 0.63662 0.20405 1.27030
C -0.86241 0.13667 1.33270
C -1.46928 -1.21234 ... | 083bbc1a242a3f5f247fc6f7066e099dab654b7a | 3,656,041 |
from typing import Optional
from typing import Tuple
from typing import List
def pgm_to_pointcloud(
depth_image: np.ndarray, color_image: Optional[np.ndarray],
intrinsics: Tuple[float, float, float, float],
distortion: List[float]) -> Tuple[np.ndarray, Optional[np.ndarray]]:
"""Fast conversion of opencv... | 574d514c216f0db1f90bf277dc78a5b5dcc2535a | 3,656,042 |
def matching_poss(poss_1, poss_2):
"""Count how many rows the possibilities have in common.
Arguments:
poss_1 {np.array} -- possibilities 1
poss_2 {np.array} -- possibilities 2
Returns:
int -- the count/matches
"""
matches = 0
for row_2 in poss_2:
for row_1 in p... | 096214d8e2115afd21cbd76b28cafa54574cdfb1 | 3,656,043 |
from collections import Counter
def unk_emb_stats(sentences, emb):
"""Compute some statistics about unknown tokens in sentences
such as "how many sentences contain an unknown token?".
emb can be gensim KeyedVectors or any other object implementing
__contains__
"""
stats = {
"sents": 0... | 221b88e2124f3b8da2976a337476a11a7276a470 | 3,656,044 |
import os
def basename(path: str) -> str:
"""Returns the basename removing path and extension."""
return os.path.splitext(os.path.basename(path))[0] | 63e8e0220d1c2a9fc5b30d4bff2b609517d8cd18 | 3,656,045 |
from typing import List
async def search_dcu(
ldap_conn: LDAPConnection, dcu_id: str = None, uid: str = None, fullname: str = None
) -> List[DCUUser]:
"""
Seach DCU AD for user
Args:
ldap_conn: LDAP connection to use for searching
uid: Usersname to search for
dcu_id: dcu stude... | 32444b30f1463332f51720eef3167c3495deeaec | 3,656,046 |
def jump(inst_ptr, program, direction):
"""Jump the instruction pointer in the program until matching bracket"""
count = direction
while count != 0:
inst_ptr += direction
char = program[inst_ptr]
if char == '[':
count += 1
elif char == ']':
count -= 1
... | 76c6c4dcf4dbc452e9f2b252522871fcca95c75d | 3,656,047 |
import gecosistema_core
import os
import math
def htmlResponse(environ, start_response=None, checkuser=False):
"""
htmlResponse - return a Html Page
"""
if checkuser and not check_user_permissions(environ):
environ["url"] = justpath(environ["SCRIPT_FILENAME"])+"/back.html"
return html... | bc1ee0367b64c7cfc915ab66e9c519ad101f939e | 3,656,048 |
def center_image(IM, method='com', odd_size=True, square=False, axes=(0, 1),
crop='maintain_size', verbose=False, center=_deprecated,
**kwargs):
"""
Center image with the custom value or by several methods provided in
:func:`find_origin()` function.
Parameters
----... | 7b9793d720228a246df07c08a2aeda861108f92e | 3,656,049 |
import pysam
from cyvcf2 import VCF
import gzip
import os
def check_header(install_path):
"""Method to check the final genomics headers have a header or not
check_header
============
This method is going to go through each of the files that were created by the recipe,
and it will check if the t... | 6a87251381c7c4af0dd3fb3ac8e1cf252c380254 | 3,656,050 |
def get_mapping(mapping_name):
"""
Reads in the given mapping and returns a dictionary of letters to keys. If the given mapping is a dictionary,
does nothing an returns the mapping
mpaping_name can be a path to different file formats
"""
# read in mapping
if type(mapping_name) =... | 1e4f99d14b242ba4e8760fafecd83cd32932a92c | 3,656,051 |
def evaluate(model, reward_gen, n_steps=1000000, delta=1):
"""Evaulate the regrets and rewards of a given model based on a given reward
generator
Args:
model (TYPE): Description
n_steps (int, optional): Description
delta (int, optional): Number of steps for feedback delay
re... | a326e905156f6ac195eeb993878ae651a13a306e | 3,656,052 |
def get_photo_from_response(response: dict):
"""
parse json response and return an Photo
Keyword arguments:
response -- meetup api response in a dict
return -> get or create Photo
"""
photo, create = Photo.objects.get_or_create(meetup_id=response["id"])
# add optional fields
if "... | 9f0aeee796c1131424a7f4292a2b712d2bf0158e | 3,656,053 |
from typing import Union
from typing import List
from typing import Tuple
def composition_plot(adata: AnnData, by: str, condition: str, stacked: bool = True, normalize: bool = True,
condition_sort_by: str = None, cmap: Union[str, List[str], Tuple[str]] = None,
**kwds) -> hv.c... | f2e588c0ce6d195201754885bbd90aae83b49ba7 | 3,656,054 |
def region_of_province(province_in: str) -> str:
"""
Return the corresponding key in ITALY_MAP whose value contains province_in
:param province_in: str
:return: str
"""
region = None
for r in ITALY_MAP:
for p in ITALY_MAP[r]:
if province_in == p:
region = ... | 1aa29235d569929a0cfbbc4258d45ba4f0171f3c | 3,656,055 |
def filter_stopwords(words:list)->iter:
"""
Filter the stop words
"""
words = filter(is_not_stopword, words)
return words | a5516886be0ce5c8671ef259baf38b04d61c511f | 3,656,056 |
def numpy_jaccard(box_a, box_b):
"""计算两组矩形两两之间的iou
Args:
box_a: (tensor) bounding boxes, Shape: [A, 4].
box_b: (tensor) bounding boxes, Shape: [B, 4].
Return:
ious: (tensor) Shape: [A, B]
"""
A = box_a.shape[0]
B = box_b.shape[0]
box_a_x1y1 = np.reshape(box_a[:, 2:], ... | 1c0aed3c354a9253c5f9278109cd13365941846c | 3,656,057 |
import uuid
def test_get_rule(client_rule_factory, client_response_factory, registered_rule):
"""Check request data that client uses to get a rule.
1. Create a subclass of the abstract client.
2. Implement send request so that it checks the request parameters.
3. Invoke the get_rule method.
4. Ch... | 62b8368072cebf0591137357167980a6d710a1f0 | 3,656,058 |
import colorsys
def summaryhsl(all_summaries, summary):
"""
Choose a color for the given system summary to distinguish it from other types of systems.
Returns hue, saturation, and luminance for the start of the range, and how much the hue can be randomly varied while staying distinguishable.
"""
... | 1e874aaa359a5d8bb566809fc2be212df2890885 | 3,656,059 |
def _get_cached_values(instance, translated_model, language_code, use_fallback=False):
"""
Fetch an cached field.
"""
if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
return None
key = get_translation_cache_key(translated_model, instance.pk, language_co... | e650eabbfde8b877519b9456dba9021dfa0f78e6 | 3,656,060 |
def tensor_index_by_list(data, list_index):
"""Tensor getitem by list of int and bool"""
data_shape = F.shape(data)
indexes_types = hyper_map(F.typeof, list_index)
if const_utils.judge_indexes_types(indexes_types, mstype.int_type + (mstype.bool_,)):
sub_tuple_index = const_utils.transform_sequen... | 99702ca58ebd7f316d83687804f09ac0639e3f17 | 3,656,061 |
def sample_ingridient(user, name='Salt'):
"""Create and return a sample ingridient"""
return Ingridient.objects.create(user=user, name=name) | 8904f11164a78959eb8073b80fa349155c1ae185 | 3,656,062 |
def remove_duplicates_from_list(params_list):
"""
Common function to remove duplicates from a list
Author: Chaitanya-vella.kumar@broadcom.com
:param params_list:
:return:
"""
if params_list:
return list(dict.fromkeys(params_list))
return list() | 885b2e048ec672bd2d24fabe25066bc2df3ea8a8 | 3,656,063 |
import os
import logging
import sys
def _exec_task(fn, task, d, quieterr):
"""Execute a BB 'task'
Execution of a task involves a bit more setup than executing a function,
running it with its own local metadata, and with some useful variables set.
"""
if not d.getVarFlag(task, 'task', False):
... | 064a217bdb967db5d15634864aa62fcd09068adf | 3,656,064 |
def mediaRecognitionApi():
"""
Retrieve the resource id, name, author
and time index of a sampled media.
"""
#TODO: Improve recognition
if 'file' not in request.files:
abort(400, "No file.")
file = request.files['file']
if file.filename == '':
abort(400, "No selected file")
if file and allowed_file(file.fi... | a4a4a6aaffe83f2d15f5ad32b826f135385c7ef3 | 3,656,065 |
from typing import Sequence
def _scale_and_shift(
x: chex.Array,
params: Sequence[chex.Array],
has_scale: bool,
has_shift: bool,
) -> chex.Array:
"""Example of a scale and shift function."""
if has_scale and has_shift:
scale, shift = params
return x * scale + shift
elif has_scale:
as... | 68c7128ff7c1788cd77e3737adff293f488e190e | 3,656,066 |
import math
def get_distance_metres(aLocation1, aLocation2):
"""
Returns the ground distance in metres between two LocationGlobal objects
:param aLocation1: starting location
:param aLocation2: ending location
:return:
"""
dlat = aLocation2.lat - aLocation1.lat
dlong = aLocation2.lon... | 5f1428c099f79ba8b41177f87e6a3bffed13e00b | 3,656,067 |
import scipy
def merge_components(a,c,corr_img_all_r,U,V,normalize_factor,num_list,patch_size,merge_corr_thr=0.6,merge_overlap_thr=0.6,plot_en=False):
""" want to merge components whose correlation images are highly overlapped,
and update a and c after merge with region constrain
Parameters:
---------... | e2e15c208ae71ba20cc84d8c0501485c04e41a90 | 3,656,068 |
def RenderSubpassStartInputAttachmentsVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartInputAttachmentsVector(builder, numElems) | 484ba9746f278cfcc7d50a282605ebc9a3a4fb2b | 3,656,069 |
def GetCLInfo(cl_info_str):
"""Gets CL's repo_name and revision."""
return cl_info_str.split('/') | d077216b2804c249a7d0ffdbff7f992dde106501 | 3,656,070 |
def acyclic_run(pipeline):
"""
@summary: 逆转反向边
@return:
"""
deformed_flows = {'{}.{}'.format(flow[PWE.source], flow[PWE.target]): flow_id
for flow_id, flow in pipeline[PWE.flows].items()}
reversed_flows = {}
while True:
no_circle = validate_graph_without_circle(... | 535edb2a7ccd1c0995fe46bff8a931175c353e51 | 3,656,071 |
def TextAreaFieldWidget(field, request): # pylint: disable=invalid-name
"""IFieldWidget factory for TextWidget."""
return FieldWidget(field, TextAreaWidget(request)) | 0d2431b1274e34978a6869efed0014982aaaa2e2 | 3,656,072 |
import os
def _cgroup_limit(cpu, memory_size, pid):
"""Modify 'cgroup' files to set resource limits.
Each pod(worker) will have cgroup folders on the host cgroup filesystem,
like '/sys/fs/cgroup/<resource_type>/kubepods/<qos_class>/pod<pod_id>/',
to limit memory and cpu resources that can be used in ... | 24d0ad0ea9afaa1b0d0c1de9114175014fe7666a | 3,656,073 |
def s_wexler(T_K):
"""
Calculates slope of saturation vapor pressure curve over water at each temperature
based on Wexler 1976, with coefficients from Hardy 1998 (ITS-90).
Args:
T_K (np.ndarray (dimension<=2), float, list of floats) : Air or Dewpoint Temperatures [K]
Returns:
s : n... | b27b713b6c609115fa36f458c7f72358c001fbd5 | 3,656,074 |
from importlib import import_module
def get_additional_bases():
"""
Looks for additional view bases in settings.REST_EASY_VIEW_BASES.
:return:
"""
resolved_bases = []
for base in getattr(settings, 'REST_EASY_VIEW_BASES', []):
mod, cls = base.rsplit('.', 1)
resolved_bases.append... | 485c2f0d4778399ff534f40e681706419c3c923a | 3,656,075 |
from pathlib import Path
import warnings
def load_mask_from_shp(shp_file: Path, metad: dict) -> np.ndarray:
"""
Load a mask containing geometries from a shapefile,
using a reference dataset
Parameters
----------
shp_file : str
shapefile containing a polygon
metad : dict
r... | fd8178919b2afec71f69a8a7a00e1b2f224d2509 | 3,656,076 |
def est_corner_plot(estimation, settings=None, show=True, save=None):
"""Wrapper to corner plot of `corner <https://corner.readthedocs.io/en/latest/>`_ module;
visualisation of the parameter posterior distribution by all 2-dimensional and
1-dimensional marginals.
Parameters
----------
estimatio... | 87f9eda0dc3bf61f66d4ee28f693dad4ef383f24 | 3,656,077 |
def voigt_peak_err(peak, A, dA, alphaD, dalphaD):
"""
Gives the error on the peak of the Voigt profile. \
It assumes no correlation between the parameters and that they are \
normally distributed.
:param peak: Peak of the Voigt profile.
:type peak: array
:param A: Area under the Voigt p... | 52d3fbb7fabe5dfe2e5ab67bcd498d5434f7afc7 | 3,656,078 |
import zipfile
import os
def zip_recursive(destination, source_dir, rootfiles):
"""
Recursively zips source_dir into destination.
rootfiles should contain a list of files in the top level directory that
are to be included. Any top level files not in rootfiles will be omitted
from the zip file.
... | 267dedb78495e02bbeb2ffaddcfe2278ab72be67 | 3,656,079 |
import typing
def discord_api_call(method: str, params: typing.Dict, func, data, token: str) -> typing.Any:
""" Calls Discord API. """
# This code is from my other repo -> https://gtihub.com/kirillzhosul/python-discord-token-grabber
# Calling.
return func(
f"https://discord.com/api/{method}"... | 84ea201c88dd4260bbc80dbd45654c01cb5a36ee | 3,656,080 |
import logging
def get_startup(config: Config) -> Startup:
"""Extracts and validates startup parameters from the application config
file for the active profile
"""
db_init_schema = config.extract_config_value(
('postgres', 'startup', 'init_schema'),
lambda x: x is not None and isinstan... | daa3809ed4f8be6c991796c8bbc11ee7b1434ee5 | 3,656,081 |
def new_request(request):
"""Implements view that allows users to create new requests"""
user = request.user
if user.user_type == 'ADM':
return redirect('/admin')
if request.method == "POST":
request_type = request.POST.get('requestType')
if request_type == 'SC' and user.user... | d90f72d5f299282709ed8a925569512a81d60591 | 3,656,082 |
def get_slice_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets):
"""
Args:
test_dataloader:
test_kwargs:
eval_kwargs (dict):
test_dataloader (Dataloader):
robustness_testing_datasets (dict):
Returns:
"""
slice_test = None
if '... | b995ff26fd743f106115c5d5958dd0654e0d4645 | 3,656,083 |
def transform_config(cfg, split_1='search:', split_2='known_papers:'):
"""Ugly function to make cfg.yml less ugly."""
before_search, after_search = cfg.split(split_1, 1)
search_default, papers_default = after_search.split(split_2, 1)
search, paper_comment = '', ''
for line in search_default.splitli... | 78d079b6b06c8426be2b65307782129c414a42c4 | 3,656,084 |
def filter_coords(raw_lasso, filter_mtx):
"""Filter the raw data corresponding to the new coordinates."""
filter_mtx_use = filter_mtx.copy()
filter_mtx_use["y"] = filter_mtx_use.index
lasso_data = pd.melt(filter_mtx_use, id_vars=["y"], value_name="MIDCounts")
lasso_data = lasso_data[lasso_data["MIDC... | fce1159db2a2bdb75acbe9b7ccb236af8bade627 | 3,656,085 |
def compute_threshold(predictions_list, dev_labels, f1=True):
"""
Determine the best threshold to use for classification.
Inputs:
predictions_list: prediction found by running the model
dev_labels: ground truth label to be compared with predictions_list
f1: True is using F1 score, F... | 230824c1454978cbe7c5f50ee43fba7b16754922 | 3,656,086 |
import torch
def color2position(C, min=None, max=None):
"""
Converts the input points set into colors
Parameters
----------
C : Tensor
the input color tensor
min : float (optional)
the minimum value for the points set. If None it will be set to -1 (default is None)
max : f... | 809d8cfd6f24e6abb6d65d5b576cc0b0ccbc3fdf | 3,656,087 |
def is_empty_parsed_graph(graph):
"""
Checks if graph parsed from web page only contains an "empty" statement, that was not embedded in page
namely (<subjectURI>, <http://www.w3.org/ns/md#item>, <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>)
:param graph: an rdflib.Graph
:return: True if graph co... | bf66271bc23f078669bc478a133b67c715fd8fdf | 3,656,088 |
def fillinNaN(var,neighbors):
"""
replacing masked area using interpolation
"""
for ii in range(var.shape[0]):
a = var[ii,:,:]
count = 0
while np.any(a.mask):
a_copy = a.copy()
for hor_shift,vert_shift in neighbors:
if not np.any(a.mask): break
a_shifted=np.roll(a_copy,shift=hor_shift,axi... | a8ffc34dac72cbd4ecdbbc9ad02270a457b0b8d9 | 3,656,089 |
from plistlib import loads, FMT_BINARY
from bplistlib import loads
def parse_plist_from_bytes(data):
"""
Convert a binary encoded plist to a dictionary.
:param data: plist data
:return: dictionary
"""
try:
return loads(data, fmt=FMT_BINARY)
except ImportError:
return loads(... | b9f96ef749af88bdb950d8f3f36b584f6766661d | 3,656,090 |
def projection_standardizer(emb):
"""Returns an affine transformation to translate an embedding to the centroid
of the given set of points."""
return Affine.translation(*(-emb.mean(axis=0)[:2])) | 65686636caeac72a16198ac6c7f603836eaedc53 | 3,656,091 |
def forward_imputation(X_features, X_time):
"""
Fill X_features missing values with values, which are the same as its last measurement.
:param X_features: time series features for all samples
:param X_time: times, when observations were measured
:return: X_features, filled with last measurements in... | ea0a41bfef02752338dc5384ce7fcd447c95f8c7 | 3,656,092 |
def calc_mlevel(ctxstr, cgmap, gtftree, pmtsize=1000):
"""
Compute the mean methylation level of promoter/gene/exon/intron/IGN in each gene
"""
inv_ctxs = {'X': 'CG', 'Y': 'CHG', 'Z': 'CHH'}
ign = defaultdict(list)
mtable = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))
counter... | 59b3a36e09e6ea0dd3608da0cf04f14f4d487182 | 3,656,093 |
def _get_service(plugin):
"""
Return a service (ie an instance of a plugin class).
:param plugin: any of: the name of a plugin entry point; a plugin class; an
instantiated plugin object.
:return: the service object
"""
if isinstance(plugin, basestring):
try:
(plugin... | a3433521b40861926d9ac3efa6a693d926a7fc94 | 3,656,094 |
def taiut1(tai1, tai2, dta):
"""
Wrapper for ERFA function ``eraTaiut1``.
Parameters
----------
tai1 : double array
tai2 : double array
dta : double array
Returns
-------
ut11 : double array
ut12 : double array
Notes
-----
The ERFA documentation is below.
... | c7f9490a5af86de98c89af37cb6ca1bcb92d107a | 3,656,095 |
from SPARQLWrapper import SPARQLWrapper, JSON
def fetch_ppn(ppn):
"""
"""
ENDPOINT_URL = 'http://openvirtuoso.kbresearch.nl/sparql'
sparql = SPARQLWrapper(ENDPOINT_URL)
sqlquery = """
SELECT ?collatie WHERE {{
kbc:{ppn} dcterms:extent ?formaat, ?collatie .
FILTER (?forma... | fd974eccc7f4c099320c50a20b678d36cea7b899 | 3,656,096 |
def prepare_link_title(
item: feedparser.FeedParserDict) -> feedparser.FeedParserDict:
"""
Для RSS Item возвращает ссылку, заголовок и описание
:param item:
:return:
"""
result = None
if item:
assert item.title, 'Not found title in item'
assert item.link, 'Not found link ... | 445eccd9855484b65b726a4ee12a3dfa9a9de375 | 3,656,097 |
def api_docs_redirect():
""" Redirect to API docs """
return redirect('/api/v1', code=302) | d7ed10aa264d1403325f0b044b4c7b8b20b5989f | 3,656,098 |
from typing import List
def print_topics(model, vectorizer, top_n: int=10)-> List:
"""Print the top n words found by each topic model.
Args:
model: Sklearn LatentDirichletAllocation model
vectorizer: sklearn CountVectorizer
top_n (int): Number of words you wish to return
... | c0477c19c6806c2eaacb4165d332291dc0ba341b | 3,656,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.