content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def clear(ctx):
"""Clear all config values."""
log.debug('chemdataextractor.config.clear')
config.clear() | 58,400 |
def validate_unity(unity_permutation: List[Any]) -> bool:
"""Checks that the input permutation is the unity permutation, i.e., an
object s of type List[List[int], float, bool] such that
* s[0][0] > -1,
* s[0][i] < s[0][j] for i < j,
* s[1] = 1.0, and
* s[2] = False.
Args:
unity_per... | 58,401 |
def gf_TC(f, K):
"""Returns trailing coefficient of `f`. """
if not f:
return K.zero
else:
return f[-1] | 58,402 |
def readinput(filename, target_col=None, exclude_features=None,
make_shadows=False):
"""
Read a dataset and return an input and a target features subset
Parameters
----------
filename : str
The file path of the dataset to be read
target_col : str or integer, ... | 58,403 |
def shared_podcast_episode_query(user):
"""
Shared query set for PodcastEpisodesViewSet and RecentPodcastEpisodesViewSet
"""
return (
PodcastEpisode.objects.filter(published=True, podcast__published=True)
.prefetch_related(
Prefetch("offered_by", queryset=LearningResourceOff... | 58,404 |
def generate_tclloader_radfilt(radin, rads):
"""
Filter non-existent radio variants.
:param radin: Directory containing files to copy.
:type radin: str
:param rads: List of radio variants.
:type rads: list(str)
"""
rfiles, infiles = generate_tclloader_radset(radin, rads)
coll = [os... | 58,405 |
def verifyRequiredEnvVars():
"""Verify that all required environment variables are set. Error and exit if one is not set."""
for var in REQUIRED_ENV_VARS:
verifyRequiredEnvVar(var) | 58,406 |
def convert_image(
png_image_base64: str, jpeg_image_quality: int = IMAGE_QUALITY_JPEG
) -> str:
"""
Convert an image from PNG to JPEG, encoded in Base64.
(Semi-)transparent pixels are replaced with (semi-)white pixels in
the output JPEG image.
Args:
png_image_base64: PNG image encoded... | 58,407 |
def merge(*args):
""" Merge multiple frame states together """
if not args:
return create()
s = {arg['identifier'] for arg in args}
if len(s) != 1:
raise ValueError("Expected identifiers, got %s" % str(s))
children = defaultdict(list)
for arg in args:
for child in arg['ch... | 58,408 |
def load_jupyter_server_extension(lab_app):
"""Registers the API handler to receive HTTP requests from the frontend extension.
Parameters
----------
lab_app: jupyterlab.labapp.LabApp
JupyterLab application instance
"""
url_path = "ros"
setup_handlers(lab_app.web_app, url_path)
l... | 58,409 |
def int64_counter(urn, metric, ptransform=None, pcollection=None, labels=None):
# type: (...) -> metrics_pb2.MonitoringInfo
"""Return the counter monitoring info for the specifed URN, metric and labels.
Args:
urn: The URN of the monitoring info/metric.
metric: The payload field to use in the monitoring ... | 58,410 |
def test_add_geo_distance_with_dict():
"""
Create Geo Distance with Dictionary
"""
# When add a Geo Distance field
t = GeoDistance({"lat": 1.0, "lon": 2.0}, "20mi")
# Then I see the appropriate JSON
results = {
"geo_distance": {
"distance": "20mi",
"location"... | 58,411 |
def _to_binary_string_py3(text):
"""
Converts a string to a binary string if it is not already one. Returns a str
in Python 2 and a bytes in Python3.
Do not use directly, use to_binary_string instead.
"""
if isinstance(text, six.binary_type):
return text
elif isinstance(text, six.st... | 58,412 |
def get_log_info(prefix='', rconn=None):
"""Return info log as a list of log strings, newest first. On failure, returns empty list"""
if rconn is None:
return []
# get data from redis
try:
logset = rconn.lrange(prefix+"log_info", 0, -1)
except:
return []
if logset:
... | 58,413 |
def get_hidden_status(data):
"""
使用Gaussian HMM对数据进行建模,并得到预测值
"""
cols = ["r_5", "r_20", "a_5", "a_20"]
model = GaussianHMM(n_components=3, covariance_type="full",
n_iter=1000, random_state=2010)
model.fit(data[cols])
hidden_status = model.predict(data[cols])
retu... | 58,414 |
def N_interrupts():
"""(read-only) Number of interruptions this bus per year"""
return lib.Bus_Get_N_interrupts() | 58,415 |
def strip_parameter(context, param):
"""
A template tag to remove the specified parameter from the url
string. If there are no parameter left, it returns the bare
url (without any parameters or ?-mark)
"""
query = context["request"].GET.copy()
query.pop(param)
if len(query):
r... | 58,416 |
def get_center_radius(ra, dec, logger=logger):
"""Get a list of RA and DEC coordinates and returns the center and the
search radius."""
center_ra = (np.max(ra) + np.min(ra))/2
center_dec = (np.max(dec) + np.min(dec))/2
radius = np.max([np.max(ra) - np.min(ra),
np.max(dec) - np.m... | 58,417 |
def calculate_health(package_name, package_version=None, verbose=False, no_output=False):
"""
Calculates the health of a package, based on several factors
:param package_name: name of package on pypi.python.org
:param package_version: version number of package to check, optional - defaults to latest ve... | 58,418 |
def _df_to_array(instances):
"""
Transform inputs into arrays
Parameters
----------
instances : DataFrame, Series or array
Input data
Returns
-------
instances : array
Transformed features
"""
if isinstance(instances, pd.DataFrame):
return instances.valu... | 58,419 |
def S2(Scat,
Source,
phi,
theta):
"""Function compute :math:`S_2` component of scattered FarField defined
as Eq:III.111 of B&B.
:math:`S_2 = \sum_{n=1}^\\infty \sum_{m=-n}^{n} \\frac{2n+1}{n(n+1)}
\\Big[ a_n g_{n,TM}^m \\tau_n^{|m|} \\big(\cos (\\theta) \\big) +
m i b_n g_{n,TE... | 58,420 |
def text_to_html(string):
"""Take text as input and return html that renders nicely.
For example replace newlines with '<br/>'
This was built for use in reminder emails, please check for
effects there if you are updating it."""
string = "<html><body>" + string + "</body></html>"
string = string... | 58,421 |
def spacecraft_vel(deltaw, deltan, deltar, dij, vmap):
"""
function to calculate pixel-wise spacecraft velocities for Sunpy map
Based on Haywood et al. (2016) and described in Ervin et al. (2021) - In Prep.
Parameters
----------
deltaw: float, array
relative westward position of pixel
... | 58,422 |
def task__package_mkdir_iso_root() -> types.TaskDict:
"""Create the packages root directory on the ISO."""
return targets.Mkdir(
directory=constants.REPO_ROOT, task_dep=['_iso_mkdir_root']
).task | 58,423 |
def _gen_3d_examples(x1_size: float, x2_size: float, num_examples: int,
noise_prob: float):
"""Generates 3D examples
Each example has coordinates [x1, x2] where:
- x1 is on interval [0, x1]
- x2 is on interval [0, x2]
Args:
x1_size: Size of first axis.
x2_s... | 58,424 |
def get_target_args(args: List[Arg]) -> List[Arg]:
"""Given args for a controlled operation, get the args that are being acted on"""
return [arg for arg in args if arg[0] < 2 and arg[1] > -1] | 58,425 |
def gen_stats_grouped_accum(_, group_type):
"""
Args:
_: Http Request (ignored in this function)
group_type: Keyword defining group label (day,month,year)
Returns: Activities grouped by (day or month or year) wrapped on response's object
"""
error_messages = []
success_messages = []
status = HTTP_200_OK
... | 58,426 |
def ClassWeightedLabelSmoothingLoss(real,pred,weights,vocab_size,epsilon):
"""
pred (FloatTensor): batch_size x seq_len x vocab_size
real (LongTensor): batch_size x seq_len
weights (FloatTensor): vocab_size
"""
real = tf.cast(real,tf.int32)
real_onehot = tf.one_hot(real,depth=vocab_size)
... | 58,427 |
def lanczos(A, b, n, m, conn):
"""
A: n X n matrix
b: initial vector
m: number of steps
"""
beta = "beta"
v = ["v%s" % i for i in range(m+2)] # TODO: why this fixed?
v_tmp = "v_tmp"
alpha = "alpha"
create_vector_or_matrix(beta, conn) # just empty
for v_table in v:
c... | 58,428 |
def find_spots(input_path, output_path, intensity_percentile=99.995, filter_width=2, small_peak_min=4, small_peak_max=100,
big_peak_min=25, big_peak_max=10000, small_peak_dist=2, big_peak_dist=0.75, block_dim_fraction=0.25,
spot_pad_pixels=2, keep_existing=False):
"""
Find and keep... | 58,429 |
def map_legislators_to_state(graph, legs):
"""Create graph with legislators connected to their states."""
delete(graph)
nodes = {}
for leg in legs:
if leg.official_name:
name = leg.official_name
else:
name = '{} {}'.format(leg.first_name, leg.last_name)
te... | 58,430 |
def get_compilation_step_args(session, task):
"""Prepare arguments passe to each compilation step."""
latex_document = _get_node_from_dictionary(
task.depends_on, session.config["latex_source_key"]
).value
compiled_document = _get_node_from_dictionary(
task.produces, session.config["late... | 58,431 |
def persistent_q_learning(
q_tm1: Array,
a_tm1: Numeric,
r_t: Numeric,
discount_t: Numeric,
q_t: Array,
action_gap_scale: float,
stop_target_gradients: bool = True,
) -> Numeric:
"""Calculates the persistent Q-learning temporal difference error.
See "Increasing the Action Gap: New Opera... | 58,432 |
def preprocess_data(tokenizer, task):
"""Preprocess dataset to test."""
log.info('Loading dev data...')
if task == 'QA':
# question_answering
batchify_fn = nlp.data.batchify.Tuple(
nlp.data.batchify.Stack(),
nlp.data.batchify.Pad(axis=0, pad_val=vocab[vocab.padding_to... | 58,433 |
def do_with_retry(func, *args, **kwargs):
""" Tries a function 3 times using exponential backoff
according to Google API specs. Optional kwargs:
`_attempts` - override the number of attempts before giving up.
`_catch` - tuple of exception types used in `except types as e`.
"""
MINIM... | 58,434 |
def lightFalloff(constant, linear, quadratic):
"""Sets the attenuation coefficients for light sources defined afterwards."""
attrib.lightFalloff = (constant, linear, quadratic) | 58,435 |
def to_int(s):
"""convert a string to an integer with PRECISION"""
assert isinstance(s, str) # don't convert twice!
result = int(float(s) * PRECISION)
return result | 58,436 |
def cast(value):
"""
Casts a RETS value into a Python data type
Since RETS servers can return non-Boolean strings (like 'yes' or 'no') or
numeric values (namely 0 or 1) for Booleans, these values are left alone
and are NOT cast into Python Booleans. Application developers should
decide on a cas... | 58,437 |
def submit_txn_sold():
"""
Endpoint to create a new transaction via our application.
"""
guid = request.form["guid"]
fish = fetch_fish(guid)
if fish == None:
# Error looking up fish. It might not exist?
print("Fish is None")
return redirect('/')
lastConsumption = fi... | 58,438 |
def folder_exists(folder_path):
"""Checks if a folder exists"""
return os.path.exists(folder_path) | 58,439 |
def check_waiting_list(username):
"""Check username's waiting list to crawl more
Args:
app context, username
Returns:
None
"""
user = User.objects(username=username).first()
if user.is_crawling == 1:
return
User.objects(username=username).update_one(set__is_crawling=1... | 58,440 |
def validate_calendar_date(date_to_validate):
"""Checks to see if date (yyyy, yyy-mm, or yyyy-mm-dd) is a
valid Gregorian calendar date.
"""
parts = str(date_to_validate).split('-')
if len(parts) == 3:
year = parts[0]
month = parts[1]
day = parts[2]
if len(parts) == 2:... | 58,441 |
async def async_setup(hass, config):
"""Set up the updater component."""
if "dev" in current_version:
# This component only makes sense in release versions
_LOGGER.info("Running on 'dev', only analytics will be submitted")
conf = config.get(DOMAIN, {})
if conf.get(CONF_REPORTING):
... | 58,442 |
def ListMessagesMatchingQuery(service, user_id, query=''):
"""List all Messages of the user's mailbox matching the query.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
query: String used to filter me... | 58,443 |
def calibrate_camera(nx, ny, basepath):
"""
:param nx: number of grids in x axis
:param ny: number of grids in y axis
:param basepath: path contains the calibration images
:return: write calibration file into basepath as calibration_pickle.p
"""
objp = np.zeros((nx*ny,3), np.float32)
o... | 58,444 |
def convert_time(t):
"""Takes epoch time and translates it to a human readable version"""
return time.strftime('%Y-%m-%d', time.localtime(t)) | 58,445 |
def convert(
value: typing.Any,
*,
schema: oa_types.Schema,
read_only: typing.Optional[bool] = None,
) -> types.TOptObjectDict:
"""
Convert object schema value to dictionary.
Args:
value: The value to convert.
schema: The schema for the value.
read_only (optional): W... | 58,446 |
def test_create_invalid_token(client, valid_upload_file_patcher):
"""
Test that a bad token results in 401
"""
fake_jwt = "1.2.3"
valid_upload_file_patcher["access_token_mock"].side_effect = HTTPException(
HTTP_403_FORBIDDEN, "bad token"
)
data = {
"file_name": "test.txt",
... | 58,447 |
def getuniqname(base, ext, pre=""):
"""Returns a unique random file name at the given base directory. Does not
create a file."""
while True:
uniq = op.join(base, pre + "tmp" + str(uuid.uuid4())[:6] + ext)
if not os.path.exists(uniq):
break
return op.normpath(uniq) | 58,448 |
def _get_proto_summaries(
proto_expressions
):
"""Gets the proto summaries."""
result = [] # type: List[ProtoRequirements]
for expr in proto_expressions:
def get_summary(tensor_of_protos, desc):
for summary in result:
if id(summary.tensor) == id(
tensor_of_protos) and summary.d... | 58,449 |
def singleNumber(nums: List[int]) -> int:
"""
思路:排序,哈希,位运算(异或) 0^1 = 1, 1^1 = 0
"""
# n = 0
# for val in nums:
# n ^= val
# return n
return reduce(lambda x, y: x ^ y, nums) | 58,450 |
def calc_latent_heat(model, pos):
"""
Calculate latent heat.
Latent heat is set to the latent heat of sublimation for snow covered
surfaces, and to the latent heat of vaporization elsewhere.
Parameters
----------
model : OpenAmundsen
openAMUNDSEN model instance.
pos : ndarray(... | 58,451 |
def run(fips_dir, proj_dir, args) :
"""run the get verb"""
if len(args) > 0 :
name = args[0]
# check project registry to resolve git url
if registry.exists(fips_dir, name) :
url = registry.lookup_url(fips_dir, name)
log.info("registry lookup: {} => {}".fo... | 58,452 |
def main_document(args):
"""Handle document subcommand."""
project = get_project()
for job_id in find_with_filter(args):
job = _open_job_by_id(project, job_id)
if args.pretty:
pprint(job.document(), depth=args.pretty)
else:
print(json.dumps(job.document(), ind... | 58,453 |
def getPort():
"""
Retreives the current TCP port.
Returns:
hostIP(str): Current TCP port
"""
return port | 58,454 |
def SABDL(cpu_context: ProcessorContext, instruction: Instruction):
"""Signed absolute difference long (vector form)"""
logger.debug("%s instruction not currently implemented.", instruction.mnem) | 58,455 |
def main():
"""
video super resolution inference
"""
acl_resource = AclLiteResource()
acl_resource.init()
input_video_name = 'low_resolution.mp4'
input_dir = '../data'
scale = 4
num_frames = 5
set_file = 'test.json'
batch_size = 1
output_dir = '../out'
output_video_n... | 58,456 |
def setup_prior(prior=None, num_causes=None):
"""Setup for prior array
Parameters
----------
prior : array_like, optional
Prior distribution to use. If not specified, each cause bin will be
assigned an equal probability (default is None, and uniform prior will
be used).
num_... | 58,457 |
def data_upgrades():
"""Add optional data upgrade migrations here"""
# TODO: update this once data is gathered about how to fix
# existing global inclusions as they do not have ref to a file
pass | 58,458 |
def get_intact_complex_portal_xrefs_df() -> pd.DataFrame:
"""Get IntAct-Complex Portal xrefs."""
df = _get_complexportal_df()
df['source_ns'] = 'intact'
df['target_ns'] = 'complexportal'
df['source'] = COMPLEXPORTAL_MAPPINGS
df = df[['source_ns', 'source_id', 'target_ns', 'target_id', 'source']]... | 58,459 |
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return tf.cast(image, tf.float32) * 255, label | 58,460 |
def valid_box(box, host_extent):
"""Returns True if the entire box is within a grid of size host_extent.
input arguments (unmodified):
box: numpy int array of shape (2, 3)
lower & upper indices in 3 dimensions defining a logical cuboid subset of a 3D cartesian grid
in python protocol... | 58,461 |
def spec_stich_n_norm(spec, wave, cont, sig):
"""This stitches and continuum normalises CARMENES E2DS spectra into 1D spectra for use in
molecfit.
N. Borsato - 24-02-2021"""
import numpy as np
from astropy.io import fits
from scipy.interpolate import interp1d
#These arrays will be filled w... | 58,462 |
def average(self, key_selector=None):
"""Computes the average of an observable sequence of values that are in
the sequence or obtained by invoking a transform function on each
element of the input sequence if present.
Example
res = source.average();
res = source.average(lambda x: x.value)
... | 58,463 |
def disparate_impact_remover(structured_data):
"""
Perform disparate impact removal from dataset and convert to pandas dataframe.
Parameters:
aif_standard_data (aif360.datasets.standard_dataset.StandardDataset): Structured dataset.
Returns:
data_transf_df (pandas dataframe): Pandas dat... | 58,464 |
def teardown_module(module):
"""
Delete necessary files.
"""
os.chdir("..")
rmtree("temp_pseudocap", ignore_errors=True) | 58,465 |
def PyDateTime_DATE_GET_SECOND(space, w_obj):
"""Return the second, as an int from 0 through 59.
"""
try:
return space.int_w(space.getattr(w_obj, space.newtext("second")))
except OperationError:
return 0 # see comments in PyDateTime_DATE_GET_HOUR | 58,466 |
def get_market_tops(symbols=None, **kwargs):
"""
Top-level function to obtain TOPS data for a symbol or list of symbols
Parameters
----------
symbols: str or list, default None, optional
A symbol or list of symbols
kwargs:
Additional Request Parameters (see base class)
"""
... | 58,467 |
def has_all_params_ortho(**params) -> bool:
""" Returns True, if all 12 keys of an orthotropic material are provided."""
return len(missing_params_ortho(**params)) == 0 | 58,468 |
def hgw_init():
"""Instantiate all the needed objects and setups references between them."""
collector = DataCollector()
cabinet = FilingCabinet()
broker = MessageBroker()
adc = AsynchronousDataCarrier()
sdc = SynchronousDataCarrier()
# NOTE: collector -> cabinet <-> broker <-> carrier
collector.cabinet = ca... | 58,469 |
def piechartgrid(x='None', y='None', data='None', legendmode ='on', legendposition = 'auto',
subfigsize=(2,2), dpi=100, latex=True, **kwargs):
"""Generates a of pie charts for categorial data. Based on the unique values in dataframe columns ``x`` and ``y`` the grid of subplots is constructed
and the associate... | 58,470 |
def fix_curie(curie:str) -> str:
"""
Biothings explorer has some very weird curie prefixes, like "HP:HP:0012092"
and "MESH.DISEASE:ICD10CM:E11.8". This method chooses the first prefix that
appears in the response of the bioentities endpoint. If it can't fix the
curie then it returns it.
Example... | 58,471 |
def draw():
"""
Redraw the current figure.
This is used to update a figure that has been altered, but not
automatically re-drawn. If interactive mode is on (via `.ion()`), this
should be only rarely needed, but there may be ways to modify the state of
a figure without marking it as "stale". P... | 58,472 |
def answer(request, question_id):
"""
Add an answer to a question
"""
question = get_object_or_404(Question, pk=question_id)
try:
answer_text = request.POST.get('answertext')
if answer_text:
# check to make sure that a new answer was entered and then save it
... | 58,473 |
def test_wrong_intervals(app, es):
"""Test aggregation with interval > index_interval."""
with pytest.raises(ValueError):
StatAggregator('test-agg', 'test', es,
interval='month', index_interval='day') | 58,474 |
def map_genome_events(time, domains, header):
"""Map a genome's properties to its state
Args:
time: time of the current state
domains: dictionary of the genome. keys are gene names, values are the genome objects
header: csv header to make sure we have the values in the right order
Re... | 58,475 |
def replace_check_sum(data):
"""
data[2:-2]のチェックサムを計算し
data[-2:]を置き換える
@param data データ。4バイト以上の長さが必要
@return 最終2バイトをチェックサムに置き換えたデータ
"""
cksum = 0
for i in range(2, len(data) - 2):
cksum += data[i]
return data[:-2] + pack('BB', cksum % 256, cksum // 256) | 58,476 |
def conv3x3(in_channels, out_channels, stride=1, padding=1, dilation=1):
"""3x3 convolution"""
return nn.Conv2d(
in_channels,
out_channels,
kernel_size=3,
stride=stride,
padding=padding,
dilation=dilation,
bias=False,
) | 58,477 |
def set_event_type(request, event_id):
"""
Set event type. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param event_id: The ObjectId of the event to update.
:type event_id: str
:returns: :class:`django.http.HttpRes... | 58,478 |
def test_pedido_confirmation_view_permissions(
unauthenticatedClient,
userClient,
adminClient,
confirmation_url,
user,
admin
):
"""Testa as permissões na confirmation view da api dos pedidos"""
res = unauthenticatedClient.post(confirmation_url(0))
assert res.status_code == status.HTT... | 58,479 |
def rect(x: np.ndarray) -> np.ndarray:
"""
Rectangle function.
"""
try:
return np.array(
[
1.0 if (x_i < 0.5 and x_i > -0.5) else 0.
for x_i in x
]
)
except:
return 1.0 if (x < 0.5 and x > -0.5) else 0. | 58,480 |
async def challenge(msg, mobj):
"""
The Challenge
Picks a random Dota 2 hero to play and gives you 3 items to work towards
Optional: supply a hero and get the 3 items to play (sd/ap/rd applicable)
Example: !challenge
-> Bloodseeker: Guardian Greaves, Abyssal Blade, Dagon
"""
ms... | 58,481 |
def saveFileInTag(soup, pagefolder, url, session, tag2find='img', inner='src'):
"""saves on specified `pagefolder` all tag2find objects"""
# count for files that doesn't has a filename
count = 0
# store the url of all downloaded files, so that we won't download duplicate files
# key = url, value =... | 58,482 |
def generate_pydot_graph(root, visibility_level):
"""
Generate the pydot graph - this is usually the first step in
rendering the tree to file. See also :py:func:`render_dot_tree`.
Args:
root (:class:`~py_trees.behaviour.Behaviour`): the root of a tree, or subtree
visibility_level (:clas... | 58,483 |
def upload_metadata_api():
"""
Upload the metadata.csv file to a specific folder
data = {'folder_name': 'desired_name'}
files = {'metadata': open('metadata.csv'), 'rb')}
"""
folder_name = request.form.get('folder_name', None)
if not folder_name:
app.logger.warning('No folder_name pr... | 58,484 |
def _lookahead(param, lookahead_ema, step, beta_lookahead=0.5, lookahead_every_nth_iter=4):
"""lookahead at the param level instead of group level"""
condition = step % lookahead_every_nth_iter < 0.5 # == 0. but inexact to deal with roundoffs
lookahead_ema = jnp.where(condition, beta_lookahead*lookahead_ema... | 58,485 |
def test_rsync_source_dir(gearman_worker):
"""
Verify the source directory exists for a rsync server transfer
"""
return_val = []
# Create temp directory
tmpdir = tempfile.mkdtemp()
rsync_password_filepath = os.path.join(tmpdir,'passwordFile')
try:
logging.debug("Saving rsync... | 58,486 |
def load_pickle(h5f, safe=True):
""" Deserialize and load a pickled object within a hickle file
WARNING: Pickle has
Parameters
----------
h5f: h5py.File object
safe (bool): Disable automatic depickling of arbitrary python objects.
DO NOT set this to False unless the file is from a trusted sou... | 58,487 |
def sheet_to_excel(sheet_name, csv_path):
"""Export the Google Sheet."""
sheet_download(
sheet_name,
csv_path,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') | 58,488 |
def dataset_using_generator(samples, reader, **kwargs):
"""
A generator class which wraps samples so that they can
be used with tf.data.Dataset.from_generator
Parameters
----------
samples : [:obj:`object`]
A list of samples to be given to ``reader`` to load the data.
reader : :obj:... | 58,489 |
def getBarcodesFromSnapSimple(fname):
"""Read barcodes from a snap file
Attributes:
fname - a snap-format file
Return:
a dictionary contains barcode without qc
"""
try:
f = h5py.File(fname, 'r');
except IOError:
print("error: unable to open fname, check if i... | 58,490 |
def save(arr, filename, key=None, comm=None, **kwargs):
"""
Save function for tar
"""
filename, key = split_filename(filename, key)
mode_suffix = _get_mode(filename)
kwargs = {"comm": comm, **kwargs}
if comm is not None:
check_comm(kwargs["comm"])
with _open_for_saving(filename... | 58,491 |
def yaml_dump_result(obj, stream):
"""Redefinition of yaml.safe_dump with added float representer
The float representer uses float precision of four decimal digits
"""
def float_representer(dumper, value):
text = '{0:.4f}'.format(value)
return dumper.represent_scalar(u'tag:yaml.org,2002... | 58,492 |
def _poly_fit_delta(data_series_in):
"""Given an input Pandas Series (data_series_in) with a PeriodIndex and at
least 3 non-nan values, models the expected last value of the series and
returns the difference between the modeled and actual value.
A linear regression is computed for the input da... | 58,493 |
def scrape_last_patch_change(names, save=True):
"""
Scrapes the last patch in which each champion was changed from League Wiki
and saves them to a csv file, but returns nothing
Parameters
----------
names : pandas series
Contains the champion names as strings in alphabetical ord... | 58,494 |
def delete_all():
""" Delete all predictions in the database.
Args:
None.
"""
return Prediction.objects.all().delete() | 58,495 |
def sig_handler(signum, frame):
"""USR1 signal handler that requeues the job."""
del frame # Unused.
logging.warning('Signal handler called with signal %s', signum)
prod_id = int(os.environ['SLURM_PROCID'])
if 'SLURM_ARRAY_JOB_ID' in os.environ:
job_id = '%s_%s' % (os.environ['SLURM_ARRAY_J... | 58,496 |
def strip_readonly(model: ModelNormal):
"""Strip read only fields before sending to server"""
for field in [
elt
for elt in model.attribute_map.values()
if hasattr(model, elt)
and isinstance(
getattr(model, elt),
(models.Id16ReadOnly, models.Id16ReadOnlyNu... | 58,497 |
def get_stock_rack_assembler(entity, rack_barcodes, excluded_racks=None,
requested_tubes=None, include_dummy_output=False,
**kw):
"""
Factory method generating a stock rack assembler (XL20 worklist generator)
tool for the passed entity. The generator... | 58,498 |
def wait(duration=-1):
"""Resumes capture replay or sleeps for duration.
If `duration` is `0`, then waits forever.
"""
if duration < 0:
while True:
_wait(0.1)
if is_end():
break
else:
_wait(duration) | 58,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.