content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def read_data(f_name):
"""
Given an input file name f_name, reads the JSON data inside returns as
Python data object.
"""
f = open(f_name, 'r')
json_data = json.loads(f.read())
f.close()
return json_data | 629ab7e9a8bd7d5b311022af4c9900d5942e7a23 | 51,000 |
def load_df(df_path):
"""
Parameters
---
df_path: string
absolute path to where a pandas DataFrame generated by the match_to_GLEAM function
has been generated
Returns
---
table: DataFrame
the loaded pandas DataFrame
"""
table = pd.read_pickle(df_p... | 8971254f7a74b04fd6cd7aaa25f033fd35026e59 | 51,001 |
def user(db):
"""A user for the tests."""
user = UserFactory(password='myPrecious')
db.session.commit()
return user | 3e8ddc1184c700f5544e482da315b4e36a11edce | 51,002 |
def logistic(x, x0=0, L=1, k=1):
""" Calculate the value of a logistic function.
# Arguments
x0: The x-value of the sigmoid's midpoint.
L: The curve's maximum value.
k: The logistic growth rate or steepness of the curve.
# References https://en.wikipedia.org/wiki/Logistic_function
... | 48d667dd6402435d20813fd4ceba7b5193ec9935 | 51,003 |
def reverse_string_recursive(s):
"""
Returns the reverse of the input string
Time complexity: O(n^2) = O(n) slice * O(n) recursive call stack
Space complexity: O(n)
"""
if len(s) < 2:
return s
# String slicing is O(n) operation
return reverse_string_recursive(s[1:]) + s[0] | a8d22e88b1506c56693aa1a8cd346695e2b160b2 | 51,004 |
def checkIsHours(value):
"""
checkIsHours tries to distinguish if the value describes hours or degrees
:param value: string
:return:
"""
if not isinstance(value, str):
return False
if '*' in value:
return False
elif '+' in value:
return False
elif '-' in va... | 4d28996de6087b802757508313e15543b9dd9272 | 51,005 |
from typing import Optional
import os
import json
import logging
import re
def _map_las_file_to_metadata(file_directory: str, file_name: str) -> Optional[str]:
"""Performs mapping of las plot level file to associated JSON metadata file
Arguments:
file_directory: the directory of the file
file_... | 45a5df6b02086e9bcda855ef8ceef927a1114249 | 51,006 |
def gnome_sort(a):
"""
Sorts the list 'a' using gnome sort
>>> from pydsa import gnome_sort
>>> a = [5, 6, 1, 9, 3]
>>> gnome_sort(a)
[1, 3, 5, 6, 9]
"""
i = 0
while i < len(a):
if i != 0 and a[i] < a[i-1]:
a[i], a[i-1] = a[i-1], a[i]
i -= 1
el... | 05aca54513c6d441836aa7a60147b06b85b4e34d | 51,007 |
def get_choices_roles():
"""
Restituisce i ruoli utente (Admin/Operator)
:return:
"""
try:
return [(i.role, i.role) for i in agency.models.Role.objects.all().order_by('role')]
except:
return [] | 1212de6a8ae55a74a58eca3c79d4722f2c8ab043 | 51,008 |
def get_boxscore_from_game_id(
cz_game_id : str
,**request_kwargs
)->defaultdict:
"""Returns a curling boxscore (dict) based on the cz_game_id."""
url = 'https://www.curlingzone.com/game.php?1=1&showgameid=%s#1'%cz_game_id
soup = make_soup(url=url,**request_kwargs)
return _get_boxscore_from_g... | c2cdbd762ee2227b52294a3235e2f1a513d6e9a8 | 51,009 |
def lpf_smooth(s3d, a, b):
"""
:param s3d: K x J x 3
:param a: [5,]
:param b: [5,]
:return:
"""
lpf_num = len(a)
s3d_y_ = [s3d[0].copy() for _ in range(lpf_num - 1)]
s3d_x_ = np.pad(s3d, ((lpf_num - 1, 0), (0, 0), (0, 0)), 'edge')
for i, s3d1f in enumerate(s3d_x_):
if i ... | 96debc682c2b31c48b0e8b99c9545c03768197fd | 51,010 |
def STOK(df):
"""
Stochastic oscillator %K
"""
result = pd.Series((df['Close'] - df['Low']) / (df['High'] - df['Low']), name='SO%k')
return out(SETTINGS, df, result) | d503f6ffd747bb40a20329c6f016c5e3185e81f2 | 51,011 |
def scaleLongSide(ip, longSide):
""" Scale the image with respect to the longSide parameter (new size along the long side of the image should equal the longSide parameter) """
w = ip.width
h = ip.height
l = max(w,h)
s = float(longSide)/l
imp = ImagePlus('scaleLongSide',ip)
IJ.run(imp, "Scale...", "x="+str(s)+" y... | 59e217f9ace99ff13ed71bf4d5d242a97b1a8240 | 51,012 |
import joblib
def load_pipeline(*, file_name: str) -> Pipeline:
"""Load a persisted pipeline."""
file_path = TRAINED_MODEL_DIR / file_name
trained_model = joblib.load(filename=file_path)
return trained_model | 41cb259a03b0cbc4836f472bbbe0211ed0d03cd5 | 51,013 |
import logging
def WIFI(frame, no_rtap=False):
"""calls wifi packet discriminator and constructor.
:frame: ctypes.Structure
:no_rtap: Bool
:return: packet object in success
:return: int
-1 on known error
:return: int
-2 on unknown error
"""
pack = None
try:
... | 7a19774675cb251a156063ed4d1aeb70d9429430 | 51,014 |
from typing import Set
from typing import Dict
import os
def get_files_being_copied(directories: Set[str]) -> Dict[str, DiskCopyInfo]:
"""Get all the files which are not accessible for write (i.e. being copied)
Parameters
----------
directories : Set[str]
Directories where to search for files... | 07c95ea452d8f36bd173a96b7c2d9a4f6933a564 | 51,015 |
import time
def time_elapsed(func):
"""
记录函数运行耗时的生成器
:param func:
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
timestamp = time.time() * 1000
ret = func(*args, **kwargs)
now_ts = time.time() * 1000
elapsed = now_ts - timestamp
print('%s c... | f83976cdc8a830aba6f24dbd34b33d0f30fc9718 | 51,016 |
import logging
import os
def _get_params(args, opts):
"""
Get params from conffile
"""
logger = logging.getLogger('fms')
simconffile = _get_simconffile(args)
if os.path.splitext(simconffile)[-1] == '.xml':
logger.debug("Calling XmlParamsParser on %s" % simconffile)
params = Xml... | dbed593f07abdc51df4a8a8b63ef36fe5bd34ac8 | 51,017 |
def Weight(*args):
"""Weighting factor for this Sensor measurement with respect to other Sensors. Default is 1."""
# Getter
if len(args) == 0:
return lib.Sensors_Get_Weight()
# Setter
Value, = args
lib.Sensors_Set_Weight(Value) | 27129adee521053645364a2bdb6fe4681673697f | 51,018 |
def load_from_arff(filename, labelcount, endian="big",
input_feature_type='float', encode_nominal=True, load_sparse=False,
return_attribute_definitions=False):
"""Method for loading ARFF files as numpy array
Parameters
----------
filename : str
path to ARFF file
labelcount: integer
... | 84bb27d193246eadec2cb9ec4ab61151570bd6b0 | 51,019 |
from typing import Callable
from typing import Mapping
from typing import List
def hashimoto(dataset_lookup: Callable[[uint32_hash_array, int], uint32_hash]) -> Callable[[bytearray, bytearray, int, uint32_hash_array], Mapping[str, bytes]]:
""" Decorator function. Returns the hashimoto algorithm.
Args:
... | 6cdad8a0552a99399bf32356af6f44c5005ed703 | 51,020 |
def run_in_thread_pool (*, callbacks = (), callbacks_kwargs = ()):
"""将函数放入线程池执行的装饰器"""
def decorator (func):
@wraps(func)
def wrapper (*args, **kwargs):
future = EXECUTOR.submit(func, *args, **kwargs)
for index, callback in enumerate(callbacks):
try:
... | 311990156f275eb6932c921bc8fade3ea1413ec8 | 51,021 |
def evaluate_position(board, colour, legal_moves):
""" Evaluation function for chess game """
white = chess.WHITE
black = chess.BLACK
pieces = {}
# Counting pieces depeneding on colour
wking = bin(board.occupied_co[white] & board.kings).count('1')
wqueen = bin(board.occupied_co[white] & boar... | 1b0dd2347a95a5c9f923d8d1950cf441e37adab0 | 51,022 |
def rotate_point_cloud_and_gt(batch_data,batch_gt=None):
""" Randomly rotate the point clouds to augument the dataset
rotation is per shape based along up direction
Input:
BxNx3 array, original batch of point clouds
Return:
BxNx3 array, rotated batch of point clouds
"... | 3f076281d14992a6c3651d3b80be8c205e1b9aae | 51,023 |
def signal_resample(
ser_raw:pd.Series,
resample_method:str='linear',
resample_timestep:str='100ms'
) -> pd.Series:
"""
Resample the data and fill the values following 3 methods:
* linear will apply:
* linear interpolation when 1 point is missing
* Akima interpolation when more p... | 7c408cd7e169c24f38b062786dee09ea41fc3e05 | 51,024 |
def client_script():
""" Reads qtwebchannel.js from disk and creates QWebEngineScript to inject to QT window.
This allows for JavaScript code to call python methods marked by pyqtSlot in registered objects.
Args:
None.
Returns:
None.
Raises:
"""
qwebchannel_js = QFile(... | c2627e9a95caa2b5faf183a98d50bca643e7f5bd | 51,025 |
from functools import reduce
def thread_first(val, *forms):
""" Thread value through a sequence of functions/forms
>>> def double(x): return 2*x
>>> def inc(x): return x + 1
>>> thread_first(1, inc, double)
4
If the function expects more than one input you can specify those inputs
in ... | 80b500b80233ac17e41d809a4ffcf24a0173c63b | 51,026 |
from typing import List
def _get_parent_object(obj: dict, dotted_path: List[str]):
"""
Given a nested dictionary, return the object denoted by the dotted path (if any).
In particular if dotted_path = [], it returns the same object.
:param obj: the dictionary.
:param dotted_path: the path to the ... | 328a2baaab22b28b1f061609ff2720d461cdf3be | 51,027 |
import re
def vm_info(name):
"""
Wrapper around VBoxManage showvminfo
Return all the information about an existing VM
:param name: str
:return: dict[str,str]
"""
try:
INFO_PARSER = re.compile(
r'^("(?P<quoted_key>[^"]+)"|(?P<key>[^=]+))=(?P<value>.*)$')
info = {... | 6b4e08af12420a305f6928dc133220658125f5cf | 51,028 |
import subprocess
import sys
def shell(*args, **kwargs):
""" A really roundabout way to issue a system call """
sys.stdout.flush()
# Parse the keyword arguments
verbose = kwargs.get('verbose', False)
detatch = kwargs.get('detatch', False)
shell = kwargs.get('shell', True)
# Print what yo... | 8d18d9abf39ac88a36aeb9c16c986fc32375e4d5 | 51,029 |
def fmod(x, y):
"""Return fmod(x, y), as defined by the platform C library.
:type x: numbers.Real
:type y: numbers.Real
:rtype: float
"""
return 0.0 | cd580ca8efe1e9bd3e5511613ccdcc59ebe55119 | 51,030 |
from typing import OrderedDict
def load_observation(db, obs_id, dets=None, prefix=None):
"""Load the data for some observation. You can restrict to only some
detectors. Coming soon: also restrict by time range / sample
index.
This specifically targets the pipe-s0001 sim format.
Arguments:
... | d6e48317f2bc876afe15a169eadd570fc980d394 | 51,031 |
import os
import pickle
def read_mrk(fname):
"""Marker Point Extraction in MEG space directly from sqd
Parameters
----------
fname : str
Absolute path to Marker file.
File formats allowed: *.sqd, *.mrk, *.txt, *.pickled
Returns
-------
mrk_points : numpy.array, shape = (n... | a1a92cb1bfdab60607842f36762e1d824de772f4 | 51,032 |
import os
def ModelFileName(suffix):
"""Location of filename `Description()`_`suffix` in `dataset_dir/dumps`."""
return os.path.join(dataset_dir, 'dumps',
'%s_%s' % (Description(), suffix)) | df241dc662357deb9c957d07cf6bad4a4fae87d2 | 51,033 |
def get_tickers(fiat="ALL"):
"""
마켓 코드 조회 (업비트에서 거래 가능한 마켓 목록 조회)
:return:
"""
try:
url = "https://api.upbit.com/v1/market/all"
contents = _call_public_api(url)[0]
if isinstance(contents, list):
markets = [x['market'] for x in contents]
if fiat == "K... | 955831b785246a97547519c61276bd466f0835f4 | 51,034 |
def EulerFluxX(u):
"""Calculate the x-direction Euler flux from a solultion vector"""
dens = u.dens()
momX, momY, momZ = u.momX(), u.momY(), u.momZ()
en = u.energy()
pressure = u.pressure()
x_flux = np.array(
[
momX,
momX * momX / dens + pressure,
momX... | f38cabfe0524ac74fd08c57eff6c2ebd3c8901b0 | 51,035 |
def error_handler(fun):
"""
Assert异常装饰器,用来方便的进行断言式接口开发
"""
def wrapper_fun(*args, **kwargs):
try:
return fun(*args, **kwargs)
except AssertionError as e:
return e.args[0]
except Exception as e:
return create_resp(code=8000, data=[], message=str... | df4a8c65c3c47eef252463a273698ab743c24ac9 | 51,036 |
def notfound(e):
"""404 template"""
return render_template('404.html'), 404 | ceb28334d35490d9af39fdb3a9100e9ff3c262d8 | 51,037 |
def read_pipes():
# type: () -> str
""" Call to read_pipes.
:return: The command read from the pipe
"""
o = _COMPSs.read_pipes() # noqa
return o | 412d738dee3a45d9c1770345f9ad56eebefc5554 | 51,038 |
from bs4 import BeautifulSoup
async def get_relic_info(relic_name):
"""
Gets relic information and caches it, if not already cached.
Also helps mantain a parts list.
"""
logger.info("Fetching relic info for %s." % relic_name)
relic_infos = utils.get_json('relic_info')
if relic_name in r... | 0d2046b915f2dc8debfcd34f23d952f66ea9f505 | 51,039 |
def manchester_vermont_observed(
awhere_api_key,
awhere_api_secret,
manchester_vermont_longitude,
manchester_vermont_latitude,
):
"""Fixture that returns a geodataframe for the observed weather
for Manchester, Vermont.
"""
# Define kwargs for Manchester, Vermont
vt_kwargs = {
... | 50ca693e86f151a08c897f5ebc2517e4c1ab09c9 | 51,040 |
def get_rv_xmatch(ra, dec, G_mag=None, dr2_sourceid=None):
"""
Given a single RA, dec, and optionally Gaia G mag, and DR2 sourceid, xmatch
against spectroscopic catalogs to try and mine out an RV and error.
Returns tuple of:
(rv, rv_err, provenance)
Presumably all RVs returned are helio... | 3239caa15b2444e080da2c3830570b7b4b7eb7e8 | 51,041 |
import time
import string
from datetime import datetime
def increment_name(mjd, lastname=None, suffixlength=4):
""" Use mjd to create unique name for event.
"""
dt = time.Time(mjd, format='mjd', scale='utc').to_datetime()
if lastname is None: # generate new name for this yymmdd
suffix = stri... | 3028fa8983f56f39d3ed75877cda32aad51be3d7 | 51,042 |
from tasks.models import Task
def get_fields_for_annotation(prepare_params):
""" Collecting field names to annotate them
:param prepare_params: structure with filters and ordering
:return: list of field names
"""
result = []
# collect fields from ordering
if prepare_params.ordering:
... | c99ef78678c3fe004eab46efb5977211918efcbf | 51,043 |
def topic_meta(topic, precinctNum):
"""
Return meta data about each precinct's election result
output:
{
"percentTurnout": num,
"registeredVoters": num,
"totalVotes": num
},
"""
if precinctNum != 'all':
return j... | 1f63ff299ee9ad722295f2d764bffccccdc044d7 | 51,044 |
def check_for_previewimage(czi):
"""Check if the CZI contains an image from a prescan camera
:param czi: CZI imagefile object
:type metadata: CziFile object
:return: has_attimage - Boolean if CZI image contains prescan image
:rtype: bool
"""
att = []
# loop over the attachments
fo... | 8ea3b89e0cbf798d13054f0b418589820e1a6106 | 51,045 |
from typing import Union
from typing import Iterable
def check_spec(spec: Union[str, Iterable[str]]) -> bool:
"""Checks the spec against the hard constraints.
Internally, Draco checks against the definitions, constraints, helpers,
and hard constraints.
:param spec: The specification to check
"""... | f21feb2ff4af0df098858bad5e0c8d24e4b9ca54 | 51,046 |
def num_associated_keyword(keyword, input_rel, relation, quantified=False, keyword2=None):
"""
Finds the number of associated elements for a given keyword.
Optionally a second keyword can be passed, in which case the number of elements that are associated with BOTH
keywords is returned.
:param keyw... | 86ba097863a97d406b6173daf03f645f7dd4c2e1 | 51,047 |
def get_closest_multiple_of_16(num):
"""
Compute the nearest multiple of 16. Needed because pulse enabled devices require
durations which are multiples of 16 samples.
"""
return int(num) - (int(num) % 16) | 333cbed27abbcb576541d5fb0b44bf85b78c9e78 | 51,048 |
def _convert_line_to_task(line: str) -> Task:
"""
Convert a line record to a task instance.
Args:
line A record line from the storage file
Return
A task instance
"""
id, message, time, project, category, links, started_at, finished_at = line.strip().split(sep)
return ... | 23986ef4d22006aca8a8e3148cfa888be79a6089 | 51,049 |
def TransformListFactory(name: str, transforms: tp.Sequence[Transform]):
"""Create a new TransformationList subclss with the given name that performs
the specified transforms."""
return TransformListMetaclass(name, (TransformationList,), {},
transforms=transforms) | bc19ef5fecb17f30057787cab66d3f67e0e4df1e | 51,050 |
from typing import List
from typing import Tuple
def max_subarray(arr: List[int]) -> Tuple[int, int]:
"""
:time: O(n)
:space: O(n)
"""
max_val = max(x for x in arr)
if max_val < 0:
return max_val, max_val
max_subsequence_sum = sum(x for x in arr if x > 0)
max_subarray_sum = 0
... | 056b4c83191f57a36f0fdeb7474b2de2f6e8bb28 | 51,051 |
import json
def receive_redcap_det(*, session):
"""
Receive REDCap data entry triggers.
"""
document = request.form.to_dict()
LOG.debug(f"Received REDCap data entry trigger")
datastore.store_redcap_det(session, json.dumps(document))
return "", 204 | 4a3ec3354faf11d6f38918bf196e2db161177848 | 51,052 |
import os
def distribute_statistics(immutability, source_path, packaging_path, parms, user, group):
"""
Determines if the distribution method is set to local or remote
and calls the correct distribution method.
Args:
immutability (bool): If True, change the file attributes for immutability.
... | 1f24af76770bb3f9313062f171180f911b6818d5 | 51,053 |
def AND_columns_with_NANFLAGs(
df: pd.DataFrame, nan_val: int = 1, NANFLAG=-1
) -> pd.Series:
"""see :func:`apply_bool_op_on_columns_with_NANFLAGs()`"""
return apply_bool_op_on_columns_with_NANFLAGs(
df, pd.Series.__and__, nan_val, NANFLAG
) | a0c76a07828d40857026832c4d56965800d8435f | 51,054 |
def split_container(path):
"""Split path container & path
>>> split_container('/bigdata/path/to/file')
['bigdata', 'path/to/file']
"""
path = str(path) # Might be pathlib.Path
if not path:
raise ValueError('empty path')
if path == '/':
return '', ''
if path[0] == '/':
... | 53b0d1164ecc245146e811a97017f66bb1f032a7 | 51,055 |
def load_data_dict(data_config):
"""
Load mapping information (dictionary) between raw data files to table names in the
database.
Parameters
----------
data_config : str
Path of the config file that stores data dictionaries in yaml.
This file should contains two dictionaries, on... | 70e242bf59916abe14fb63791ef5312baa2e9e73 | 51,056 |
import yaml
from typing import Any
from typing import List
from typing import Dict
from typing import Iterable
import os
import json
async def _run_clang_tidy(
options: Any, line_filters: List[Dict[str, Any]], files: Iterable[str]
) -> CommandResult:
"""Executes the actual clang-tidy command in the shell."""
... | 1ee31a0e63665186e4632f7d8068b29eba42b198 | 51,057 |
def alias_tuples_from_dict(aliases_dict):
"""
Convert from aliases dict we use in items, to a list of alias tuples.
The providers need the tuples list, which look like this:
[(doi, 10.123), (doi, 10.345), (pmid, 1234567)]
"""
alias_tuples = []
for ns, ids in aliases_dict.iteritems():
... | 3f35cf368c3e7bea8a309177c70013f3125f5220 | 51,058 |
import aiohttp
import json
async def response_to_dict(response: aiohttp.ClientResponse) -> CensusData:
"""Convert a response received from the server to a dictionary.
In some cases - mostly error states - the API will return JSON data
without providing the appropriate ``Content-Type`` entity header,
... | 5619c1364fe439e717774ba6642b42d76acec2eb | 51,059 |
from typing import Optional
from typing import List
def partial_trace(
density_matrix: np.ndarray,
targets: Optional[List[int]] = None,
) -> np.ndarray:
"""Returns the reduced density matrix for the target qubits.
If no target qubits are supplied, this method returns the trace of the density matrix.
... | e7b192fd56e5ef72e765b51638331b83c884bde8 | 51,060 |
def lazy_pinyin(hans, style=Style.NORMAL, errors='default'):
"""不包含多音字的拼音列表.
与 gupinyin.pinyin 的区别是返回的拼音是个字符串,
并且每个字只包含一个读音.
:param hans: 汉字
:type hans: unicode or list
:param style: 指定拼音风格,默认是 gupinyin.Style.NORMAL 风格。
更多拼音风格详见 gupinyin.Style。
:param errors: 指定如何处理没有拼音的字符,... | 477c5104ac2b29ddb9845992c505b1c0543754cd | 51,061 |
def energy_degeneracy(N, m):
"""Calculate the number of Dicke states with same energy.
The use of the `Decimals` class allows to explore N > 1000,
unlike the built-in function `scipy.special.binom`
Parameters
----------
N: int
The number of two-level systems.
m: float
Tota... | 46d41f1e3f13a49490c306237bef4e6279004f96 | 51,062 |
def sigmoid(x):
"""Implementation of the sigmoid (logistic) function.
:param x: Function parameter.
:type x: int or float
"""
return 1 / (1 + np.exp(-x)) | 01aab97de3b3eb4c368c6433c541f4b36340ad1d | 51,063 |
def list_entities() -> (str, int):
"""
Точка входа для запроса на получение записи пользователя по id. Пример запроса:
curl http://localhost:80/users
:return: если база не пуста, то возвращает json с данными пользователей и код 200,
иначе возвращает код 404
Формат возвращаемого... | 6eadaedaa8a1b7a1c4bb8416aca67e1a39463304 | 51,064 |
def map_intervals(ref_itv, other_itv, gap_chars={"-", "."}):
"""
Map intervals of representative sequences on its aligned version
Report contracted intervals that need to backpropagate in the other alignments at this level
"""
# extend contracted intervals
contracted = other_itv.length < ref_itv... | 6cabda95779cf8d1fadb6843307ace90bae08050 | 51,065 |
def convert_ros2_time_to_float(time_tuple):
"""
Converts time from tuple (ROS2) format to floating point number
"""
return float(time_tuple[0] + time_tuple[1]/TIME_CONVERSION_CONST_) | dd552feab86741380c63fb87993269d181cecc39 | 51,066 |
import concurrent
def csv_render(domain):
"""Render and return the csv-formatted report."""
headers = ('Domain', 'Type', 'Tweak', 'IP', 'Error')
csv_filename = 'dnstwister_report_{}.csv'.format(domain.to_ascii())
def local_resolve_candidate(candidate):
domain = Domain(candidate['domain-name']... | 7fceadab2420d522c3b1e755c2bc330689e2e6f5 | 51,067 |
def center(x, y, width, height):
"""
info: gets the center x, y
:param x: int
:param y: int
:param width: int: 0 - inf
:param height: int: 0 - inf
:return: (int, int)
"""
return _get_center(x, width), _get_center(y, height) | faa0e1492bd2da2b87338d256b35e3021bd012fb | 51,068 |
def get_prettyhandles_image(rankings):
"""return PIL image for rankings"""
SMOKE_WHITE = (250, 250, 250)
BLACK = (0, 0, 0)
img = Image.new("RGB", (900, 450), color=SMOKE_WHITE)
font = ImageFont.truetype("tle/assets/fonts/Cousine-Regular.ttf", size=30)
draw = ImageDraw.Draw(img)
x = 20
y... | 6e00a619c7f968c96d26b445ede1f3a7394e86d4 | 51,069 |
def extract_cnn_features(net, mean, img, layer, blob = None):
""" Extracts image features from a CNN using Caffe.
net - caffe.Net instance
mean - A numpy array with the mean values for each channel.
Channels must be in BGR order and the scale of values is assumed to be [0,255].
... | 9599cf7fa7098f65b4f76570a5a7a84147df7038 | 51,070 |
from pyspark.sql import SQLContext
from pyspark.sql import SparkSession
def get_or_create_sc(type="sparkContext", name="CerebralCortex-Kernal", enable_spark_ui=False):
"""
get or create spark context
Args:
type (str): type (sparkContext, SparkSessionBuilder, sparkSession, sqlContext). (default="s... | 05ed6be4b37678e54009d8f1e67d37c0e770cdda | 51,071 |
def welchs_test_arrays(x1, x2):
"""
A spearate implementation that automatically calculates means, variances and the number of samples from the input lists of values.
Not currently used in the code because the number of samples is calculated earlier, when the estimators were combined.
It is kept as a s... | 4f7ff1cd0e12772e83c1caf66df5daa021225987 | 51,072 |
def extrapolate_nsigma(ref_mag, SNR, nsigma=5):
"""
Fit a parabola to log10(SNR) vs ref_mag and
extrapolate/interpolate to find the n-sigma magnitude limit.
"""
log10_SNR = np.log10(SNR)
index = np.where(log10_SNR == log10_SNR)
pars = np.polyfit(log10_SNR[index], ref_mag[index], 2)
mag =... | 3ac3b647565ce46ab8abc3dd089cea928c27e937 | 51,073 |
def extract_valid_voxels(gdf: gpd.GeoDataFrame):
"""
Given a GeoDataFrame gdf containing data from one source team,
with columns "dst_ip", "geometry",
process the Shapely objects contained in
"geometry" and store only the voxels that have not been invalidated
over their relevant time frames.
... | e529dfd7ad325dea4ba68e1c1236aef37d74f8e1 | 51,074 |
import warnings
def apply_holms_test(imbalanced_experiment, control_oversampler=None):
"""Use the Holm's method to adjust the p-values of a paired difference
t-test for every combination of classifiers and metrics using a control
oversampler.
Parameters
----------
imbalanced_experiment : obje... | 04c1e6541bbeb0bec037bd7f2c010ac1cc9faf03 | 51,075 |
def read_gmt(filepath,
gene_sets=(),
drop_description=True,
save_clean=False,
collapse=False):
"""
Read GMT.
:param filepath: str; filepath to a .gmt compress
:param gene_sets: iterable: list of gene set names to keep
:param drop_description: bool;... | 7000fd7ba36fcc14be4d83b57b39a86580e21604 | 51,076 |
from nebula_website.views.db_stat import DPS_write_fn
def test_DPS_write_fn(tmpdir):
"""
1. max line 65536
"""
def count_line(fn):
c = 0
with open(fn, 'r') as f:
for _ in f:
c += 1
return c
# 写入65534 + 1 行
# 实际也有 65535行
valid_count = 6553... | d26900bb2611a41bc276554d95dcc70d4972c5dd | 51,077 |
def get_email_from_token(token, salt, secret, max_age=86400):
"""
Read an email from a timestamped token.
Raises an exception if the token is more than 24 hours old or invalid
"""
ts = URLSafeTimedSerializer(secret)
email = ts.loads(token, salt=salt, max_age=max_age)
return email | a568a80f7843baa6067f21180cc967e5194eeb52 | 51,078 |
def template_match(source_image, template_image, region_center, option=0):
""" template match
@param source_image: np.array(input source image)
@param template_image: np.array(input template image)
@param region_center: list(if not None, it means source_image is
part of origin target image, ot... | 3e620eba2ab83e40e83bb97c833b4c6c3baa5ae9 | 51,079 |
def months_in_prison(popu):
"""Return array of months in prison for each person in population."""
return np.array([person["months_in_prison"] for person in popu.values()]) | bc4b92aa09e9c08f6ce2308f75862d575086b821 | 51,080 |
def elementary(deriv_func):
"""Decorator to create an elementary operation
This takes as an argument a function that calculates the derivative of the function
the user is calculating. When the decorated function is called, `@elementary` also calls
`deriv_func` and stores both the value and derivative i... | 38ccc3889471c0880bc802cef535f45dbfd0a92d | 51,081 |
def _singularize_copa_examples(dataset):
"""Converts COPA multi-choice examples to batch of single-answer examples."""
indexes = []
premises = []
questions = []
choices = []
labels = []
for example in dataset:
for choice in ["choice1", "choice2"]:
indexes.append(example["idx"])
premises.a... | 1f680e0366b296a040e3450f00975c499d81672c | 51,082 |
def test_skewt_shade_cape_cin(test_profile):
"""Test shading CAPE and CIN on a SkewT plot."""
p, t, tp = test_profile
with matplotlib.rc_context({'axes.autolimit_mode': 'data'}):
fig = plt.figure(figsize=(9, 9))
skew = SkewT(fig, aspect='auto')
skew.plot(p, t, 'r')
skew.plot... | 035194fe3dbd049a40c1cc5e94980b0d3b0c1089 | 51,083 |
import os
def configure_code_run(batch):
"""
This function tells stroopwafel what program to run, along with its arguments.
IN:
batch(dict): This is a dictionary which stores some information about one of the runs. It has an number key which stores the unique id of the run
It also has ... | a73564aba194d91bf326dbab6f11d42d041a3eef | 51,084 |
def get_client() -> RabbitmqClient:
"""Returns a RabbitmqClient instance."""
# Replace the parameters with proper values for host, port, login and password
# Change the value of exchange if needed.
#
# For any parameter that is not given here, the client tries to use a value from an environment vari... | 7aebab2405234f779f5b9a06e366ec6539fc8847 | 51,085 |
def get_animal_ids(id=None):
"""
Return the distinct animal ids
:param id : id of the specific dataset
"""
if id is None:
return jsonify({})
animal_ids = db.session.query(Movement_data.animal_id).filter_by(dataset_id=id).distinct(Movement_data.animal_id)
result = []
for ... | 07d279b79ea52b2cda236de7c6ff3b72ad90417f | 51,086 |
def find_actors(hg, edge):
"""Returns set of all coreferences to actors found in the edge."""
actors = set()
if is_actor(hg, edge):
actors.add(main_coref(hg, edge))
if not edge.is_atom():
for item in edge:
actors |= find_actors(hg, item)
return actors | ba2c44de426619f21eceab1a3e39b9ea78161200 | 51,087 |
def rate_project(request, project_id):
"""
rate_project view function to process the user input rating information
based on usability,content and design and return an average
rating which will be stored in the database
"""
current_user=request.user
# get project to be rated from the DB
... | 049acdfd25e66970e24e82c2dc068d8d9b01a6d7 | 51,088 |
import fsspec
def load_era5(
var, lat, lon, time,
reduce_func=None,
resample="1D",
):
"""
Download and return an ERA5 variable for a defined time window.
Parameters
----------
var : string
Name of the ERA5 climate variable to download, e.g "air_temperature_at_2_metres"
la... | 79c79412bac5baafcb1442e730ac7a992dca8f83 | 51,089 |
import copy
def stack_to_queue(stack):
"""
Convert queue to a stack
"""
input_stack = copy.deepcopy(stack)
output_queue = ArrayQueue()
while True:
try:
output_queue.add(input_stack.pop())
except KeyError:
break
return output_queue | 839a94ce94f8e28d39d2c1df0c11673a0a378826 | 51,090 |
def sigma(S,T,P=0. | units.dbar):
""" Density anomaly """
_S=S.value_in(units.psu)
_T=T.value_in(units.Celsius)
_P=P.value_in(units.dbar)
return _seawater.sigma(_S,_T,_P) | units.kg/units.m**3 | 3d5a62ba17abc62ec5037f78efa767301b1decf4 | 51,091 |
import os
def get_dir_list_recurse(basepath, itempath="", parent=None):
"""Walk directory tree for get_dir_list."""
total = []
if not basepath.endswith("/"):
basepath = basepath + "/"
if itempath and not itempath.endswith("/"):
itempath = itempath + "/"
items = os.listdir(basepath ... | ffabd0aa2bdc20363c5d599adbbb76b6a1ab9aa8 | 51,092 |
import torch
def laplacian_positional_encoding(g, pos_enc_dim):
"""
Graph positional encoding v/ Laplacian eigenvectors
"""
# Laplacian
A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float)
N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float)
L = s... | 644ae9c397e2e78d073b5f0edc04777e71a128e3 | 51,093 |
def create_2d_gaussian(dim, sigma):
"""
Source: https://github.com/vsvinayak/mnist-helper/blob/master/mnist_helpers.py
This function creates a 2d gaussian kernel with the standard deviation
denoted by sigma
:param dim: integer denoting a side (1-d) of gaussian kernel
:type dim: int
:param s... | 8b6ed5ce4621503c9624f4571e05c0357351e5db | 51,094 |
import io
import pkgutil
def get_embedding(path):
"""
Get the dataset of ingredients as a dictionary.
:return: a dictionary representing the embedding
"""
embedding_io = io.BytesIO(pkgutil.get_data(__name__, path))
return np.load(embedding_io, allow_pickle=True).item() | 22fe9b285cf64cdac83192574cd631a9dd79b59f | 51,095 |
import pickle
def get_challenges_for_user_id(database, user_id, ctf_channel_id):
"""
Fetch a list of all challenges a user is working on for a given CTF.
Return a list of matching Challenge objects.
This should technically only return 0 or 1 challenge, as a user
can only work on 1 challenge at a t... | acc2bfb7277040c0051f43931915794732371aac | 51,096 |
def allowed_file(filename):
""" allowed formats to be uploaded for mcdss """
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | 46d5f76264f57d4786fe4849ca992cf9fe3c8b6f | 51,097 |
def parse_sph_header( fh ):
"""Read the file-format header for an sph file
The SPH header-file is exactly 1024 bytes at the head of the file,
there is a simple textual format which AFAIK is always ASCII, but
we allow here for latin1 encoding. The format has a type declaration
for each field a... | d0055b3dc276facd9acb361dfde167d8c123b662 | 51,098 |
def add_records(datalinks_records_list):
"""
upserts records into db
:param datalinks_records_list:
:return: success boolean, plus a status text for retuning error message, if any, to the calling program
"""
rows = []
for i in range(len(datalinks_records_list.datalinks_records)):
fo... | db359c586ce70b536f5a2753c365987280ed72f6 | 51,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.