content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def suite_host():
"""Hostname of agent under test."""
return os.environ.get("SUITE_HOST", "localhost") | e95eafeae82ac5e8bc31959f79ec8198028c4d64 | 644,706 |
def HImass2flux(m_hi, D):
"""
Converts HI masses into observed fluxes, depending on the distance
Input
-----
M : float or ndarray
HI mass in solar masses
D : float
Distance in Mpc
Returns
-------
S : Flux in Jy km/s
"""
S = m_hi / 2.36e5 / D**2
return S | 028ed2f49b66fe560df4455f59cc39a840114499 | 644,707 |
def percent_invert(value, total):
"""
Convert avail and total values to percent
"""
if total:
v = (float(total) - float(value)) * 100.0 / float(total)
if v >= 0.0:
return v
return 100.0 | 082cf70e682c1dc30925e49b2eeadf13eebf1dd5 | 644,708 |
import sys
def override_obj(obj, obj_name):
"""
Override object name with name given in obj_name option.
"""
if type(obj_name) is list and len(obj_name) == 1:
return obj_name[0]
elif type(obj_name) is list and len(obj_name) > 1:
sys.exit("*** ERROR: obj_name requires only one name,... | d5899fd5438a6d78c581d329d86b8b0893abdab2 | 644,710 |
def weekend_feature(date, num):
"""One Hot encoding for weekend feature
One Hot encoding for the weekend feature of a given sample. takes a 1
as the value if the feature is computed, 0 otherwise.
Parameters
----------
data: pd.Dataframe
input dataframe containing the time series.
... | fb5bc6258b8327bce61dab09c14fc7964bf9c5b5 | 644,711 |
import yaml
def get_rule_set(args):
"""Read and parse the config file at the location given when the
linter script is run.
Parameters
----------
args : argparse.Namespace
Arguments input when script is called from the console
Returns
-------
dict
Contains structured d... | 335b5e73c721f8ca276690444ede1f88fd33c2e9 | 644,712 |
def use_images_as_annotations(ibs, gid_list, name_list=None, nid_list=None,
notes_list=None, adjust_percent=0.0,
tags_list=None):
""" Adds an annotation the size of the entire image to each image.
adjust_percent - shrinks the ANNOTATION by percentage o... | 84712e6463d72668f657e327a9bc1c98d934690a | 644,713 |
def spam():
"""Example spam message using SpamAssassin's GTUBE message."""
return (
b"Subject: Test spam mail (GTUBE)\n"
b"Message-ID: <GTUBE1.1010101@example.net>\n"
b"Date: Wed, 23 Jul 2003 23:30:00 +0200\n"
b"From: Sender <sender@example.net>\n"
b"To: Recipient <recip... | 5633a59c487575b84230d90356eb4e5e167dff60 | 644,714 |
from datetime import datetime
def current_season():
"""Get Current Season."""
today = datetime.today()
today = datetime(today.year, today.month, today.day)
Y = today.year
seasons = [
("winter", (datetime(Y, 1, 1), datetime(Y, 3, 20))),
("spring", (datetime(Y, 3, 21), datetime(Y, 6,... | 96b450d33586d81ec0e0495b48d0451fc293f626 | 644,715 |
def str_range(start, end):
"""get range with string type"""
return [str(i) for i in range(start, end)] | 7ed8aab00ed414a58439a6ebc5a196ac1ff24ca8 | 644,716 |
def dichotomize(data, tables):
"""
-> perform dichotomization on data, using tables.
-> data is a matrix
-> tables is a listof disjonctif table (i.e 2D array)
-> return a new dichotomized matrix
"""
data_new = []
for vector in data:
variable_index = 0
vector_new = []
for scalar in vector:
scalar_new = ... | d14722ff912c8cfbd8e449f78cf127c4f4d490e8 | 644,717 |
def get_direction(connection_byte, connection_id):
"""given a connection byte and a connection id, which direction is this connection?
the 0th connection of $5 is SOUTH and the 1st connection is EAST"""
connection_options = [0b1000, 0b0100, 0b0010, 0b0001]
results = ["NORTH", "SOUTH", "WEST", "EAST"]
... | 33f50da36a3193fc1c1e230dad9e92310c839e16 | 644,718 |
import requests
def do_http_get(request_url: str):
"""helper method to do http requests"""
resp: requests.Response = requests.get(request_url)
if resp.ok:
return resp.json()
else:
raise ConnectionError | 837bb226c9266752a241c01b349891cf4c1cb293 | 644,719 |
def get_moves(pos, xs, ys, step):
"""
Get the 5 possible moves from a position given a constant speed.
(left, right, forward, back, stay still)
:param pos:
:param xs:
:param ys:
:param step:
:return:
"""
moves = []
for dx, dy in [(-step, 0), (step, 0), (0, -step), (0, step), ... | 31d3f6d54da0243370cfe649075cd12c6e2702bc | 644,720 |
from typing import Sequence
def apply_weights(values: Sequence[float], weights: Sequence[float]):
"""
Returns values[0] * weights[0] + values[1] * weights[1] + ... + values[n] * weights[n]
"""
return sum([v[0] * v[1] for v in zip(values, weights)]) | 22e1e2decc29a2c5cdf0d34d97cb70cd3e144d85 | 644,721 |
import re
def headers(corpus):
"""
Places headers up to h6 into the corpus.
"""
for i in range(3, 1, -1):
corpus = re.sub(r'(^|\n)'+f'({"#"*i})'+'[ \t]+([^\n]+)',
fr'\g<1><h{i+1}>\g<3></h{i+1}>', corpus)
return corpus | cb793d3bc432b7981193770dd6d1b55a01e7828a | 644,722 |
import math
def move_time(move, eres):
""" Calculates the time it takes to do a move.
Calculates how long it will take to complete a move of the motor. It
is assumed that the motor will decerate to a stop for the end of the
move as opposed to keep moving at velocity.
Everything is in motor units... | 7e71f4c484a9b5553916cc541b4ceaee658fb814 | 644,723 |
def hexify(i, digits=4):
""" convert an integer into a hex value of a given number of digits"""
format_string = "0%dx" % digits
return format(i, format_string).upper() | 8ede435664c629bf5ca43e5211a4ddb5d369bac1 | 644,725 |
def splitIndentDeepness(text):
"""
Return tuple (d, t) where d is deepness of indentation and t is text
without the indentation.
"""
pl = len(text)
text = text.lstrip()
return (pl-len(text), text) | 8a16f023c5d66a53a0f2afe86e6832c3363d66af | 644,726 |
def mjd2met(mjd):
"""
Converts Modified Julian Day in Mission Elapsed Time (MET, in seconds).
Cf. http://fermi.gsfc.nasa.gov/ssc/data/analysis/documentation/Cicerone/Cicerone_Data/Time_in_ScienceTools.html
to see how the time is handled in the Fermi Science Tools.
Input: time in MJD (fraction of a... | 9721ebe622af3a9fe58176a292dd77469095d617 | 644,727 |
import socket
def is_ip_addr(addr):
"""Returns True if an address is an ipv4 address or an ipv6 address based on format. False otherwise."""
for addr_type in [socket.AF_INET, socket.AF_INET6]:
try:
socket.inet_pton(addr_type, addr) # not present on python 2.7 on Windows
return... | 8304db91e470f6391a265513e1abd8f72cf6142c | 644,729 |
from typing import Union
def is_union(etype) -> bool:
""" Determine whether etype is a Union """
return type(etype) == type(Union) | 6bb449b336eeb3e94501781ef39de3ef66a7110f | 644,730 |
def nullable_attrgetter(key, default):
"""To allow sorting on nullable field with default value"""
def getter(item):
return getattr(item, key) or default
return getter | 995495f97c6adc115829c518a44b5c48c835f5c5 | 644,733 |
def figsize(relwidth=1, aspect=.618, refwidth=6.5):
"""
Return figure dimensions from a relative width (to a reference width) and
aspect ratio (default: 1/golden ratio).
"""
width = relwidth * refwidth
return width, width*aspect | 496a5377bb8ffa9bebe4d1cd6080013b70742bd1 | 644,734 |
def trim_urls(attrs, new=False):
"""Bleach linkify callback to shorten overly-long URLs in the text.
Pretty much straight out of the bleach docs.
https://bleach.readthedocs.io/en/latest/linkify.html#altering-attributes
"""
if not new: # Only looking at newly-created links.
return attrs
... | 57558ab63f042708c88cabe8c9aee94c4237c05c | 644,735 |
def format_error_code(errorCode: int, descriptions: list) -> str:
"""Emergency error code -> description.
Args:
errorCode: Error code to check.
descriptions: Description table with (code, mask, description) entries.
Returns:
Text error description.
"""
description = 'Unknow... | cb13d0f4b338302966db883d69acd26cf1481e74 | 644,736 |
import os
def _chpl_home():
"""Calculate and return $CHPL_HOME defaulting to root of repo/install."""
repo_root = os.path.abspath(os.path.join(
os.path.dirname(__file__), '../..'))
return os.environ.get('CHPL_HOME', repo_root) | b644767dfab0f9bb58c4c7df55d74b29fab202c8 | 644,737 |
import re
def is_string_id(string_id):
"""Checks if a string is a valid user ID string"""
if re.match('<@![0-9]+>', string_id):
return True
return False | 930f106a624f2c815c9551aa4a1a8eaebe6082ee | 644,738 |
def check_chrom_bounds(gene, slack, bounds):
"""
:param gene:
:param slack:
:param bounds:
:return:
"""
s, e = int(gene[1]), int(gene[2])
assert s >= 0, 'Gene start invalid: {}'.format(s)
assert e > 0, 'Gene end invalid: {}'.format(e)
if gene[5] == '+':
if bounds['start']... | 8334638e70776c8311f237462f0a480c54ca4d4a | 644,741 |
def get_plural_name(name):
"""
将单数形式的名字转换为复数形式
:param name:
:return:
"""
plural_name = name
if plural_name[-1] == 'y':
plural_name = '%sies' % plural_name[:-1]
elif plural_name[-1] == 's':
plural_name = '%ses' % plural_name
else:
plural_name = '%ss' % plural_name
return plural_name | 9eca1182eaf238752488df27d6ffc2aedc5aff01 | 644,742 |
import subprocess
def get_devices():
"""
获取连接电脑的手机设备号列表
可能输出的信息
* daemon not running; starting now at tcp:5037
* daemon started successfully
List of devices attached
9598552235004UD device
or
List of devices attached
9598552235004UD device
:return: 手机设别号list结构体
"""... | 5a7c1b8e3b19e5c535718332a5d305bc2e692515 | 644,744 |
def process_other_transcript(contents):
"""
process all other transcript output
"""
checked = contents.count('<strong>') > 0
context = {'text': contents, 'checked': checked }
return context | 7455d6545df52a31c3c551c3fe44c764f0528c27 | 644,745 |
def find_du_based_on_ip(ip, functions):
"""
This method finds a du id associated to an ip
"""
for vnf in functions:
if 'vnfr' not in vnf.keys():
continue
vnfr = vnf['vnfr']
dus = []
if 'virtual_deployment_units' in vnfr.keys():
dus = vnfr['virtual... | 78e83888e1a61ea6d4a230bd6a33fdbaa1d05402 | 644,746 |
def parse_list(list_string):
"""
Parses IPv6/prefix/route list string (output of wpanctl get for properties WPAN_IP6_ALL_ADDRESSES,
IP6_MULTICAST_ADDRESSES, WPAN_THREAD_ON_MESH_PREFIXES, ...)
Returns an array of strings each containing an IPv6/prefix/route entry.
"""
# List string example (get(W... | b9088f0e36c7f4d21f624c6838905bd9f52d5424 | 644,747 |
def rule_enclosing(
value: float, layer1: str, layer2: str, angle_limit: float = 90
) -> str:
"""Layer1 must be enclosed by layer2 by value.
checks if layer1 encloses (is bigger than) layer2 by value
"""
error = f"{layer1} enclosing {layer2} by {value}um"
return (
f"{layer1}.enclosing({l... | 1f941ab3f19095774819623fa2d394c32040cc3e | 644,748 |
def find_overlapping_ranges(shard_ranges):
"""
Find all pairs of overlapping ranges in the given list.
:param shard_ranges: A list of :class:`~swift.utils.ShardRange`
:return: a set of tuples, each tuple containing ranges that overlap with
each other.
"""
result = set()
for shard_ra... | 66c07b8311a66de2f42cce61928a47cb3d6144a9 | 644,749 |
def remote_resources_data_to_metax(resources):
"""
Converts external resources from qvain light schema to metax schema.
Arguments:
data {object} -- External resources.
Returns:
object -- Object containing external resources array that complies with Metax schema.
"""
metax_remo... | acd63f8b5508d144abe9dfcf4d8d6c1493a16ee5 | 644,750 |
def lightness_glasser1958(Y, **kwargs):
"""
Returns the *Lightness* :math:`L^*` of given *luminance* :math:`Y` using
*Glasser et al. (1958)* method.
Parameters
----------
Y : numeric
*luminance* :math:`Y`.
\*\*kwargs : \*\*, optional
Unused parameter provided for signature c... | f1af67296158c0b6c7589f887df51f17ac700daf | 644,751 |
def proportional(nseats, votes_dict):
"""assign n seats proportionaly to votes using Hagenbach-Bischoff quota
:param nseats: int number of seats to assign
:param votes: iterable of int or float weighting each party
:result: list of ints seats allocated to each party
"""
items = votes_dict.items(... | 36300d98424501134040728d75110159bfa3179d | 644,752 |
def n_params(model):
"""Return the number of parameters in a pytorch model.
Args:
model (nn.Module): The model to analyze.
Returns:
int: The number of parameters in the model.
"""
pp = 0
for p in list(model.parameters()):
nn = 1
for s in list(p.size()):
... | 02bf6c5cf4c3a8cbbfce2bdf1525bcdc73aac686 | 644,754 |
def _is_namedtuple(x):
"""Duck typing test for namedtuple factory-generated objects."""
return isinstance(x, tuple) and hasattr(x, '_fields') | 434eb3e17f0ad57157061819eae96983ba8e1671 | 644,755 |
def as_int(raw):
"""Return an int for the given raw value.
Return None for "falsey", non-zero values.
"""
if raw == 0:
return 0
elif not raw:
return None
else:
return int(raw) | c4048c4ec14251b61a9101d398b4f9a5a2920e5b | 644,756 |
import random
def Jitter(values, jitter=0.5):
"""Jitters the values by adding a uniform variate in (-jitter, jitter)."""
return [x + random.uniform(-jitter, jitter) for x in values] | 3ef6e8e85884b2b6ec472b1daa8bbe2d7450c481 | 644,757 |
from typing import OrderedDict
def alphabetically_sorted_dict(d):
"""
Returns a dictionary with all keys recursively sorted alphabetically
"""
ordered = OrderedDict()
for k, v in sorted(d.items()):
if isinstance(v, dict):
ordered[k] = alphabetically_sorted_dict(v)
else:... | 071d761d4d660480b34da954d3d0410bfacc5dfd | 644,758 |
def ensure_collection(value, collection_type):
"""Ensures that `value` is a `collection_type` collection.
:param value: A string or a collection
:param collection_type: A collection type, e.g. `set` or `list`
:return: a `collection_type` object containing the value
"""
return collection_type((v... | 9afa29fd0672d7ab2e65484fdd0c811781fb9f82 | 644,759 |
def add_srt_to_meta(meta_list, srt_dict):
"""
Combindes the metadata and srt dictionarys.
:param meta_list A list of metadata dictionarys from get_episode_metas
:param srt_dict A dictionary of ID, SRT
"""
new_list = [] # Make a new array to avoid pass my refrence override
for elem... | 3d80176e9e5a134f843023d574a1d5d587141902 | 644,760 |
def exclude_ancestor_filediffs(to_filter, all_filediffs=None):
"""Exclude all ancestor FileDiffs from the given list and return the rest.
A :pyclass:`~reviewboard.diffviewer.models.filediff.FileDiff` is considered
an ancestor of another if it occurs in a previous commit and modifies the
same file.
... | 3fa5e39f136c4b29f1d6fe1eecbba2d7bf12f497 | 644,762 |
import random
def random_within_range(num_bytes, max_bytes=None):
"""Return a random int within range.
- If only ``num_bytes`` is set, return ``num_bytes``
- If both ``num_bytes`` and ``max_bytes`` are set, return random int within between
``num_bytes`` and ``max_bytes`` (including).
"""
r... | 4d87a735e7461464a24395a591ec37a86da4b3f1 | 644,763 |
from typing import Dict
def dict_diff(d1: Dict, d2: Dict) -> Dict:
"""Compute the set difference `d1` - `d2`"""
def flatten(obj):
if isinstance(obj, (list, tuple)):
return tuple([flatten(o) for o in obj])
elif isinstance(obj, dict):
return tuple([(flatten(k), flatten(v... | d5482cc144d9aee3abdf28c5d370ad6d405c3338 | 644,764 |
def cleanup(run_dir):
"""
Cleans up the run directory.
"""
# Remove param_plots folder if empty
histo_dir = run_dir.joinpath('histogram_plots')
if histo_dir.is_dir() and not any(histo_dir.iterdir()):
histo_dir.rmdir()
# If run_dir is empty because there aren't enough good pixels, re... | 6c180dc2a3125e2a8c5074e0a5aee42c3473f36d | 644,766 |
def _calculate_area(p, q, r):
""" Calculates the area of the triangle by its vertex coordinates.
Helper method for the _calculate_distortion_energy() and compute_one_csd() methods.
It calculates the area of the triangle spanned by three points in R^2 or R^3.
Parameters
----------
p/q/r : tripl... | 94b4573399ecbcf1b4eec7910d5af0e445b8c1ee | 644,768 |
import glob
import shutil
def copy_egg_info(dest_dir):
"""Copies the .egg-info directory to the specified location.
Args:
dest_dir: str. The destination directory.
Returns:
0 on success, 1 on failure.
"""
# Remove any trailing slash on the destination directory.
dest_dir = dest_dir.rstrip('/')
... | 39edab7773f9d02beac07f58e9eb5191f7f65321 | 644,769 |
def get_headers():
"""
返回请求头信息
:return:
"""
headers = {
'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
}
return headers | 4a694762920d9b246962ab7f8a89cb9dde12be64 | 644,770 |
import numpy
def normalize(x):
"""Normalizes a numpy array by dividing by the sum."""
s = float(numpy.sum(x))
return x / s | 08da2609872600f0928c2c0756b0a396dde4d4b6 | 644,771 |
from typing import Dict
def get_project_config_from_user() -> Dict:
"""
Ask the user for the information for the project config.
Returns: A dictionary with the config for the project, including local_dir, target, remote_dir, and port.
"""
local_dir = input('Path to code_sync on this local machin... | df30648f2ad1f07f4ac29694e3f74c5f56180a7b | 644,772 |
import os
def add_suffix(path, suffix="-0"):
"""
Add suffix to the filename.
add_suffix(".../XX.tif", "Suf") returns ".../XXSuf.tif"
"""
fname, ext = os.path.splitext(os.path.basename(path))
dname = os.path.dirname(path)
return os.path.join(dname, fname + suffix + ext) | f75fdb4ce7c28f297d13f5368fe59aa2d2e4f55c | 644,773 |
import os
def uploadObject(s3, bucket_name, filepath, dst_dir):
"""Upload to s3 Bucket
Args:
bucket_name (str): s3 bucket name
filepath (str): Path to local file that needs to be uploaded
dst_dir (str): Path to s3 bucket
"""
filename = os.path.basename(filepath)
new_path =... | c9417e911c19b94903adb5bbe70ba08d6396fff6 | 644,774 |
def __FindTouchingTrack(t1, endpoint, trackLookup):
"""Find a track connected to the end of another track"""
match = 0
matches = 0
ret = False, False
for t2 in trackLookup[t1.GetLayer()][t1.GetNetname()]:
# The track object can change, this seems like the only
# reliable way to test ... | 3803ddfe562136f7568c6342d0dfd6ef8c2d8ea4 | 644,775 |
def ugly_number(n):
"""
Returns the n'th Ugly number.
Ugly Numbers are numbers whose only prime factors are 2,3 or 5.
Parameters
----------
n : int
represent the position of ugly number
"""
if(n<1):
raise NotImplementedError(
"Enter a valid natural numbe... | b0753801532c7ec34f7eba6cfcdf28f2e7edb66b | 644,776 |
def problem048():
"""
The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
"""
modulo = 10 ** 10
ans = sum(pow(i, i, modulo) for i in range(1, 1001)) % modulo
return ans | e68dfdf7315dc46b26118667299f0c89e3918d91 | 644,777 |
def get_wcs_ctype(wcs):
"""
Get celestial coordinate type of WCS instance.
Parameters
----------
wcs : `~astropy.wcs.WCS`
WCS transformation instance.
Returns
-------
ctype : {'galatic', 'icrs'}
String specifying the coordinate type, that can be used with
`~astr... | 612c5dd5659437a91f35ed984778b74dd4910ab4 | 644,779 |
def create_random_stamp_ids(rnd: int) -> tuple:
"""スタンプ用IDをランダムに生成する
Args:
rnd: 乱数
Returns:
tuple: スタンプセットのパッケージIDとスタンプID
"""
package_id = 11537
sticker_id = 52002749
if rnd == 1:
package_id = 11537
sticker_id = 52002764
elif rnd == 2:
package_id... | b84b96f3b618a9fefd484ad078575d70bbc399ab | 644,780 |
def to_word_indexes(tokens, keyed_vectors, unk=None, fallback_transform=None):
"""Look up embedding indexes for tokens."""
if fallback_transform:
assert unk
unk = keyed_vectors.vocab[unk]
return [
keyed_vectors.vocab.get(
token,
keyed_vectors.v... | b03d17f1c4373ffa909b9fc5982cab664ae4b1f3 | 644,781 |
def multiple(first,second):
"""Return multiplication of the 2 arguments.
Examples
--------
>>> multiple(4,5)
20
>>> multiple(2,1)
2
"""
return first * second | 6e0c997387ff839e7662d3b9e6974a4615e5d90d | 644,782 |
import operator
def _ext_proc_tpls_to_procs(xps):
"""List processors by each priority.
:param xps: A list of (file_extension, processor_cls)
:return: List of [processor_cls]
"""
return sorted((operator.itemgetter(1)(xp) for xp in xps),
key=operator.methodcaller("priority")) | ecc93f6bb6de68f72982329607e00f1f3f8a5274 | 644,783 |
import logging
def WriteToPoolCount(pool_d, rcbc_list,
counts, nSamples, out_prefix, indexes):
"""
Inputs:
pool_d (dict)
rcbarcode (s) => [barcode (str), scaffold (str), strand (str), pos (i)]
rcbc_list (list<str>): We get a list of all the rcbarcodes as they a... | 00e5448bbb773d8a8dc4e0541dc85ae3a1d66e73 | 644,784 |
import os
def chdir(path, **kwargs):
"""change current working directory"""
return os.chdir(path, **kwargs) | 114e058515c23a39efbb7f5286f9a6b74f3ba0dc | 644,785 |
def strategy_expensive(cookies, cps, history, time_left, build_info):
"""
Always buy the most expensive item you can afford in the time left.
"""
#maximum cookies to be able to get in the time left
max_cookies = cookies + cps * time_left
expensive_item = None
expensive_item_cost = ... | bc4e50a93a7ce508688eb37d60b3f8960e6862c7 | 644,786 |
def subtractProductAndSum(self, n):
"""
:type n: int
:rtype: int
82% faster
61% less mem
"""
prod = 1
sum = 0
for i in range(len(str(n))):
sum += (n%10)
prod *= (n%10)
n /=10
return prod - su... | 819095589f0be176054169876aa589e9a9d3ca6b | 644,787 |
def get_manual_finding_report_detail(manual_finding_reports):
"""
Iterate over manual finding report detail from response.
:param manual_finding_reports: manual finding report detail from the response
:return: List of manual finding report elements.
"""
return [{
'ID': manual_finding_re... | 91623bf01f23df31256631b8a7d905afcffb1a4c | 644,788 |
def reverse_str(numeral_str):
"""Reverses the order of a string."""
return numeral_str[::-1] | 0336a1ab5b5252e5f54062bb263d2c7e9682f0a7 | 644,789 |
def read_cols_query(col_names, table_name, schema_name):
"""
Obtain the query to read the columns from a table
:param col_names: (list of strs) list of cols names to read
:param table_name: (str) table name to read from
:param schema_name: (str) schema name of the table
:return:
A stri... | 542bb33dbfc2c7a570fb4bdf652d89ab87c7e20f | 644,791 |
def ds_search_url():
"""
"Creates the URL for the datastore search end-point"
:return: a URL
"""
search_url = "https://www.opendata.nhs.scot/api/3/action/datastore_search"
return search_url | 6d4faf83694a39f770ddefbb3ec7fcf428bd81f9 | 644,792 |
def generate_words_list(texts: list) -> list:
"""Cria uma lista de palavras"""
words_list = []
for text in texts:
words_in_text = text.split()
for word in words_in_text:
if word not in words_list:
words_list.append(word)
return words_list | 3eb1e4ea38cbe9aa3684613014ba948f0f5b2642 | 644,793 |
import configparser
def reset_config():
"""
Resets the Config File. In fact the Config.ini file will be rewritten in total.
:return:
"""
config = configparser.ConfigParser()
config['DATA'] = {
'data_root_directory': 'Data/',
'data_raw_directory': 'Data/Raw',
'data_resul... | b79031e2c9bc9029e9ef794bdc900f993db2642d | 644,794 |
from bs4 import BeautifulSoup
def lyrics_from_letrasmus(html):
"""Extracts lyrics from the html of a webpage of 'letras.mus.br'."""
lyrics = ''
soup = BeautifulSoup(html, 'html.parser')
verses = soup.select('.cnt-letra article p')
for para in verses:
lyrics += para.get_text('\n') + '\n\n... | 24c074bb0e66e6e20c6177c70a037e67a0088736 | 644,795 |
def unflatten_columns (self, columns, delimiter=","):
"""
Compacts data from multiple rows based on cell data.
Parameters
----------
:param columns: (str or List[str]) Name of the column(s) to be used as keys for unflattening.
:param delimiter: (Optional[str]) Separator for the data in the res... | d7fea98ac6dc67bbd15c7bd0287730e6cb68287a | 644,796 |
def confirm(output, default=None):
"""
진행될 내용을 표시하고 유져에게 확인 받기
:return: Boolean
"""
suffix = ('[y/N]', '[Y/n]', '[Y/N]')
default = 1 if default is True else 0 if default is False else 2
while True:
print(output, end=' ')
i = input(suffix[default]).strip().lower()
if len(i) == 0:
if default == 2:
con... | adb5ae0cc7f9be9e88da9b0be2f2f9c951dfe4f0 | 644,797 |
def extract(entrytext,
lchar,
rchar):
"""extracts all the textblocks surrounded by lchar and rchar from
entrytext"""
def indexlist(entrytext,
char):
"""Creates a list of the indexes of segments
to be extracted
"""
rl_temp = [... | 65437c2cdc67b5a891182299ecc8baf1948297e6 | 644,798 |
def normalize_key(key: str):
""" Normalize CSV header values """
key = key.lower().replace('_', '').replace('-', '').replace(' ', '')
return {
'startdatetime': 'start_date_time',
'enddatetime': 'end_date_time',
'resultslocation': 'results_location'
}.get(key, key) | 8e28a82af6d0efee81174d1e2e344b885b156140 | 644,799 |
def VAVL(pa,pb):
""" Van Albada & Van Leer averaging function """
if(pa*pb > 0.0):
e = 1.0e-8
num = ( pa*pa + e*e )*pb + ( pb*pb + e*e )*pa
den = ( pa*pa + pb*pb + 2.0*e*e )
vv = num/den
else:
vv = 0.0
return vv | 9474c4896f21d2e919643d2c38be2a895ccba1f0 | 644,800 |
def reflect(cp, anchor):
"""
Reflect the point `cp` through the anchor.
"""
vec = (cp[0] - anchor[0], cp[1] - anchor[1])
neg = (-vec[0], -vec[1])
return (anchor[0] + neg[0], anchor[1] + neg[1]) | 86ea4cdbd4f23c1d9bdddd54892d11d708749d4b | 644,803 |
import torch
def Jaccard_loss_cal(true, logits, eps=1e-7):
"""Computes the Jaccard loss, a.k.a the IoU loss.
Note that PyTorch optimizers minimize a loss. In this
case, we would like to maximize the jaccard loss so we
return the negated jaccard loss.
Args:
true: a tensor of shape [B, H, W]... | 7e1032c23daee1bed517950274c5188bb5c9508d | 644,804 |
import zlib
def zlib_encode(input,errors='strict'):
""" Encodes the object input and returns a tuple (output
object, length consumed).
errors defines the error handling to apply. It defaults to
'strict' handling which is the only currently supported
error handling for this codec.... | c7ae64666b763e935cc515c44ed1550410846c30 | 644,805 |
def GenerateConfig(context):
"""Generate YAML resource configuration."""
resources = [{
'name': context.env['name'],
'type': 'compute.v1.instanceTemplate',
'properties': {
'properties': {
'machineType': context.properties['machineType'],
'disks': [{
... | 04b9e389947bab69c2ae645ad4b72a2aa5aa9828 | 644,806 |
def getitem(obj, item):
"""Grab the item from the object.
Example usage:
someObj|getitem:key
"""
return obj[item] | 7bac8e8bace8ea1ad79073da9907ac57ed0af039 | 644,807 |
import os
def lambda_handler(event, context):
"""Lambda function which checks if the meta data for the current day is available or not
Parameters
----------
event: dict, required
Input event to the Lambda function
context: object, required
Lambda Context runtime methods and attri... | a6002d21d4ff98814a1c8f422e0fdde3ad611f32 | 644,808 |
import tempfile
import os
import imp
def _tmp_pkg(dirName):
"""
Create a temporary package.
Returns (name, path)
"""
while True:
path = tempfile.mkdtemp(dir=dirName)
name = os.path.basename(path)
try:
imp.find_module(name)
# if name is found, delete... | e249102f67f7e7ec0b086c3c9017afbbaef45cb0 | 644,809 |
def _get_list_traj(trajectory):
"""Return a list of (proxy) snapshots from either a list or Trajectory
Parameters
----------
trajectory : :class:`.Trajectory` or :class:`.list`
trajectory or list to convert into a list of snapshots
Returns
-------
:class:`.list`
list of (prox... | 751fb4a579b0bb54870286e9229703abfb0936de | 644,810 |
def main(data):
"""
Esta función recibe una tupla, dicha tupla contiene un array y una cadena, el objetivo de esta función es analizar cuántas veces se repite la cadena dentro de los elementos del array y también devolvernos la cantidad de elementos del array.
Args:
data (tupla): Contiene como prim... | d65c5de30d852c50ece3a702d2e52640f6e33289 | 644,811 |
def proximaVariable(valor, pos):
"""Extrae la próxima "%variable%" de valor después pos.
Extrae la próxima variable de entorno que esté en la forma "%variable%" dentro de la cadena valor después de la posición pos. Retorna un par de valores, la posición después de la variable encontrada para una futura búsqueda y e... | 350a6470bd2711d71b26c0d8be68eef9764a5ba7 | 644,812 |
def sign(x: float):
"""Retuns 1 if x > 0 else -1. > instead of >= so that sign(False) returns -1"""
return 1 if x > 0 else -1 | e2e9dbc8d6c7fbfbb5e982732bd9d5b0af87b521 | 644,813 |
import os
def _is_subpackage_of(package, parent):
"""A function check if a package is a package imported from environment or a subpackage of a parent package.
Parameters
----------
package : module
The package to check if it's a subpackage of 'parent'
parent : module
A package which had imported 'package' ... | d3f950ecec1a2d58af92e9a7ef7f2b4e22eea54e | 644,814 |
import re
def is_empty_line(line: str):
"""Check if line is empty. Returns True if line contains only whitespaces"""
return bool(re.match(r"\s*\n", line)) | 7c84e416ac29d42de5224004d8ab4c6f3f5c215a | 644,815 |
def is_json_string(text: str) -> bool:
"""
Given an input text, is_json_string returns `True` if it is a valid JSON string, or False otherwise.
The definition of a valid JSON string is set out in the JSON specification available at https://json.org/.
Specifically, the section on strings defines them as: "A string ... | a57408c05e8672f370ede3e7f85cab595e70f082 | 644,816 |
def matches(value, attr_list):
"""Return whether value matches the attribute described by attr_list
Attributes come from mutagen as lists of strings (except for the "path"
attribute). If the value is surrounded by double quotes, we look for exact
matches; otherwise, we join together the attribute list ... | 57f29ee419214c254ca17a769ac3364cd1c00fab | 644,818 |
def cli(ctx, history_id):
"""Returns the state of this history
Output:
A dict documenting the current state of the history. Has the following keys:
'state' = This is the current state of the history, such as ok, error, new etc.
'state_details' = Contains individual statistics for vario... | 9d226b3296c5cc9765c3ba42621029fa7fd64351 | 644,819 |
import struct
def retrieve_message(conn, out_format):
"""Retrieve a message from the client.
Parameters
----------
conn : socket.socket
socket for server connection
out_format : str or None
format of the output structure
Returns
-------
Any
received message
... | 5fcb0c9e3051d680a531e9a43414a474e4c69c54 | 644,820 |
def vm_name(request):
"""
Customized VM name in module scope
"""
name_marker = request.node.get_closest_marker("vm_name")
return name_marker.args[0] if name_marker else request.node.name | 4a8cec2ba017c0fb578a701b89187a9b7cad9f85 | 644,821 |
def bits_to_target(bits):
""" Decodes the full target from a compact representation.
See: https://bitcoin.org/en/developer-reference#target-nbits
Args:
bits (int): Compact target (32 bits)
Returns:
target (Bignum): Full 256-bit target
"""
shift = bits >> 24
target = (bits &... | 58e140be51908ae0cde003e1ca938ea9e75d1724 | 644,822 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.