content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def is_fouling_team_in_penalty(event):
"""Returns True if fouling team over the limit, else False"""
fouls_to_give_prior_to_foul = event.previous_event.fouls_to_give[event.team_id]
return fouls_to_give_prior_to_foul == 0 | 5,340,000 |
def is_img_id_valid(img_id):
"""
Checks if img_id is valid.
"""
t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE)
t = re.sub(r'\.+', '.', t)
if img_id != t or img_id.count(':') != 1:
return False
profile, base_name = img_id.split(':', 1)
if not profile or not base_name:
... | 5,340,001 |
def lmc(wave, tau_v=1, **kwargs):
""" Pei 1992 LMC extinction curve.
:param wave:
The wavelengths at which optical depth estimates are desired.
:param tau_v: (default: 1)
The optical depth at 5500\AA, used to normalize the
attenuation curve.
:returns tau:
The optical d... | 5,340,002 |
def minMax(xs):
"""Calcule le minimum et le maximum d'un tableau de valeur xs (non-vide !)"""
min, max = xs[0], xs[0]
for x in xs[1:]:
if x < min:
min = x
elif x > max:
max = x
return min,max | 5,340,003 |
def events(request):
"""Events"""
# Get profile
profile = request.user.profile
# Get a QuerySet of events for this user
events = Event.objects.filter(user=request.user)
# Create a new paginator
paginator = Paginator(events, profile.entries_per_page)
# Make sure page request is an int,... | 5,340,004 |
def print_describe(name: str, item: Any):
"""Print an item with a description, where the item is properly indented.
Args:
name (str): The name of the item to print.
item (Any): The item to print, indented by one tab.
"""
print(f"{name}: ")
print(textwrap.indent(str(item), "\t")) | 5,340,005 |
def latent_posterior_factory(x: np.ndarray, y: np.ndarray) -> Tuple[Callable]:
"""Factory function that yields further functions to compute the log-posterior
of the stochastic volatility model given parameters `x`. The factory also
constructs functions for the gradient of the log-posterior and the Fisher
... | 5,340,006 |
def update_build_configuration_set(id, **kwargs):
"""
Update a BuildConfigurationSet
"""
data = update_build_configuration_set_raw(id, **kwargs)
if data:
return utils.format_json(data) | 5,340,007 |
def create_app(settings_override: Optional[dict]=None) -> Flask:
"""
Create a Flask app
:param settings_override: any settings to override
:return: flask app
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config.settings')
app.config.from_pyfile('sett... | 5,340,008 |
def compute_prefix_function(pattern):
"""
Computes the prefix array for KMP.
:param pattern:
:type pattern: str
:return:
"""
m = len(pattern)
prefixes = [0]*(m+1)
i = 0
for q in range(2, m + 1):
while i > 0 and pattern[i] != pattern[q - 1]:
i = prefixes[... | 5,340,009 |
def binary_indicator(states,
actions,
rewards,
next_states,
contexts,
termination_epsilon=1e-4,
offset=0,
epsilon=1e-10,
state_indices=None,
... | 5,340,010 |
def sigmoid(num):
"""
Find the sigmoid of a number.
:type number: number
:param number: The number to find the sigmoid of
:return: The result of the sigmoid
:rtype: number
>>> sigmoid(1)
0.7310585786300049
"""
# Return the calculated value
return 1 / (1 + math... | 5,340,011 |
def print_version(ctx, param, value):
"""Print out the version of opsdroid that is installed."""
if not value or ctx.resilient_parsing:
return
click.echo("opsdroid {version}".format(version=__version__))
ctx.exit(0) | 5,340,012 |
def list_lattices(device_name: str = None, num_qubits: int = None,
connection: ForestConnection = None):
"""
Query the Forest 2.0 server for its knowledge of lattices. Optionally filters by underlying
device name and lattice qubit count.
:return: A dictionary keyed on lattice names a... | 5,340,013 |
def read_vec_flt_ark(file_or_fd):
""" generator(key,vec) = read_vec_flt_ark(file_or_fd)
Create generator of (key,vector<float>) tuples, reading from an ark file/stream.
file_or_fd : ark, gzipped ark, pipe or opened file descriptor.
Read ark to a 'dictionary':
d = { u:d for u,d in kaldi_io.read_... | 5,340,014 |
def inflate_tilegrid(
bmp_path=None,
target_size=(3, 3),
tile_size=None,
transparent_index=None,
bmp_obj=None,
bmp_palette=None,
):
"""
inflate a TileGrid of ``target_size`` in tiles from a 3x3 spritesheet by duplicating
the center rows and columns.
:param Optional[str] bmp_path... | 5,340,015 |
def mark_ballot_stuffing_delta(row, i, rows,
duplicate_threshold,
random_order_threshold):
"""
Modifies the list elements in place adding a smelly attribute to each row
dictionary that is equal to the searched row within a timedelta
Added ran... | 5,340,016 |
def get_name_and_version(requirements_line: str) -> tuple[str, ...]:
"""Get the name a version of a package from a line in the requirement file."""
full_name, version = requirements_line.split(" ", 1)[0].split("==")
name_without_extras = full_name.split("[", 1)[0]
return name_without_extras, version | 5,340,017 |
def test_required_parameters_provided_valid_inputs():
"""
Unit test to check the required_parameters_provided function with valid inputs
"""
parameters = {}
keys = []
required_parameters_provided(
parameters=parameters,
keys=keys
) | 5,340,018 |
def _compute_eval_stats(params, batch,
model,
pad_id):
"""Computes pre-training task predictions and stats.
Args:
params: Model state (parameters).
batch: Current batch of examples.
model: The model itself. Flax separates model state and architecture.
... | 5,340,019 |
def tail_conversation(conversation):
"""
Yield lines from the backlog of the specified conversation. Yields an empty
string when EOF is encountered, but will keep trying. This is based on
this clever SO answer: http://stackoverflow.com/a/1703997
"""
with open(os.path.join(MESSAGE_DIR, conversati... | 5,340,020 |
def validateTextFile(fileWithPath):
"""
Test if a file is a plain text file and can be read
:param fileWithPath(str): File Path
:return:
"""
try:
file = open(fileWithPath, "r", encoding=locale.getpreferredencoding(), errors="strict")
# Read only a couple of lines in the f... | 5,340,021 |
def get_title(filename="test.html"):
"""Read the specified file and load it into BeautifulSoup. Return the title tag
"""
with open(filename, "r") as my_file:
file_string = my_file.read()
file_soup = BeautifulSoup(file_string, 'html.parser')
#find all of the a tags with href attribut... | 5,340,022 |
def make_job_files_public(jobs):
"""Given a list of jobs from the db, make their result files
publicly readble.
"""
for job in jobs:
for mimetype, url in job['results'].iteritems():
make_job_file_public(url) | 5,340,023 |
def is_valid_dump_key(dump_key):
"""
True if the `dump_key` is in the valid format of
"database_name/timestamp.dump"
"""
regexmatch = re.match(
r'^[\w-]+/\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}_\d+\.\w+\.dump$',
dump_key,
)
return regexmatch | 5,340,024 |
def GetProfileAtAngle( imdata, xc,yc, angle, radius, width=1 ):
"""
Returns a 1D profile cut through an image at specified angle, extending to
specified radius.
Note: this is designed to imitate pvect, so angles are measured CCW from +x axis!
This function uses IRAF coordinates (1-based, x = co... | 5,340,025 |
def gen_dict_extract(key: str,
var: Union[Dict[str, Any], List[Any]]) -> Generator[Any, None, None]:
"""A generator that extracts all values in a nested dict with the given key.
Args:
key: The key we are looking for.
var: The target dictionary (maybe a list during the recur... | 5,340,026 |
async def test_light(opp, rfxtrx_automatic):
"""Test light entities."""
rfxtrx = rfxtrx_automatic
entity_id = "binary_sensor.x10_security_motion_detector_a10900_32"
await rfxtrx.signal(EVENT_LIGHT_DETECTOR_LIGHT)
assert opp.states.get(entity_id).state == "on"
await rfxtrx.signal(EVENT_LIGHT_D... | 5,340,027 |
def create_out_dir_name(params):
"""
Create output directory name for the experiment based on the current date
and time.
Args:
params (dict): The parameters of the experiment.
Returns:
str: The path to the output directory.
"""
current_timestamp = timestamp()
out_dir ... | 5,340,028 |
def extract_axon_and_myelin_masks_from_image_data(image_data):
"""
Returns the binary axon and myelin masks from the image data.
:param image_data: the image data that contains the 8-bit greyscale data, with over 200 (usually 255 if following
the ADS convention) being axons, 100 to 200 (usually 127 if f... | 5,340,029 |
async def app(
jupyter: MockJupyter, cachemachine: MockCachemachine
) -> AsyncIterator[FastAPI]:
"""Return a configured test application.
Wraps the application in a lifespan manager so that startup and shutdown
events are sent during test execution.
Notes
-----
This must depend on the Jupy... | 5,340,030 |
def main():
"""
Main - program execute
"""
print (str(datetime.datetime.now()) + ' Starting ...')
datadir = 'C:/Dev/covid-19-vic-au/'
processXlsx(datadir)
print (str(datetime.datetime.now()) + ' Finished!')
exit() | 5,340,031 |
def create_mne_array(recording, ch_names=None):
"""
Populate a full mne raw array object with information.
Parameters
----------
lfp_odict : bvmpc.lfp_odict.LfpODict
The lfp_odict object to convert to numpy data.
ch_names : List of str, Default None
Optional. What to name the mn... | 5,340,032 |
def expand_advanced(var, vars_, nounset, indirect, environ, var_symbol):
"""Expand substitution."""
if len(vars_) == 0:
raise MissingClosingBrace(var)
if vars_[0] == "-":
return expand_default(
var,
vars_[1:],
set_=False,
nounset=nounset,
... | 5,340,033 |
def overlap(n2, lamda_g, gama):
""" Calculates the 1/Aeff (M) from the gamma given.
The gamma is supposed to be measured at lamda_g
(in many cases we assume that is the same as where
the dispersion is measured at).
"""
M = gama / (n2*(2*pi/lamda_g))
return M | 5,340,034 |
def fill_none(pre_made_replays_list):
"""Fill none and reformat some fields in a pre-made replays list.
:param pre_made_replays_list: pre-made replays list from ballchasing.com.
:return: formatted list.
"""
for replay in pre_made_replays_list:
if replay["region"] is None:
replay... | 5,340,035 |
def main(args):
"""
Main function of script
:param :args: args from command line
:return: None
"""
username = args.username if args.username != '' else input(
'Username [> ')
file_name = username.lower() + '.api'
if os.path.exists(file_name):
data = ih.load_da... | 5,340,036 |
def parse_args_from_str(arg_str, arg_defs): # , context=None):
"""
Args:
args_str (str): argument string, optionally comma-separated
arg_defs (tuple): list of argument definitions
context (dict, optional):
When passed, the arguments are parsed for ``$(var_name)`` macros,
... | 5,340,037 |
def test_nb_regression_ini_setting_init(testdir):
"""Test the nb_regression fixture is initialised with the config file settings."""
testdir.makeini(
r"""
[pytest]
nb_exec_cwd = {path}
nb_exec_allow_errors = True
nb_exec_timeout = 100
nb_diff_use_color = True
... | 5,340,038 |
def model_evaluation(
data_loader,
ml_model_name,
ml_model,
smiles_dictionary,
max_length_smiles,
device_to_use,
):
"""
Evaluation per batch of a pytorch machine learning model.
Parameters
----------
data_loader : torch.utils.data
The training data as seen by Pytorch... | 5,340,039 |
def compSeq(s1, s2, lineL=50):
"""Print two sequences showing mismatches.
Parameters
----------
s1, s2 : str
Strings representing aligned AA or NT sequences
lineL : int
Wrap line at lineL"""
lineN = int(np.ceil(min(len(s1), len(s2))/lineL))
count = 0
samecount = 0
ou... | 5,340,040 |
def reverse_dict2(d):
"""Reverses direction of dependence dict
>>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}
>>> reverse_dict(d) # doctest: +SKIP
{1: ('a',), 2: ('a', 'b'), 3: ('b',)}
:note: dict order are not deterministic. As we iterate on the
input dict, it make the output of this functio... | 5,340,041 |
def setup(argv):
"""
Setup the fido2 database
:return:
"""
db_path, encryption_key = handle_args(argv, "pe", ["db-path=",
"encryption-key="])
connection = get_db_connection(db_path, encryption_key)
cursor = connection.cursor()
sql_command = """... | 5,340,042 |
def Flip(p, y='Y', n='N'):
"""Returns y with probability p; otherwise n."""
return y if random.random() <= p else n | 5,340,043 |
def plot_soma(ax, soma, plane='xy',
soma_outline=True,
linewidth=_LINEWIDTH,
color=None, alpha=_ALPHA):
"""Generates a 2d figure of the soma.
Args:
ax(matplotlib axes): on what to plot
soma(neurom.core.Soma): plotted soma
plane(str): Any pair of... | 5,340,044 |
def prepare():
"""Prepare the database (create needed tables, indices, etc.)."""
con = connect()
with con:
con.execute(
"""
CREATE TABLE IF NOT EXISTS characters (
name string primary key,
attack int,
defense int
)
... | 5,340,045 |
def test_projected_cov_calc(lorenz_dataset):
"""Test the project_cross_cov_mats function by also directly projecting
the data."""
rng = np.random.RandomState(20200226)
T, d, X, _, _ = lorenz_dataset
X = X[:, :3]
N = 3
d = 2
T = 6
V = init_coef(N, d, rng, 'random_ortho')
tV = torc... | 5,340,046 |
def show_status():
"""prints out "_ " or the letter itself from the current_capital_upper if
it is in the used_letters list"""
global current_capital_upper
global current_country
global used_letters
global life
current_life()
if life == 1:
print("\nOh! It's the capital of %s\n!" ... | 5,340,047 |
def resolve_avicenna(d):
"""
.. todo::
WRITEME
"""
import pylearn2.datasets.avicenna
return pylearn2.config.checked_call(pylearn2.datasets.avicenna.Avicenna,d) | 5,340,048 |
def sub_to_db(sub,
add_area=True,
area_srid=3005,
wkt=True,
wkb=False,
as_multi=True,
to_disk=False,
procs=1,
engine=None):
"""
Convert the object to a SQLite database. Returns the |db| module exposin... | 5,340,049 |
def delete_keys(session, keys):
"""Removes list of key classes from data store
args:
session: Active database session
keys: list of key classes
returns:
nothing
"""
_delete(session, keys)
session.commit() | 5,340,050 |
def T_autoignition_methods(CASRN):
"""Return all methods available to obtain T_autoignition for the desired
chemical.
Parameters
----------
CASRN : str
CASRN, [-]
Returns
-------
methods : list[str]
Methods which can be used to obtain T_autoignition with the given input... | 5,340,051 |
def parse_config2(filename=None):
"""
https://docs.python.org/3.5/library/configparser.html
:param filename: filename to parse config
:return: config_parse result
"""
_config = configparser.ConfigParser(allow_no_value=True)
if filename:
# ConfigParser does not create a file if it d... | 5,340,052 |
def test_lsp_type_serialization() -> None:
"""
LSP spec names are camel case while Python conventions are to use snake case.
"""
class MyLspType(lsp_types.LspModel):
snake_case_name: int
optional: Optional[int]
spec_compatible: Dict = {"snakeCaseName": 0}
v1 = MyLspType(snake_... | 5,340,053 |
def masa(jd, place):
"""Returns lunar month and if it is adhika or not.
1 = Chaitra, 2 = Vaisakha, ..., 12 = Phalguna"""
ti = tithi(jd, place)[0]
critical = sunrise(jd, place)[0] # - tz/24 ?
last_new_moon = new_moon(critical, ti, -1)
next_new_moon = new_moon(critical, ti, +1)
this_solar_month = raasi(... | 5,340,054 |
def sigma(s):
"""The probablity a normal variate will be `<s` sigma from the mean.
Parameters
----------
s : float
The number of sigma from the mean.
Returns
-------
p : float
The probability that a value within +/-s would occur.
"""
from scipy.special import erf
r... | 5,340,055 |
def addneq_parse_residualline(line: str) -> dict:
"""
Parse en linje med dagsløsningsresidualer fra en ADDNEQ-fil.
Udtræk stationsnavn, samt retning (N/E/U), spredning og derefter et vilkårligt
antal døgnresidualer.
En serie linjer kan se således ud:
GESR N 0.07 0.02 -0.... | 5,340,056 |
async def threadsafe_async_pipe(queue: Queue, async_queue: asyncio.Queue, event: Event):
"""Checks the formal threadsafe queue for a message
then places it on the async_queue
Args:
queue:
async_queue:
event: The kill event
"""
while True and not event.is_set():
try:... | 5,340,057 |
def extract_header(file_path):
"""
Loads the header from a PSG-type file at path 'file_path'.
Returns:
dictionary of header information
"""
fname = os.path.split(os.path.abspath(file_path))[-1]
_, ext = os.path.splitext(fname)
load_func = _EXT_TO_LOADER[ext[1:]]
header = load_fu... | 5,340,058 |
def get_xsd_schema(url):
"""Request the XSD schema from DOV webservices and return it.
Parameters
----------
url : str
URL of the XSD schema to download.
Returns
-------
xml : bytes
The raw XML data of this XSD schema as bytes.
"""
response = HookRunner.execute_inj... | 5,340,059 |
def get_char_pmi(data):
"""
获取 pmi
:param data:
:return:
"""
print('get_char_pmi')
model = kenlm.LanguageModel('../software/kenlm/test.bin')
res = []
for line in data:
words = line.strip().split()
length = len(words)
words.append('\n')
i = 0
pm... | 5,340,060 |
def fahrenheit_to_celsius(fahrenheit):
"""Convert a Fahrenheit temperature to Celsius."""
return (fahrenheit - 32.0) / 1.8 | 5,340,061 |
def test_insert_sort_on_one_item_list():
"""Test insert sort with single item list."""
from insert import insert_sort
assert insert_sort([5]) == [5] | 5,340,062 |
def sample_blocks(num_layers, num_approx):
"""Generate approx block permutations by sampling w/o replacement. Leave the
first and last blocks as ReLU"""
perms = []
for _ in range(1000):
perms.append(sorted(random.sample(list(range(0,num_layers)), num_approx)))
# Remove duplicates
perms.s... | 5,340,063 |
def test_installed_no_source():
"""
test wusa.installed without passing source
"""
with pytest.raises(SaltInvocationError) as excinfo:
wusa.installed(name="KB123456", source=None)
assert excinfo.exception.strerror == 'Must specify a "source" file to install' | 5,340,064 |
def reviewer_actions(org, repo, output_file_prefix, pr_count):
""" Generate metrics for tier reviewer groups, and general contributors
Will collect tier reviewer teams from the github org
Tier reviewer teams will read from settings file, and default to what SatelliteQE uses
"""
for repo_name in re... | 5,340,065 |
def save_visualization(segmentation, original_image, path_to_output, alpha=0.5):
"""
Saves the visualization as png in the specified fied path.
"""
f = plt.figure()
a = f.add_subplot(131)
a.imshow(original_image, cmap='gray')
a.set_title('image')
a = f.add_subplot(132)
a.imshow(... | 5,340,066 |
def adjacent_values(vals, q1, q3):
"""Helper function for violinplot visualisation (courtesy of
https://matplotlib.org/gallery/statistics/customized_violin.html#sphx-glr-gallery-statistics-customized-violin-py)
"""
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adja... | 5,340,067 |
async def test_get_weather_no_forecast_data(hass, coordinator_config):
"""Test missing forecast data."""
session = Mock()
response = Mock()
response.status = HTTPStatus.OK
mock_response_json = {}
response.json = AsyncMock(return_value=mock_response_json)
session.get = AsyncMock(return_value=... | 5,340,068 |
def l2_first_moment(freq, n_trials, weights):
"""Return the first raw moment of the squared l2-norm of a vector (f-p), where `f` is an MLE
estimate
of the `p` parameter of the multinomial distribution with `n_trials`."""
return (np.einsum("aiai,ai->", weights, freq) - np.einsum("aiaj,ai,aj->", weigh... | 5,340,069 |
def sigmoid(x: float, a: float = 1, b: float = 1, shift: float = 0) -> float:
"""
Sigmoid function represented by b * \frac{1}{1 + e^{-a * (x - shift)}}}
Args:
x (float): Input x
a (float, optional): Rate of inflection. Defaults to 1.
b (float, optional): Difference of lowest to hig... | 5,340,070 |
def db_credentials():
"""Load creds and returns dict of postgres keyword arguments."""
creds = load_json('creds.json')
return {
'host': creds['db_host'],
'user': creds['db_username'],
'password': creds['db_password'],
'database': creds['db_database']
} | 5,340,071 |
def generate_corpus_output( cfg, docL, tfidfL ):
""" Generate a list of OutputRecords where the number of key words
is limited to the cfg.corpusKeywordCount highest scoring terms.
(i.e. cfg.usePerDocWordCount == False)
"""
outL = []
# for the cfg.corpusKeyWordCount highest scoring keywords... | 5,340,072 |
def test_top_level_overrides_environment_markers(PipenvInstance):
"""Top-level environment markers should take precedence.
"""
with PipenvInstance() as p:
with open(p.pipfile_path, 'w') as f:
contents = """
[packages]
apscheduler = "*"
funcsigs = {version = "*", os_name = "== 'splashwear... | 5,340,073 |
def expand(directory: str) -> str:
"""Apply expanduser and expandvars to directory to expand '~' and env vars."""
temp1 = os.path.expanduser(directory)
return os.path.expandvars(temp1) | 5,340,074 |
def test_apply_colormap():
"""Basic test of silx.math.colormap.apply_colormap"""
data = numpy.arange(256)
expected_colors = numpy.empty((256, 4), dtype=numpy.uint8)
expected_colors[:, :3] = numpy.arange(256, dtype=numpy.uint8).reshape(256, 1)
expected_colors[:, 3] = 255
colors = colormap.apply_c... | 5,340,075 |
def gather_ensemble_info(nmme_model):
"""Gathers ensemble information based on NMME model."""
# Number of ensembles in the forecast (ens_num)
# Ensemble start index (ens_start)
# Ensemble end index (ens_end)
if nmme_model == "CFSv2":
ens_num=24
ens_start=1
ens_end=24
eli... | 5,340,076 |
def makedirs(pathname):
"""Create a directory, or make sure that the directory is world-writable"""
# This is a workaround for promblem caused by the Rayonix software running
# under a different user id on the Rayonix control computer, compared
# to the beamline control computer, so directories created via NFS ... | 5,340,077 |
def harmonic_fitter(progressions, J_thres=0.01):
"""
Function that will sequentially fit every progression
with a simple harmonic model defined by B and D. The
"B" value here actually corresponds to B+C for a near-prolate,
or 2B for a prolate top.
There are a number ... | 5,340,078 |
def print_KruskalWallisH(div_calc):
"""
Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that
each group must have at least 5 measurements.
"""
calc = defaultdict(list)
try:
for k1, v1 in div_calc.iteritems():
for k2, v2 in v1.iteritems():
... | 5,340,079 |
def test_build_payload_xml_config(mock_pynxos_device_xml):
"""Build payload with list of commands (XML)."""
mock_device = mock_pynxos_device_xml
payload = mock_device.api._build_payload(
["logging history size 200"], method="cli_conf"
)
xml_root = etree.fromstring(payload)
api_method = x... | 5,340,080 |
def visualize_roc_curves(prediction,
target,
output_dir,
report_gt_feature_n_positives=50,
style="seaborn-colorblind",
fig_title="Feature ROC curves",
dpi=500):
"""
... | 5,340,081 |
def test_get_last():
"""
Check get_last returns a json with necessary fields
"""
route = GetLast()
route_result = route.get(engine=ENGINE)
assert check_api_result(route_result) | 5,340,082 |
def display_solution(board):
"""Display the current state of the board (and count a solution)."""
global _num_solutions
_num_solutions += 1
if QUIET:
return
print('Solution {}:'.format(_num_solutions))
for i in range(0, len(board), TOTAL_WIDTH):
print(''.join(c or ' ' for c in bo... | 5,340,083 |
def _random_exptname():
"""Generate randome expt name NNNNNNNN_NNNNNN, where N is any number 0..9"""
r = ''.join(random.choice(string.digits) for _ in range(8))
r = r + '_' + ''.join(random.choice(string.digits) for _ in range(6))
return r | 5,340,084 |
def remove_store(store_name):
""" Deletes the named data store.
:param store_name:
:return:
"""
return get_data_engine().remove_store(store_name) | 5,340,085 |
def rules_pyo3_fetch_remote_crates():
"""This function defines a collection of repos and should be called in a WORKSPACE file"""
maybe(
http_archive,
name = "rules_pyo3__cfg_if__1_0_0",
url = "https://crates.io/api/v1/crates/cfg-if/1.0.0/download",
type = "tar.gz",
strip_... | 5,340,086 |
def is_tracked_upstream(folder: Union[str, Path]) -> bool:
"""
Check if the current checked-out branch is tracked upstream.
"""
try:
command = "git rev-parse --symbolic-full-name --abbrev-ref @{u}"
subprocess.run(
command.split(),
stderr=subprocess.PIPE,
... | 5,340,087 |
def limit_checkins_per_user(checkins: list, num_checkins_per_user: int, random_seed=1):
"""
Limit for each user a maximum number of check-ins by randomly select check-ins.
Parameters
----------
checkins: list
list of check-ins
num_checkins_per_user: int
max number of check-ins p... | 5,340,088 |
def expect_exit_code(step, exit_code):
"""Expect the exit code to be a certain integer"""
assert step.context.exit_code == exit_code, (
"Actual exit code was: {}\n".format(step.context.exit_code)
+ "stdout from radish run: '{}':\n".format(" ".join(step.context.command))
+ step.context.st... | 5,340,089 |
async def main() -> None:
"""Show example on controlling your LaMetric device."""
# Create a alert notification, with 3 message frames.
# First frame is a text, the second is a goal, last one
# shows a chart. Additionally, the WIN notification sound
# is played.
notification = Notification(
... | 5,340,090 |
def display_overview(ticker: str):
"""Alpha Vantage stock ticker overview
Parameters
----------
ticker : str
Fundamental analysis ticker symbol
"""
df_fa = av_model.get_overview(ticker)
if df_fa.empty:
console.print("No API calls left. Try me later", "\n")
return
... | 5,340,091 |
def getCharacterFilmography(characterID, charIF, charDF, movieIF, movieKF,
personIF, personKF, limit=None):
"""Build a filmography list for the specified characterID."""
try:
ifptr = open(charIF, 'rb')
except IOError, e:
import warnings
warnings.warn('Unab... | 5,340,092 |
def sqrt_fixed_full(x, config, is_training=True, causal=True):
"""Full attention matrix with sqrt decomposition."""
bsize = x.shape[0]
query, key, value = attention.get_qkv(x, x, x, hidden_size=config.model_size,
num_heads=config.num_heads,
... | 5,340,093 |
def mcf_from_row(row, gene_to_dcid_list):
"""Generate data mcf from each row of the dataframe"""
gene = row['Gene name']
tissue = get_class_name(row['Tissue'])
cell = get_class_name(row['Cell type'])
expression = EXPRESSION_MAP[row['Level']]
reliability = RELIABILITY_MAP[row['Reliability']]
... | 5,340,094 |
def add_repo_information( pom, repo_url ):
"""Adds development maven repo to pom file so that the artifacts used are the development artifacts"""
to_insert = """
<repositories>
<repository>
<id>checker-framework-repo</id>
<url>%s</url>
</r... | 5,340,095 |
def loads(json_str, target=None):
"""
Shortcut for instantiating a new :class:`JSONDecoder` and calling the :func:`from_json_str` function.
.. seealso::
For more information you can look at the doc of :func:`JSONDecoder.from_json_str`.
"""
return _decoder.from_json_str(json_str, target) | 5,340,096 |
def discover(discover_system: bool = True) -> Discovery:
"""
Discover capabilities offered by this extension.
"""
logger.info("Discovering capabilities from aws-az-failure-chaostoolkit")
discovery = initialize_discovery_result(
"aws-az-failure-chaostoolkit", __version__, "aws"
)
dis... | 5,340,097 |
def generate_feed(videos, baseurl, root_path):
"""Creates feed from items from db"""
fg = FeedGenerator()
fg.load_extension('podcast')
fg.title('My feed')
fg.link(href=baseurl, rel='alternate')
fg.description('Some description')
fg.author({"name":"makovako", "email":"test@example.com"})
... | 5,340,098 |
def getter_nofancy(a, b, asarray=True, lock=None):
""" A simple wrapper around ``getter``.
Used to indicate to the optimization passes that the backend doesn't
support fancy indexing.
"""
return getter(a, b, asarray=asarray, lock=lock) | 5,340,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.