content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
async def test_cleanup(exp_log_records, timeout, recon_client, caplog, mocker,
monkeypatch):
"""Proper cleanup with or without pending tasks."""
recon_client.cleanup_timeout = timeout
# mocked methods names must match those in reconciler._ASYNC_METHODS
async def publish_change_me... | 26,600 |
def _check_alignment(beh_events, alignment, candidates, candidates_set,
resync_i, check_i=None):
"""Check the alignment, account for misalignment accumulation."""
check_i = resync_i if check_i is None else check_i
beh_events = beh_events.copy() # don't modify original
events = np.z... | 26,601 |
def user_info():
"""
个人中心基本资料展示
1、尝试获取用户信息
user = g.user
2、如果用户未登录,重定向到项目首页
3、如果用户登录,获取用户信息
4、把用户信息传给模板
:return:
"""
user = g.user
if not user:
return redirect('/')
data = {
'user': user.to_dict()
}
return render_template('blogs/user.html', data=da... | 26,602 |
def test_laplace_boundary_fmm(helpers, grid):
"""Test Laplace boundary operators."""
space = bempp.api.function_space(grid, "P", 1)
vec = helpers.load_npy_data("fmm_p1_vec")
for filename, operator in [
("fmm_laplace_single", bempp.api.operators.boundary.laplace.single_layer),
("fmm_lapl... | 26,603 |
def build_config_tests_list():
"""Build config tests list"""
names,_,_,_ = zip(*config_tests)
return names | 26,604 |
def writefits(filename,array):
"""
This is a fast wrapper for fits.writeto, with overwrite enabled.
"""
import astropy.io.fits as fits
from tayph.vartests import typetest
from tayph.vartests import dimtest
import pathlib
import numpy as np
filename=check_path(filename,'filename in wr... | 26,605 |
def get_layer_type_from_name(name=None) :
"""
get the layer type from the long form layer name
"""
if name is None :
print("Error get_layer_type_from_name - Bad args - exiting...")
sys.exit(1)
#print(name)
phase, layer_name = name.split(' ')
layer_type = layer_name
## @... | 26,606 |
def annotate_filter(**decargs):
"""Add input and output watermarks to filtered events."""
def decorator(func):
"""Annotate events with entry and/or exit timestamps."""
def wrapper(event, *args, **kwargs):
"""Add enter and exit annotations to the processed event."""
funcna... | 26,607 |
def cplot(*args,**kwargs):
"""
cplot - Plot on the current graphe
This is an "alias" to gcf().gca().plot()
"""
return(gcf().gca().plot(*args,**kwargs)) | 26,608 |
def need_to_flush_metrics(time_now):
"""Check if metrics need flushing, and update the timestamp of last flush.
Even though the caller of this function may not successfully flush the
metrics, we still update the last_flushed timestamp to prevent too much work
being done in user requests.
Also, this check-an... | 26,609 |
def path_to_url(path):
"""Return the URL corresponding to a given path."""
if os.sep == '/':
return path
else:
return '/'.join(split_all(path)) | 26,610 |
def get_store_contents(request, store_name):
"""Returns a list containing all the contents of the store in the form of:
[
{
"oid": <document_id>,
"data": <document_data>,
},
...
]
Keyword arguments:
request -- Django HttpRequest object
store_name ... | 26,611 |
def create_instances_from_lists(x, y=None, name="data"):
"""
Allows the generation of an Instances object from a list of lists for X and a list for Y (optional).
All data must be numerical. Attributes can be converted to nominal with the
weka.filters.unsupervised.attribute.NumericToNominal filter.
... | 26,612 |
def plot_mission(results,line_style='bo-'):
"""This function plots the results of the mission analysis and saves those results to
png files."""
# Plot Flight Conditions
plot_flight_conditions(results, line_style)
# Plot Aerodynamic Forces
plot_aerodynamic_forces(results, line_style)
... | 26,613 |
def jitdevice(func, link=[], debug=None, inline=False):
"""Wrapper for device-jit.
"""
debug = config.CUDA_DEBUGINFO_DEFAULT if debug is None else debug
if link:
raise ValueError("link keyword invalid for device function")
return compile_device_template(func, debug=debug, inline=inline) | 26,614 |
def median_filter_(img, mask):
"""
Applies a median filer to all channels
"""
ims = []
for d in range(3):
img_conv_d = median_filter(img[:,:,d], size=(mask,mask))
ims.append(img_conv_d)
return np.stack(ims, axis=2).astype("uint8") | 26,615 |
def test_get_images_404(
api_client: TestClient,
return_encoded: EncodedImage,
return_user: User,
image_service: ImageService,
access_token,
image_name: str,
) -> None:
"""Test a successful get request for decoded images without finding any results."""
image_service.get_encoded.return_va... | 26,616 |
def replace_lines(inst, clean_lines, norm_lines):
"""
Given an instance and a list of clean lines and normal lines,
add a cleaned tier and normalized if they do not already exist,
otherwise, replace them.
:param inst:
:type inst: xigt.Igt
:param clean_lines:
:type clean_lines: list[dict... | 26,617 |
def get_html(link: Link, path: Path) -> str:
"""
Try to find wget, singlefile and then dom files.
If none is found, download the url again.
"""
canonical = link.canonical_outputs()
abs_path = path.absolute()
sources = [canonical["singlefile_path"], canonical["wget_path"], canonical["dom_path... | 26,618 |
def normalization(X,degree):
""" A scaling technique in which values
are shifted and rescaled so that they
end up ranging between 0 and 1.
It is also known as Min-Max scaling
----------------------------------------
degree: polynomial regression degree, or attribute/feature number
... | 26,619 |
def markdown_file(source_markdown_file, version, tmp_dir, new_path=None):
"""
Given a markdown file path, generate an HTML partial in a directory nested
by the path on the URL itself.
"""
if not new_path:
new_path = settings.OTHER_PAGE_PATH % (
settings.EXTERNAL_TEMPLATE_DIR, ver... | 26,620 |
def select_without_source_table_privilege(self, node=None):
"""Check that user is unable to select from a view without SELECT privilege for the source table."""
user_name = f"user_{getuid()}"
view_name = f"view_{getuid()}"
table_name = f"table_{getuid()}"
exitcode, message = errors.not_enough_privil... | 26,621 |
def get_tags_from_match(child_span_0, child_span_1, tags):
"""
Given two entities spans,
check if both are within one of the tags span,
and return the first match or O
"""
match_tags = []
for k, v in tags.items():
parent_span = (v["start"], v["end"])
if parent_relation(child_... | 26,622 |
def test_1_1_1_7_file_group(host):
"""
CIS Ubuntu 20.04 v1.0.0 - Rule # 1.1.1.7
Tests if /etc/modprobe.d/1.1.1.7_vfat.conf is owned by group root
"""
assert host.file(VFAT_MOD_FILE).group == 'root' | 26,623 |
def _rfc822_escape(header):
"""Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline.
"""
lines = header.split('\n')
header = ('\n' + 8 * ' ').join(lines)
return header | 26,624 |
def getCgiBaseHref():
"""Return value for <cgiBaseHref/> configuration parameter."""
val = sciflo.utils.ScifloConfigParser().getParameter('cgiBaseHref')
if val is None:
val = "http://%s/sciflo/cgi-bin/" % socket.getfqdn()
return val | 26,625 |
def _add_remote_resources(resources):
"""Retrieve remote resources like GATK/MuTect jars present in S3.
"""
out = copy.deepcopy(resources)
for prog, info in resources.items():
for key, val in info.items():
if key == "jar" and objectstore.is_remote(val):
store_dir = ut... | 26,626 |
def dijkstra(gph: GraphState,
algo: AlgoState,
txt: VisText,
start: Square,
end: Square,
ignore_node: Square = None,
draw_best_path: bool = True,
visualize: bool = True) \
-> [dict, bool]:
"""Code for the dijkst... | 26,627 |
def list_members(infile):
"""Print list of projects"""
member_list = open(infile, mode='r', encoding='utf-8') # open file in read mode
jlist = json.load(member_list) # load information from json
if len(jlist) != 0:
for project in jlist: # create cycle for
print(str(project['... | 26,628 |
def calc_window_features(dict_features, signal_window, fs, **kwargs):
"""This function computes features matrix for one window.
Parameters
----------
dict_features : dict
Dictionary with features
signal_window: pandas DataFrame
Input from which features are computed, window
fs :... | 26,629 |
def nowIso8601():
"""
Returns time now in ISO 8601 format
use now(timezone.utc)
YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]
.strftime('%Y-%m-%dT%H:%M:%S.%f%z')
'2020-08-22T17:50:09.988921+00:00'
Assumes TZ aware
For nanosecond use instead attotime or datatime64 in pandas or numpy
... | 26,630 |
def get_trip_data(tripdata_path, output_path, start=None, stop=None):
"""
Read raw tripdata csv and filter unnecessary info.
1 - Check if output path exists
2 - If output path does not exist
2.1 - Select columns ("pickup_datetime",
"passenger_coun... | 26,631 |
def _qparams2url(qparams):
"""
parse qparams to make url segment
:param qparams:
:return: parsed url segment
"""
try:
if qparams == []:
return ""
assert len(qparams) == 4
num = len(qparams[0][1])
path=""
for i in range(num):
for j ... | 26,632 |
def confusion_matrix(y_pred: IntTensor,
y_true: IntTensor,
normalize: bool = True,
labels: IntTensor = None,
title: str = 'Confusion matrix',
cmap: str = 'Blues',
show: bool = True):
"""Plot... | 26,633 |
def from_smiles(smiles: str) -> Molecule:
"""Load a molecule from SMILES."""
return cdk.fromSMILES(smiles) | 26,634 |
def main(log_dir='../../log/', x_axis='num episodes', y_axis=['average reward'], hue='algorithm',
env_filter_func=None, alg_filter_func=None):
"""plot performance of all environments and algorithms
1. traverse all environments and plots for all algos tensorboard logs in that environment
2. genera... | 26,635 |
def parse_template_config(template_config_data: Dict[str, Any]) -> EmailTemplateConfig:
"""
>>> from tests import doctest_utils
>>> convert_html_to_text = registration_settings.VERIFICATION_EMAIL_HTML_TO_TEXT_CONVERTER # noqa: E501
>>> parse_template_config({}) # doctest: +IGNORE_EXCEPTION_DETAIL
... | 26,636 |
def stringify_message(message):
"""Return a JSON message that is alphabetically sorted by the key name
Args:
message
"""
return json.dumps(message, sort_keys=True, separators=(',', ':')) | 26,637 |
def compute_similarity_transform(X, Y, compute_optimal_scale=False):
"""
A port of MATLAB's `procrustes` function to Numpy.
Adapted from http://stackoverflow.com/a/18927641/1884420
Args
X: array NxM of targets, with N number of points and M point dimensionality
Y: array NxM of inputs
... | 26,638 |
def simplefenestration(idf, fsd, deletebsd=True, setto000=False):
"""convert a bsd (fenestrationsurface:detailed) into a simple
fenestrations"""
funcs = (window,
door,
glazeddoor,)
for func in funcs:
fenestration = func(idf, fsd, deletebsd=deletebsd, setto000=setto000)
i... | 26,639 |
def observe_birds(observations_file: TextIO) -> Set[str]:
"""Return a set of the bird species listed in observations_file, which has one bird species per line.
>>> file = StringIO("bird 1\\nbird 2\\nbird 1\\n")
>>> birds = observe_birds(file)
>>> 'bird 1' in birds
True
>>> 'bird 2' in birds
... | 26,640 |
def convert_sheet(sheet, result_dict, is_enum_mode=False):
"""
转换单个sheet的数据
Args:
sheet: openpyxl.worksheet.worksheet.Worksheet
result_dict: [dict]结果都存在这里, key为data_name,value为sheet_result
is_enum_mode: [bool]是否为enum导表模式
Returns:
bool, 是否成功
"""
if is_enum_mode:
... | 26,641 |
def _nsimage_from_file(filename, dimensions=None, template=None):
"""Take a path to an image file and return an NSImage object."""
try:
_log('attempting to open image at {0}'.format(filename))
with open(filename):
pass
except IOError: # literal file path didn't work -- try to lo... | 26,642 |
def bytes_to_int(b: bytes, order: str = 'big') -> int:
"""Convert bytes 'b' to an int."""
return int.from_bytes(b, order) | 26,643 |
def test_mock_pp():
"""test with mocked populator."""
with mock.patch('melissa.profile_populator.profile_populator'):
with pytest.raises(IOError):
from start import main | 26,644 |
def test_consumer_offset_resume(sdc_builder, sdc_executor, database):
"""
Ensure that the Query consumer can resume where it ended and stop the pipeline when it reads all the data.
We use a pipeline:
SAP HANA Query Consumer >> wiretap
SAP HANA Query Consumer >> Finisher
The test run th... | 26,645 |
def fit_model(params,param_names,lam_gal,galaxy,noise,gal_temp,
feii_tab,feii_options,
temp_list,temp_fft,npad,line_profile,fwhm_gal,velscale,npix,vsyst,run_dir,
fit_type,output_model):
"""
Constructs galaxy model by convolving templates with a LOSVD given by
a specified set of velocity parameters.
... | 26,646 |
def main():
"""
desc: initialize a session
"""
tasty_client = tasty_session.create_new_session(
environ.get('TW_USER', "")
, environ.get('TW_PASSWORD', ""))
streamer = DataStreamer(tasty_client)
LOGGER.info('Streamer token: %s' % streamer.get_streamer_token())
loop = asyncio... | 26,647 |
def _append_pretty(parent, child):
"""Append child to parent and hack indentation."""
# Calculate indentation level for child (NB: works only if child has siblings!)
level = int(len((parent.getchildren()[-1].tail).strip("\n")) / 2 + 1)
util.indent_xml(child, level)
parent.getchildren()[-1].tail = "\... | 26,648 |
def generate_numbers():
"""
Function to generate 3 random digits to be guessed.
Generate 3 random in a list in order to be compare to the user's digits.
Return:
str_digits (Array): List with 3 random digits converted to String
"""
# List comprehension to generate numbers from 0 to 9... | 26,649 |
def get_media():
"""Retrieves metadata for all of this server's uploaded media. Can use
the following query parameters:
* max: The maximum number of records to return
* page: The page of records
"""
error_on_unauthorized()
media = Upload.query.order_by(Upload.id)
total_num = media.cou... | 26,650 |
def celery():
"""Start celery"""
assert pkconfig.channel_in('dev')
import celery.bin.celery
import sirepo.celery_tasks
run_dir = _run_dir().join('celery').ensure(dir=True)
with pkio.save_chdir(run_dir):
celery.bin.celery.main(argv=[
'celery',
'worker',
... | 26,651 |
async def test_occupation_not_sure():
"""
Selecting not sure should give a description, then ask the question again
"""
u = User(
addr="27820001001", state=StateData(name="state_occupation"), session_id="1"
)
app = Application(u)
msg = Message(
content="not sure",
to_... | 26,652 |
def start_EC2(ec2_resource, ami_id, i_type, key_path, label, envs, dry_run):
"""check if have perms to create instance.
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/ec2-example-managing-instances.html#start-and-stop-instances
if so, the create instance and tag with label.
"""
... | 26,653 |
def summate2(phasevec):
"""Calculate values b'(j^vec) for combining 2 phase vectors.
Parameter:
phasevec: tuple of two phasevectors
Example:
On input (([b_1(0),b_1(1),...,b_1(L-1)], L), ([b_2(0),b_2(1),...,b_2(L'-1)], L'))
give output [b_1(0)+b_2(0), b_1(0)+b_2(1),..., b_1(1)+b_2(0),..... | 26,654 |
def get_children():
""" Return IDs of LIST which currently is zero-based index
Modelled after treeview for future alphabetic IDs
TODO: Should probably return list of all DICT?
"""
iid_list = []
#read()
#print('location.get_children() LIST count:',len(LIST))
for i, ndx in enumera... | 26,655 |
def resume():
""" resumes a game """
world_menu = ui.Menu("Select a World")
worlds = file_manager.find(".zip")
world_names = []
for world in worlds:
# remove everything but the world name
world_name = world.replace("worlds", "").replace(os.getcwd(), "").replace("\\", "").replace("/... | 26,656 |
def makeTracker( path, args = (), kwargs = {} ):
"""retrieve an instantiated tracker and its associated code.
returns a tuple (code, tracker).
"""
obj, module, pathname, cls = makeObject( path, args, kwargs )
code = getCode( cls, pathname )
return code, obj | 26,657 |
def info(widget):
"""
Print info about a widget
"""
pprint(widget) | 26,658 |
def format_each_linpla_subaxis(ax, xticks=None, sess_ns=None, kind="reg",
single_lab=True, sess_text=True):
"""
format_each_linpla_subaxis(ax)
Formats each subaxis separately, specifically:
- Adds session numbers if provided
- Removes bottom lines and ticks for ... | 26,659 |
def get_anchor_generator(anchor_size: Tuple[tuple] = None, aspect_ratios: Tuple[tuple] = None):
"""Returns the anchor generator."""
if anchor_size is None:
anchor_size = ((16,), (32,), (64,), (128,))
if aspect_ratios is None:
aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_size)
anchor_... | 26,660 |
def tensor_to_longs(tensor: torch.Tensor) -> list:
"""converts an array of numerical values to a tensor of longs"""
assert tensor.dtype == torch.long
return tensor.detach().cpu().numpy() | 26,661 |
def test_fixed(SNRs):
"""
Fixed (infinite T1) qubit.
"""
fidelities = []
numShots = 10000
dt = 1e-3
for SNR in SNRs:
fakeData = create_fake_data(SNR, dt, 1, numShots, T1=1e9)
signal = dt*np.sum(fakeData, axis=1)
fidelities.append(fidelity_est(signal))
return fidelities | 26,662 |
def setup(app):
"""
Add the ``fica`` directive to the Sphinx app.
"""
app.add_directive("fica", FicaDirective)
return {
"version": __version__,
"parallel_read_safe": True,
"parallel_write_safe": True,
} | 26,663 |
def auth_add(action_id, auth_type, uid, pid=None):
"""
action_id :
Action ID
auth_type :
Authorization type.
Should be one of SCOPE_ONE_SHOT, SCOPE_PROCESS,
SCOPE_SESSION or SCOPE_ALWAYS
uid :
User ID
pid :
Process ID of process to grant authorizati... | 26,664 |
def set_fit_state(dag: dtfcordag.DAG, fit_state: NodeState) -> None:
"""
Initialize a DAG with pre-fit node state.
:param dag: dataflow DAG consisting of `FitPredictNode`s
:param fit_state: result of node `get_fit_state()` keyed by nid
"""
hdbg.dassert_isinstance(dag, dtfcordag.DAG)
hdbg.da... | 26,665 |
def get_summaries(ignore_hidden=True, ordered=True):
"""Yields sorted (command name, command summary) tuples."""
cmditems = commands.items()
for name, command_class in cmditems:
if ignore_hidden and command_class.hidden:
continue
yield (name, command_class.summary) | 26,666 |
def get_binary_statistics(
outputs: Tensor, targets: Tensor, label: int = 1,
) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
"""
Computes the number of true negative, false positive,
false negative, true negative and support
for a binary classification problem for a given label.
Args:
... | 26,667 |
def threshold_and_mask(min_normed_weight, W, Mc, coords): # =np.arange(Wc.shape[0])*stride + start):
"""Normalize the weights W, threshold to min_normed_weight and remove diagonal,
reduce DX and DY to the columns and rows still containing weights.
Returns
-------
coords : array_like
the in... | 26,668 |
def strings():
"""
Manipulação de strings
acessar cada caracter
nome = 'roberto'
substituir algum caracter por outro
nome = 'roberto'
lista = list(nome) necessário para substituíção
lista[0] = 't'
nome = ''.join(lista)
para saber o final de uma string | .txt | .png | .pdf | .zip etc...
file = 'arq... | 26,669 |
def train_cnn(data, model_name, nb_epoch, batch_size):
"""
Trains a Convolutional Neural Network on the MNIST dataset
Largely inspired from https://github.com/fchollet/keras/blob/master/examples/mnist_{cnn, mlp}.py
"""
X_train, X_test, Y_train, Y_test = data
np.random.seed(constants.RANDOM_STAT... | 26,670 |
def readCGcsv(filename, levels):
""" Read a .csv file of a callgraph into a dictionary keyed by callgraph level. """
cgdict = {}
with open(filename, "r") as cgcsv:
cgreader = csv.DictReader(cgcsv)
for row in cgreader:
lvl = int(row['Level'])
if (lvl < levels) or (le... | 26,671 |
def stderr_print(msg):
"""Print a msg to stderr."""
print(msg, file=sys.stderr) | 26,672 |
def use_colors(tones, i=None):
"""
Use specific color tones for plotting. If i is specified, this function returns a specific color from the corresponding color cycle
For custom color palettes generation check: http://colorbrewer2.org/#type=sequential&scheme=YlGnBu&n=8
Args:
tones : 'hot' or 'co... | 26,673 |
def main():
"""
Usage:
python commenter.py -i <path to input.tex> -o <path to output.tex> -comment # to add commments
python commenter.py -i <path to input.tex> -o <path to output.tex> -uncomment # to remove commments
"""
parser = argparse.ArgumentParser(description='Add remove comments in tex... | 26,674 |
def fill_form(forms, form):
"""Fills a given form given a set or known forms.
:param forms: A set of known forms.
:param form: The form to fill.
:return: A mapping from form element IDs to suggested values for the form.
"""
forms = list(forms)
new_form = {}
def rec_fill_form(form, lab... | 26,675 |
def read_sky_model_from_csv(path: str) -> SkyModel:
"""
Read a CSV file in to create a SkyModel.
The CSV should have the following columns
- right ascension (deg)
- declination (deg)
- stokes I Flux (Jy)
- stokes Q Flux (Jy): if no information available, set to 0
- stokes U Flux (Jy): i... | 26,676 |
def main():
"""Run main function."""
with open('data/day3data.txt', 'r') as f:
input = f.readlines()
dataList = [map(int, i.strip('\n').split()) for i in input]
# Transpose the data.
dataList = [list(i) for i in zip(*dataList)]
# Flatten the list.
triList = [item for sublist in da... | 26,677 |
def integer_to_vector(x, options_per_element, n_elements, index_to_element):
"""Return a vector representing an action/state from a given integer.
Args:
x (int): the integer to convert.
n_options_per_element(int): number of options for each element in the vector.
n_elements (int):... | 26,678 |
def samples_for_each_class(dataset_labels, task):
"""
Numbers of samples for each class in the task
Args:
dataset_labels Labels to count samples from
task Labels with in a task
Returns
"""
num_samples = np.zeros([len(task)], dtype=np.float32)
i = 0
for label ... | 26,679 |
def requiredOneInGroup(col_name, group, dm, df, *args):
"""
If col_name is present in df, the group validation is satisfied.
If not, it still may be satisfied, but not by THIS col_name.
If col_name is missing, return col_name, else return None.
Later, we will validate to see if there is at least one... | 26,680 |
def persist(session, obj, return_id=True):
"""
Use the session to store obj in database, then remove obj from session,
so that on a subsequent load from the database we get a clean instance.
"""
session.add(obj)
session.flush()
obj_id = obj.id if return_id else None # save this before obj i... | 26,681 |
def test_bittrex_query_asset_movement_int_transaction_id(bittrex):
"""Test that if an integer is returned for bittrex transaction id we handle it properly
Bittrex deposit withdrawals SHOULD NOT return an integer for transaction id
according to their docs https://bittrex.github.io/api/v3#definition-Order
... | 26,682 |
def create_merged_files(ecbplus_original, ecbstart_new, outfile1, outfile2):
"""
:param ecbplus_original: ECB+ CAT data
:param ecbstart_new: ESC CAT data
:param outfile1: event mention extended
:param outfile2: event extended coref chain
:return:
"""
ecbplus = etree.parse(ecbplus_orig... | 26,683 |
def _fixed_point(
searcher: 'AbstractSearcher',
parsed: parsed_file.ParsedFile,
initial_substitutions: Sequence[substitution.Substitution],
start: int,
end: int,
max_iterations: int,
):
"""Repeatedly apply searcher until there are no more changes."""
if max_iterations <= 1:
return initi... | 26,684 |
def masker(mask, val):
"""Enforce the defined bits in the <mask> on <val>."""
ones = sub(r"[^1]", "0", mask)
val |= int(ones,2)
zeros = sub(r"[^0]", "1", mask)
val &= int(zeros,2)
return val | 26,685 |
def ct_lt_u32(val_a, val_b):
"""
Returns 1 if val_a < val_b, 0 otherwise. Constant time.
:type val_a: int
:type val_b: int
:param val_a: an unsigned integer representable as a 32 bit value
:param val_b: an unsigned integer representable as a 32 bit value
:rtype: int
"""
val_a &= 0xf... | 26,686 |
async def is_banned(ctx: Context, user: typing.Union[discord.Member, discord.User]) -> bool:
"""Returns true if user is in guild's ban list."""
bans = await ctx.guild.bans()
for entry in bans:
if entry.user.id == user.id:
return True
return False | 26,687 |
def test_ce_aftertax_income(cps_subsample):
"""
Test ce_aftertax_income method.
"""
rec = Records.cps_constructor(data=cps_subsample)
pol = Policy()
calc1 = Calculator(policy=pol, records=rec)
pol.implement_reform({'SS_Earnings_c': {2013: 9e99}})
calc2 = Calculator(policy=pol, records=re... | 26,688 |
def _create_transformation_vectors_for_pixel_offsets(
detector_group: h5py.Group, wrapper: nx.NexusWrapper
) -> List[QVector3D]:
"""
Construct a transformation (as a QVector3D) for each pixel offset
"""
x_offsets = wrapper.get_field_value(detector_group, "x_pixel_offset")
y_offsets = wrapper.get... | 26,689 |
def buildIterator(spec_name, param_spec, global_state, random_selection=False):
"""
:param param_spec: argument specification
:param random_selection: produce a continuous stream of random selections
:return: a iterator function to construct an iterator over possible values
"""
if param_spec['ty... | 26,690 |
def logged(obj):
"""Add a logger member to a decorated class or function.
:arg obj:
the class or function object being decorated, or an optional
:class:`logging.Logger` object to be used as the parent logger
(instead of the default module-named logger)
:return:
*obj* if *obj* is... | 26,691 |
def outlier_removal_mean(dataframe, colname, low_cut, high_cut):
"""Replace outliers with the mean on dataframe[colname]"""
col = dataframe[colname]
col_numerics = col.loc[
col.apply(
lambda x: isinstance(x, (int, float))
and (x >= low_cut and x <= high_cut)
)
]... | 26,692 |
def _on_rmtree_error(func, path, exc_info):
"""
Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=o... | 26,693 |
def reac_depr(filename, output):
"""
Extract and transform a table with deprecated reaction identifiers.
INPUT FILE is the path to the raw MetaNetX source table.
OUTPUT FILE is the path for the transformed table output.
"""
logger.info("Processing deprecated compartment identifiers.")
con... | 26,694 |
def non_repeating(value, counts, q):
"""Finds the first non-repeating string in a stream.
Args:
value (str): Latest string received in the string
counts (dict): Dictionary of strings containing the counts to determine if string is repeated
q (Queue): Container for all strings in stream ... | 26,695 |
def test_run(s3_stubber):
"""Test that the command updates the relevant records ignoring ones with errors."""
sectors = SectorFactory.create_batch(5)
investment_projects = [
# investment project in CSV doesn't exist so row should fail
# sector should get updated
InvestmentProjectFa... | 26,696 |
def test_default(carousels: List[element.Tag]):
"""Test."""
carousel = carousels[0]
assert carousel["class"] == ["scbs-carousel", "scbs-slide", "scbs-carousel-fade"]
carousel = carousels[1]
assert carousel["class"] == ["scbs-carousel", "scbs-slide"]
carousel = carousels[2]
assert carousel[... | 26,697 |
async def insult(e):
""" Don't Rape too much """
await e.edit(choice(RAPE_STRINGS)) | 26,698 |
def test_cli_generate_tests():
"""Test tests command."""
runner = CliRunner()
gen_tests_result = runner.invoke(
cli.main, ["generate-tests", "--from", "bundled", "Example"]
)
assert gen_tests_result.exit_code == 0
yaml_ = yaml.safe_load(StringIO(gen_tests_result.output))
assert len(y... | 26,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.