content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def expand_header(row):
"""Parse the header information.
Args:
List[str]: sambamba BED header row
Returns:
dict: name/index combos for fields
"""
# figure out where the sambamba output begins
sambamba_start = row.index('readCount')
sambamba_end = row.index('sampleName')
... | 740790e5aa0f5415d3cb0fc22902403b16bef455 | 3,599,418 |
def _convert_types(image: tf.Tensor) -> tf.Tensor:
"""入力データセットを成型する
Args:
image (tf.Tensor): 入力画像
Returns:
tf.Tensor: 変換した画像
"""
image = tf.cast(image, tf.float32)
image /= 255.0
image = tf.reshape(image, [28, 28, 1])
return image | 5a07127c69cb382cce5c7dc6374d438a531e85b8 | 3,599,419 |
def file_get_contents(space, fname, num_args, use_include_path=False,
w_ctx=None, offset=-1, maxlen=0):
""" file_get_contents - Reads entire file into a string """
fname, read_filters, write_filters = _parse_wrapper(fname)
if fname == "" or fname is None:
space.ec.warn("file_ge... | 5b42104af22dcf4323153cb35dd05ec5b7c85906 | 3,599,420 |
def kernel_pdf_lognorm_(x, sample, bw):
"""Log-normal kernel for density, pdf, estimation, explicit formula.
Jin, Kawczak 2003
"""
term = 8 * np.log(1 + bw) # this is 2 * variance in normal pdf
pdf = (1 / np.sqrt(term * np.pi) / sample *
np.exp(- (np.log(x) - np.log(sample))**2 / term))... | 810b553d8aaf8bb5a4db4220f9fdc049245754e6 | 3,599,421 |
def get_carlyle_2017_dataframe():
"""
Return pandas dataframe for Carlyle 2017
:return:
pandas.core.frame.DataFrame: dataframe containing Carlyle 2017 data.
"""
print("Importing Carlyle 2017 pandas dataframe.")
# from 41593_2017_11_MOESM12_ESM data in 41593_2017_11_MOESM6_ESM is log10LFQ
... | 71ee70022b9f1165ca0e9c9e93c7c5375a34e618 | 3,599,422 |
def get_translations_diff(original_database, modified_database):
"""
Receive the databases names, get the translations and return a dict with the added,
modified and removed translations.
:param original_database: The name of the unmodified database.
:param modified_database: The name of the updated... | 380706f4eadb16d9438671dc6e03099355ab5b59 | 3,599,423 |
def cap_text(text):
"""
Capitalize first letter of a string
:param text: input string
:return: capitalized string
"""
return text.title() | 8403db85d37399db3b4b0693bc9e578ddcf01c3b | 3,599,424 |
def find_smalldim(imgs):
"""
Find smallest dimension of an image or list of images.
Parameters
----------
imgs : single 3D np.array or list of 3D np.arrays {
titles : str, default = None
Returns
-------
smallest_axis: int
"""
if isinstance(i... | bbcb95955e60e0ad038dbb112538d7bc0a9281fd | 3,599,426 |
def htmlize_list(items):
"""
Turn a python list into an html list.
"""
out = ["<ul>"]
for item in items:
out.append("<li>" + htmlize(item) + "</li>")
out.append("</ul>")
return "\n".join(out) | f9ac8106d85bef8807b54deeb4781fa6323af9cf | 3,599,428 |
def extractGilaTranslation(item):
"""
# Gila Translation Monster
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
ltags = [tmp.lower() for tmp in item['tags']]
if 'dawn traveler' in ltags and 'translation' in l... | 442d591bb7f96a561531867f882eacc5bc68a15b | 3,599,429 |
def _assign(
old_data,
mask,
new_data,
band_offset,
band_axis,
band_selection,
subassign,
mask_type,
replace,
accum,
ot,
):
"""
Performs the actual GrB_assign:
old_data(mask, ...)[index] << obj
or GxB_subassign:
old_data[index](mask, ...) << obj
... | 0eb7fc61861b2ef047bcd82194be394b305320e5 | 3,599,430 |
def playbook_log(request):
"""Retrieve log entries."""
log = spotmax.SPOTLog()
log_entries = log.get_log_entries(50)
# Convert '_id' to string and remove '_' from the key
logs = list()
for log in log_entries:
log['id'] = str(log['_id'])
del log['_id']
logs.append(log)
return render(
... | c730f801b4a6b716e5bbd893225848571eb4a7d2 | 3,599,431 |
def size_as_recurrence_map(size, sentinel=''):
"""
:return: dict, size as "recurrence" map. For example:
- size = no value, will return: {<sentinel>: None}
- size = simple int value of 5, will return: {<sentinel>: 5}
- size = timed interval(s), like "2@0 22 * * *:24@0 10 *... | 203bc0697cca9b3710f4079de03e759659116883 | 3,599,432 |
from typing import Optional
from typing import Any
from typing import Callable
def make_jac_jnp_to_onp(input_pytree_topology: PyTreeTopology,
output_pytree_topology: PyTreeTopology,
dtype: Optional[Any] = onp.float64) -> Callable:
"""Returns function "flattening" Jaco... | fd6a19bf881c36fc79b9201f055af5862e9ecd4d | 3,599,434 |
def create_app(testing: bool = False) -> Flask:
"""
Create and configure an instance of the Flask application.
"""
app = Flask(__name__)
if testing:
app.config['TESTING'] = True
@app.route('/')
def index():
return 'Hello, World!'
return app | 1cf39433e8526a3b22126f9b96e77102ca0387b7 | 3,599,435 |
def delete_dr_event(request, pk):
"""
:param pk: the pk of the event that is being cancelled
:param request: request object
:return: redirects user to homepage
"""
old_dr_event = DREvent.objects.get(pk=pk)
new_dr_event = old_dr_event
new_dr_event.pk = None
new_dr_event.deleted = True... | 07c741173431721bf3f39729ec52385ded207aee | 3,599,436 |
def getTrimBox(pdf, pagenumber):
"""Get a trim box given the document, page range, min x, max x,
min y, max y in points. Only suceeds if such a box exists, as checked by
hasBox"""
minx = c_double(0.0)
maxx = c_double(0.0)
miny = c_double(0.0)
maxy = c_double(0.0)
libc.pycpdf_getTrimBox(p... | f1bb4095ceba85582b3813b1383107edd2326e8b | 3,599,437 |
def interpolate_minus_plus_oxts(oxts_minus, oxts_plus, start_traveled):
"""Interpolate between closer and further points to get path point estimates."""
traveled_minus = oxts_minus.traveled.values - start_traveled
traveled_plus = oxts_plus.traveled.values - start_traveled
alpha = (PATH_POINTS - traveled... | 57ff28796375c93fc21d9c22ddc3827567cf9708 | 3,599,439 |
def cumulative_average_mask(sequence_length, maximum_length=None, dtype=tf.float32):
"""Builds the mask to compute the cumulative average as described in
https://arxiv.org/abs/1805.00631.
Args:
sequence_length: The sequence length.
maximum_length: Optional size of the returned time dimension. Otherwise
... | f4bfde66fd4e58f945e25e6c495fb0d09c909eb2 | 3,599,440 |
def U_sparse(angle1, angle2, angle3, invert):
"""Return scipy sparse CSR matrix with U gate (IBM)."""
return sparse.csr_matrix(U_np(angle1, angle2, angle3, invert)) | f744694cc619f44ae6709ad63795fcaedcacf9bb | 3,599,441 |
from ..model.view_model import store
def marketplace():
"""Marketplace."""
return render_template('marketplace.html', store=store) | 3a73b6bce70d6e80a89e949355238ae56c829be4 | 3,599,444 |
def get_field_kwargs(field_name, model_field):
"""
Creates a default instance of a basic non-relational field.
"""
kwargs = {}
return kwargs | d05d5f42a4ecc2669486d049918d271013a6969f | 3,599,446 |
def _check_same_loc(stp1, stp2, staypoints):
"""Check whether two staypoints are at the same location
Parameters
----------
stp1 : int
First staypoint id
stp2 : int
Second staypoint id
staypoints : Trackintel staypoints
GeoDataFrame with staypoints and also location ids
... | 88299b0ed42b7321e82b4309af77253d2eb88a0d | 3,599,447 |
def Rabi_2nd_exc_seq(amps, pulse_pars, pulse_pars_2nd, RO_pars, n=1,
cal_points=True,
post_msmt_delay=3e-6, verbose=False):
"""
Rabi sequence for the second excited state
Input pars:
amps: array of pulse amplitudes (V)
pulse_pars: dic... | 276b38169012e36ac7ac06ec87d43c24a4b32b46 | 3,599,449 |
def _int64_feature(value: int) -> tf.train.Features.FeatureEntry:
"""Create a Int64List Feature
Args:
value: The value to store in the feature
Returns:
The FeatureEntry
"""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) | da7bf0eae1ce7ceb072d1c6a7cea00795b129f97 | 3,599,450 |
from .png_2_ico import png_2_ico
def bat_2_exe(bat_file, exe_file, icon='', *options):
"""
Args:
bat_file: abspath
exe_file: abspath
icon: abspath *.ico
*options: suggested options below
/x64
/invisible
/password {your_password}
... | da768dbc4075971b4e7571b5128b1041713d0d6c | 3,599,451 |
from typing import Callable
from typing import Union
from typing import Sequence
from typing import Tuple
from typing import Any
def value_and_grad(
fun: Callable,
argnums: Union[int, Sequence[int]] = 0,
has_aux: bool = False,
holomorphic: bool = False,
allow_int: bool = False,
) -> Callable[..., ... | 33e2754ba0ae898dc29614236b55316c99754e20 | 3,599,453 |
import requests
import json
def get_mactable(auth):
"""
Function to get list of mac-addresses from Aruba OS switch
:param auth: AOSSAuth class object returned by pyarubaoss.auth
:return list of mac-addresses
:rtype list
"""
headers = {'cookie': auth.cookie}
url_mactable = "http://" + ... | 96c064696bf47872e5a1bec5e8770d6470b76bfc | 3,599,455 |
def es_primo(n: int) -> bool:
"""Determina si un número es primo.
:param n: número a evaluar.
:n type: int
:return: True si es primo, False en caso contrario.
:rtype: bool
"""
if n == 2 or n == 3:
return True
if n % 2 == 0 or n < 2:
return False
for i in range(3, int... | fff4802d6e47c379b6510f13e2ffe9a9d56429d2 | 3,599,456 |
def get_playlists(search_string=None):
"""
This function will be used to get playlists of a specified category
:param search_string: Category name whose playlists are required
"""
item_type = 'playlists'
info_dict = spotify.category_playlists(search_string)
items = info_dict[item_type]["ite... | 7a9c695f221e7284edc39fcfb5f3a450c561a92e | 3,599,457 |
def replace_string(string_value, replace_string, start, end):
"""
Replaces one string by another
:param string_value: str, string to replace
:param replace_string: str, string to replace with
:param start: int, string index to start replacing from
:param end: int, string index to end replacing
... | b79d685a13c427334149789195e5fbbb4a6ad28d | 3,599,458 |
from operator import concat
import torch
def collect_results(results):
"""
Converts a list of flat records/rows to a list of tall, row-wise concatenated columns
Useful for collecting a set of batches or individual samples of 0- and 1-dimensional tensors returned by each model step, collected in a list in model.o... | e6ca0388cc0bb13aa1a574bc584527e2d7fd48e6 | 3,599,459 |
def custom_exception_handler(exc, context):
""" This function runs after every exceptions raised anyware from code """
response = exception_handler(exc, context)
# Custom reposense data will be returned only if exception will be APIValidationError
if isinstance(exc, APIValidationError):
custom_... | 3dd228f3ed288ab0719376e4be6336b6f436c7d3 | 3,599,461 |
import hashlib
def hash_str(data, hasher=None):
"""Checksum hash a string."""
hasher = hasher or hashlib.sha1()
hasher.update(data)
return hasher | 5dd433a3cc04037bb439b64b71d3495d03f51ef1 | 3,599,462 |
def get_next_point(df, inc, axis):
"""
Increment to get the next points along.
Parameters
----------
df : pandas DataFrame
The dataframe of points
inc : int
The amount to increment
axis : str
The axis along which to increment. Can be 'x', 'y', or 'z'
"""
df =... | 5b91f2f23f188891ff04ded3f4a76e6b552fa2a0 | 3,599,463 |
import torch
import tqdm
def eval_epoch(model, loss_func, validation_data_generator, p_list=None):
"""Epoch operation in evaluation phase"""
bce_total_loss = 0
model.eval()
with torch.no_grad():
y_list, w_list, pred_list = [], [], []
bar = tqdm(range(update_num_per_eval_epoch), desc=' - (Validation) ', ... | 29d4a6aee8f441caa10730d1e59a1cdb16d30426 | 3,599,464 |
def CDLADVANCEBLOCK(barDs, count):
"""Advance Block"""
return call_talib_with_ohlc(barDs, count, talib.CDLADVANCEBLOCK) | fd6e98325e53238eed7333f4ea934a9c510bad45 | 3,599,465 |
def anchor_generator(input,
anchor_sizes=None,
aspect_ratios=None,
variance=[0.1, 0.1, 0.2, 0.2],
stride=None,
offset=0.5,
name=None):
"""
**Anchor generator operator**
Generate anc... | 49c7bb6376ea8163cb7d3f0635aa7fc1abebea8f | 3,599,466 |
def load_input(filename):
"""
Load poker hands from filename
"""
hands = []
with open(filename) as f:
for line in f.readlines():
tokens = line.strip().split(" ")
cards = []
for token in tokens:
value = token[0]
suit = token[... | ba79c8163098be587729f788ce231c02204f77ce | 3,599,468 |
def read_imagenet_label_map():
"""
load imagenet label map
"""
return callZooFunc("float", "readImagenetLabelMap") | 33c93638c47aac2ebd364ad3520420ffc5bc54e6 | 3,599,469 |
def string(value):
"""Validate that a configuration value is a string. If not, automatically converts to a string.
Note that this can be lossy, for example the input value 60.00 (float) will be turned into
"60.0" (string). For values where this could be a problem `string_string` has to be used.
"""
... | 5eeba7016308912f3f79abca9fd4c6e737dea672 | 3,599,470 |
from typing import IO
async def async_failure(
container: 'FutureResult[_ValueType, _ErrorType]',
) -> IO[_ErrorType]:
"""Async unwrap an error from container."""
return IO((await container._inner_value).failure()) | 66841dc44d79095e6359d1d35854330c1ccacea5 | 3,599,471 |
import json
def FormatChromeSettings(settings):
"""Makes adjustments to settings before presenting JSON."""
# Split textarea fields.
for text_field in GetTextFields():
if settings.get(text_field):
settings[text_field]['Value'] = settings[text_field]['Value'].split('\n')
return json.dumps(settings) | 89b2d7c92fabeeec5b423477d7a70616f26225fa | 3,599,472 |
def connect(*args, **kwargs):
"""Proxy connect with an additional kwarg set"""
kwargs["connection_factory"] = connection
return _2connect(*args, **kwargs) | 2d4a261d431a1f1a513b4a302e2499f0392cf81e | 3,599,473 |
def process(s):
"""Given a string with a bunch of markdown links in the style we use
in our changelog, generate the following material to insert in
the changelog.
>>> print(process("Hello [#123] [!456]"), end="")
[!456]: https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/456
... | 394cf25b8e06ec2e2162f86a834e36e1a1c5d622 | 3,599,474 |
from typing import Iterable
def check(line: Iterable[str]) -> Result:
"""Run the syntax check on a line of bracket text."""
# Save the opening brackets on the stack, and pop them as they're closed.
stack = []
closing = {"(": ")", "[": "]", "{": "}", "<": ">"}
for c in line:
if c in "([{<":... | 1f75f53e77985f2d7f8199ecace52605a7208cc7 | 3,599,475 |
def _filter_and_buffer_points_by_year(
point_table, lat_field, long_field, year_field, point_buffer):
"""Separate points in Geopandas table by year.
Args:
point_table (geopandas.Dataframe): table with lat/lng and year fields
lat_field (str): fieldname for lat in ``table``
long_f... | 68c66d05d27e773d3a751d3a293b473da5c1aa5b | 3,599,476 |
from typing import Union
from typing import Iterable
from typing import Callable
from typing import List
def combine_requirements(
requirement: Union[_Requirement, Iterable[_Requirement]],
*requirements: _Requirement,
normalize_func: Callable[[str], str] = normalize
) -> List[ComparableRequirement]:
"""
Com... | d9c21bb2919229ac5e29be6ce20e23345bc11634 | 3,599,477 |
def getSlotsRedirect(entity, params):
"""Returns the slots redirect for the specified entity.
"""
return'/%s/slots/%s' % (
params['url_name'], entity.key().id_or_name()) | 1301bcd68a987b1a72f7ea82f55cf5a57e5ae8d2 | 3,599,478 |
import math
def parse_sudoku(file):
""" parses a sudoku from a given file """
parsed = []
try:
with open(file) as f:
for line in f:
parsed.append([item for item in parse_int(line)])
except IOError:
raise ValueError(""" The sudoku file is not there, please"... | 9a1c1ad18432210cd240bc0e3f2d58762a31dcf3 | 3,599,479 |
def get_setting_type(setting_name: str) -> str:
"""
Return a string corresponding to the type of setting that is specified by setting_name.
:param setting_name: Name of the setting to change
:return: String corresponding to the type of setting that is specified by setting_name.
"""
if setting_na... | d03fa8be0052513425813c2ed769061472a3331d | 3,599,481 |
from datetime import datetime
def log_query(service, question: str, answer: str, sentiment: str = "N/A", spreadsheet_id: str = SPREADSHEET_ID) -> int:
"""
Logs a user query and chat bot response to a Google Sheet as well as the timestamp
:param service: Google Sheets API service
:param question: User... | 2a60bbb6526dfb366444947edc79434ae19b22a8 | 3,599,482 |
import urllib
import logging
import json
def get_weather(lat, long):
"""Return weather report for the next 24 hours"""
url = f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={lat}&lon={long}"
req = urllib.request.Request(url, headers={"Accept" : "application/json"})
logging.info("Retri... | 8e0ac597a15f2aaf4ac96ee30b546a0a8e1c63a1 | 3,599,483 |
def recession_spans():
"""
recession span dates from:
THE AUSTRALIAN BUSINESS CYCLE: A COINCIDENT INDICATOR APPROACH
RBA Discussion Paper 2005-07
Christian Gillitzer, Jonathan Kearns and Anthony Richards
http://www.rba.gov.au/publications/rdp/2005/pdf/rdp2005-07.pdf
"""
recessions = [
... | a2070016c3a1cbc1a34f209912d10287c364ff15 | 3,599,485 |
def primal_dual_with_candidate(variables, theta_est_bk, candidate, *args, **kwargs):
"""
Primal dual interior method with candidate
Args:
variables(variables): variable parameters
theta_est_bk(matrix): theta estimation
candidate(list): candidate solvers
"""
candidate = map(l... | 52ae145d2803c682b967a9106140c558a1a6c400 | 3,599,486 |
from doorbirdpy import DoorBird
def setup(hass, config):
"""Set up the DoorBird component."""
# Provide an endpoint for the doorstations to call to trigger events
hass.http.register_view(DoorbirdRequestView())
doorstations = []
for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVI... | ad0a7cc55a35d0f117bff63603e6166758ea40c1 | 3,599,487 |
def swap(quoteAsset, baseAsset, quoteQty, recvWindow=""):
"""# Swap (TRADE)
#### `POST /sapi/v1/bswap/swap (HMAC SHA256)`
Swap `quoteAsset` for `baseAsset`.
### Weight:
2
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
quoteAsset |STRING |YES |
baseAsset |STRING |YES |
quoteQ... | 71ee6ff1a70687dd0fdf60081c4dc944dc4aa356 | 3,599,488 |
def _getresponse(self):
"""Monkey-patched replacement getresponse method"""
intercept = self._intercept()
if intercept['mode'] == 'normal':
response = self._orig_getresponse()
if 'recorder' in intercept:
intercept['recorder']._record_response(response)
# ... | 9131ac0aa03c841cb971456d7b04b1e942dd1e78 | 3,599,490 |
def ebnbm_gamma(x, s, init=None, max_iters=10000, tol=1e-3, extrapolate=True,
fix_g=False, fix_theta=True):
"""Return fitted parameters and marginal log likelihood assuming g is a Gamma
distribution
Returns log mu, -log phi, log theta
x - array-like [n, p]
s - array-like [n, 1]
init - arra... | ff400ebb36487ac34cc69d619d85e781e6c113f4 | 3,599,491 |
def push_data(metrics_payload, url=METRICS_COLLECTION_URL):
"""
Pushes individual Payload data (SA or RE Data) to specified url.
:param audit_data: Audit Data
:return: Request Object
"""
_session.post(url=url, json=metrics_payload)
return None | 14671e026af2bba2c997cc2aca19bf3fb7d6ed5b | 3,599,493 |
def oned_pitchfork(g0=.1,g1=2.5,N=50):
"""
get figure for 1d pitchfork bifurcation
"""
fig = plt.figure(figsize=(5,3))
ax = fig.add_subplot(111)
ax.set_xlabel(r'$g$')
ax.set_ylabel('Bump Velocity')
glist = np.linspace(g0,g1,N)
an_arr_plus = np.zeros(N) # analytic speed
num_arr_p... | 19da1f5111e977ebcd78c49bedb63736117d96ee | 3,599,494 |
from datetime import datetime
import math
def _stats(tracking_data):
"""
Get statistics on the word count over time, as per nanowrimo.
Input:
wordcount_list - a list of integer word counts, one per day
starting_date - a datetime.date object giving the starting point of the period.
... | 4bd8125273eab44d1e45f5fc371523f79de5c8c4 | 3,599,495 |
def elina_texpr0_array_is_scalar(texpr_array, size):
"""
Test if an ElinaTexpr0Array has only scalar coefficients (non-interval).
Parameters
----------
texpr_array : ElinaTexpr0Array
ElinaTexpr0Array that needs to be tested.
size : c_size_t
Size of the ElinaTexpr0Array.
Ret... | a1d430896b7f6d78ae133d45d257852292f2ab50 | 3,599,496 |
def onesample(data):
"""sample for semi-parametric bootstrap"""
fitted = powerlaw.Fit(data, discrete=True, verbose=False)
xmin = getattr(fitted, "power_law").xmin
lower = [n for n in data if n < xmin]
lower_sample = np.random.choice(lower, len(lower), replace=True)
upper_sample = getattr(fitted,... | 3ef80225488eb060692bcf01ef4b5ee8814bcff8 | 3,599,497 |
def validate_answer(value):
"""
Validate a JSON input for a single answer.
Parameters:
value (any): Input value
Returns:
boolean: True if value has the format required for an answer
"""
validators = {
"participant_id": validate_int,
"question_id": validate_int,
... | bc3087abc330bdcdf143a1b5a8c0da0238670a6d | 3,599,498 |
def _find_baseline_bxr(spectrum, noise_std=None, A=None, B=None,
A_star=5.*10e-9, B_star=1.25, max_iter=30,
min_err=10e-6):
"""Private function to estimate the baseline of an MRSI spectrum.
Parameters
----------
spectrum : ndarray, shape (n_samples, )
... | c7990d92326a2db8383fcbe977fea1f0cb36ad2f | 3,599,499 |
def get_voms_proxy_vo():
"""
Returns the virtual organization name of the voms proxy.
"""
return _voms_proxy_info(["--vo"])[1].strip() | 68497ab9f4a1814c7a0d0e46e1f611acb25bf23c | 3,599,501 |
def readImage(filename):
"""
Read in an image file, errors out if we can't find the file
:param filename: The image filename.
:return: The img object in matrix form.
"""
img = cv2.imread(filename, 0)
if img is None:
print('Invalid image:' + filename)
return None
else:
... | a868b79627561ed4a47bac3bf589fe950240a70f | 3,599,502 |
def mk_contract_address(sender: str, nonce: int) -> str:
"""Create a contract address using eth-utils.
https://ethereum.stackexchange.com/a/761/620
"""
sender_bytes = to_bytes(hexstr=sender)
raw = rlp.encode([sender_bytes, nonce])
h = keccak(raw)
address_bytes = h[12:]
return to_checksu... | ae974160651089e2a35ba23e9b29e7e74963ea0f | 3,599,504 |
import functools
def synchronize(lock):
""" Decorator that invokes the lock acquire call before a function call and releases after """
def sync_func(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
lock.acquire()
res = func(*args, **kwargs)
lock.r... | e9ac48d67cf45e1b0cf9b6e776a93f569726b5d4 | 3,599,505 |
def help_invocation_for_command(prefix, command, locale):
"""
Get the help command invocation for a command.
Parameters
----------
prefix: str
The command prefix to show.
command: senko.Command
The command to get the help invocation for.
locale: senko.Locale
The loca... | abf80554c479e3f766e6a7dc1e7bbcafdbaa6098 | 3,599,506 |
from re import T
import numpy
def fourier_complex_morlet(bandwidths, centers, N):
"""Complex Morlet wavelet in Fourier
Parameters
----------
bandwidths: array
the bandwidth of the wavelet
centers: array
the centers of the wavelet
freqs: array (optional)
the frequenc... | b801822178cffcbb71b240fb3d1465481b0f42f0 | 3,599,507 |
from datetime import datetime
def payment():
"""
Payment Page
------------
"""
user_cart = current_user.cart
# extracting user info entered in checkout form
form = CheckoutForm()
name = form.name.data
city = form.city.data
address = form.address.data
phone = form.phone.data... | 3f160dcff655a96422a318239d9fc1533351ed18 | 3,599,508 |
import torch
def derivative_sigmoid(x):
"""Compute the derivative of the sigmoid for a given input.
Args:
x (torch.Tensor): The input.
Returns:
(torch.Tensor): The derivative at the input.
"""
return torch.mul(torch.sigmoid(x), 1. - torch.sigmoid(x)) | 00da3734436294bc8bb40189bc1298972fbe7f93 | 3,599,509 |
def registry(add_cls=None):
"""Global registry of action classes."""
if add_cls != None:
REGISTRY[add_cls._id] = add_cls
return REGISTRY | 462b30a1278b61c3eeca9c00bdc0e8477d1faa63 | 3,599,510 |
from typing import Tuple
from typing import Optional
def nvidia_driver_version() -> Tuple[Optional[int], Optional[int]]:
"""
Returns the nvidia driver version.
Returns:
tuple: A tuple with major and minor driver version.
"""
query = smi.getInstance().DeviceQuery('driver_version')
if q... | febb7679100a641b98970dd8eace98ec9bfe15b4 | 3,599,511 |
def bands_to_frequency(bands):
"""Converts a list of bands into an array of frequency in Hz
:param bands: List of bands.
:type bands: list[str]
:return: An array of frequency associated with the given bands.
:rtype: np.ndarray
"""
if bands is None:
bands = []
df = pd.read_csv(f"... | c9b98c2d45ab3a0bad70dd1af27c7ca215e4b4bb | 3,599,512 |
def SBP_single(ell_fix, redshift, pixel_scale, zeropoint, ax=None, offset=0.0,
x_min=1.0, x_max=4.0, alpha=1, physical_unit=False, show_dots=False, show_grid=False,
show_banner=True, vertical_line=None, linecolor='firebrick', linestyle='-',
linewidth=3, labelsize=25, ticksize=30, label='SBP', labelloc='l... | c9133d9dbb9b48e7b278bff061a6d66fad5b547c | 3,599,513 |
def get_chromedriver_url(version):
"""
Generates the download URL for current platform , architecture and the given version.
Supports Linux, MacOS and Windows.
:param version: chromedriver version string
:return: Download URL for chromedriver
"""
base_url = 'https://chromedriver.storage.goog... | c74c116e1afce42e8c048d5d914e00e2afab62ea | 3,599,514 |
def augment(image_samples):
"""
augments each of the given images by addying noise, blur and both
:param image_samples: image samples as dict indexed by the kanji the image depicts, with a list of
(font_name, image) as value
:return: a list containing the original as well as... | f8d5ce69f84d6c30a96be476b4cd041f2d11e8bb | 3,599,515 |
def loginUser(username, password): # noqa: E501
"""
# noqa: E501
:param username: The user name for login
:type username:
:param password: The password for login in clear text
:type password:
:rtype:
"""
return 'do some magic!' | 20466f242fd92ae09113e6fe3b2ef0c1b03b85b8 | 3,599,516 |
def API_to_APP_ABPBA(API_pre, API, idx2apk, apk2node, A, B, P, p, q):
"""
A helper funtion for generating ABPBA random walks.
Given previous API and current API, sample next APP (second A edge)
"""
# find neignbors of current API
ser = pd.Series(A.T[API].toarray()[0])
A_neibors = ser[ser == ... | 3b60e5b73fb29e4f61feff50439084243059421c | 3,599,517 |
def plot_saturation(
isoseq=None,
ax=None,
cov_th=2,
expr_th=[0.5, 1, 2, 5, 10],
x_range=(1e4, 1e7, 1e4),
legend=True,
label=True,
**axparams,
):
"""Plots Negative Binomial model to analyze the saturation of LRTS data.
Saturation (e.g. the probability to observe a transcript of ... | a21018873f441ff84defb9a6ddb0f8650c6f7d78 | 3,599,521 |
def canRead(*args, **kwargs):
"""
Check if an input can be read by the module class.
"""
return MultiFileTileSource.canRead(*args, **kwargs) | 4ab00bcca27abc7d8286904177aafe5ebbc4eb38 | 3,599,522 |
def conv_to_onehot_12(grid):
"""
:param grid: matrix with item equal to 0 or time of 2
:return: 16*grid.shape one-hot format 3D matrix
"""
one_hot = np.zeros((12,) + grid.shape) # , dtype=np.int)
one_hot[0, grid == 0] = 1
for i in range(1, 12):
one_hot[i, grid == 2**i] = 1
ret... | 4c55bd4e8f46af518d30b6902bc543f69fc2a264 | 3,599,524 |
def cluster_update(context, cluster, values):
"""Set the given properties on cluster and update it."""
return IMPL.cluster_update(context, cluster, values) | 518a512bfb86d062bc3d3a258ad7faf99db86009 | 3,599,525 |
from typing import Callable
from typing import Generator
import functools
from typing import Any
def listify(
func: Callable[..., Generator[Item, None, None]]
) -> Callable[..., list[Item]]:
"""Decorator to make generator function return a list."""
@functools.wraps(func)
def _wrapper(*args: Any, **kw... | fd05a339e77dab373ed4dd8efb7e4db4b248724f | 3,599,526 |
import scipy
def _experiment_01():
"""Rejection sampling experiment 01."""
_pdf_gen_1 = scipy.stats.norm(5, 1)
_pdf_gen_2 = scipy.stats.norm(-2, 3)
_pdf_gen_3 = scipy.stats.expon()
def complex_fun(
x: t.Union[int, float, np.ndarray]) -> t.Union[np.ndarray, float]:
return (0.2... | c89af2ff4f3cf72f03036e9ff21b0c73686a32bd | 3,599,527 |
def get_shape_input():
"""Get shape of the dataset for Thyroid dataset"""
return (None, 36) | 56786b62a6ea699ef6cad4e92777ead4e60b6b3c | 3,599,528 |
def generate_all_nbr_from_dataframe(dist_df, nbr_distance = 100.0):
"""
Given a distance matrix, return a list of index positions of all neighbors
within a certain distance.
Parameters
----------
dist_df : DataFrame
nbr_distanace : float
Returns
-------
all_nbrs : list
... | a735c25febbab446e28486174aa2d5ef3cb3d5d0 | 3,599,529 |
import requests
import json
def getToken():
"""
tokenを取得する。tokenの初期化や有効期限が切れていた時などに呼ばれる。
成功したらtrueを、失敗したらfalseとその時のHTTPレスポンスを返す
"""
header = {
"Accept": "application/json",
"Content-Type": "application/json",
"Content-Length": "*"
}
body = {"email": data.email}
... | 8bc931a5b07223253d5564fcc620149fc234fa84 | 3,599,530 |
def get_facility_of_source(client: Client, id: int) -> dict: # noqa: unused client
"""Get facility for specific source by ID."""
disallow_parameters(request)
source = _get_source(id, client)
if source.facility_id is None:
raise NotFound(f'No facility for source ({source.id})')
else:
... | 23a4cbc45c3c5612f4c507aaa844448d303b02ca | 3,599,532 |
def ess(log_weights: jnp.ndarray, log: bool = True) -> float:
"""Compute the effective sample size from the log-weights in a numerically stable way.
Parameters
----------
log_weights: np.ndarray
log-weights of the sample
log: bool
Compute the log-ESS or the ESS
Returns
----... | b72ea46de276618e019a9162710237c74c97e4f9 | 3,599,533 |
def mi(x, y, bins=64):
"""Calculate the mutual information between two random variables.
Calculates mutual information, I = S(x) + S(y) - S(x,y), between two
random variables x and y, where S(x) is the Shannon entropy.
Parameters
----------
x : array
First random variable.
y : arra... | 9c1d371270573b10acffa5629e160d4bc9d1ea7d | 3,599,534 |
def filter_by_predicate(walk: OsWalk, predicate: WalkPredicate, abs_path: bool = False, prune: bool = False) -> OsWalk:
"""
Filters a walk's folder AND file collection using the given predicate.
:param walk: The walk 'object' to filter
:param predicate: The condition to check; should take in the folder... | 32913812a9adf8a511416e3799992897399b1d60 | 3,599,535 |
def simple_builder(pot_family, queue, code, calc_cls):
"""Submit simple example in AiiDA 0.12.0 and higher."""
builder = calc_cls.get_builder()
builder.structure = create_structure_Si()
builder.kpoints = create_kpoints()
builder.parameters = create_params_simple()
builder.code = code
builde... | 2f7b58d87589eb3095dace4ac189dbbb4e82cede | 3,599,536 |
import warnings
def fetch_latest_schema(
schema_name,
schema_group,
mongo_collection,
):
"""find latest schema in database
Args:
schema_name (str): data source name
schema_group (str): datas source group
mongo_collection (:obj:`pymongo.collection`): db connecti... | 986850593d8b9f2565e5c7d61e935c31f8ad05bf | 3,599,537 |
from pathlib import Path
async def check_node_modules():
"""Check if node_modules exists and has contents.
Returns:
{bool} -- True if exists and has contents.
"""
ui_path = Path(__file__).parent / "ui"
node_modules = ui_path / "node_modules"
exists = node_modules.exists()
valid ... | e76703372c46982cf728b26125808e50e2b92907 | 3,599,538 |
def FCN_ResNet34(in_channels=1, **kwargs):
"""
Constructs FCN based on ResNet18 model.
"""
backbone_net = resnet34(in_channels=in_channels)
model = FCN_ResNet(backbone_net, **kwargs)
return model | 7a17560e27e2b4c14149c4781c5a5ca639b6289c | 3,599,539 |
from typing import Tuple
from typing import Optional
from typing import Sequence
from typing import Dict
from operator import gt
def flat_model(
adata: AnnData,
max_iterations: int = 1000000,
epsilon: float = 0,
equilibrate: bool = False,
wait: int = 1000,
nbreaks: int = 2,
collect_margina... | c8c763040ea1ae754397be55a33e5e59f28bb00a | 3,599,540 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.