content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def add_campaign_data(campaign_data):
"""Adds CampaignData type to datastore
Args:
campaign_data:
The CampaignData object that is prepared and added to datastore
as CampaignData entity
Returns:
None
"""
campaign_entity = convert_campaign_to_entity(campaign_data)
put... | 26,700 |
def deploy(cluster_name, hub_name, config_path):
"""
Deploy one or more hubs in a given cluster
"""
validate_cluster_config(cluster_name)
validate_hub_config(cluster_name, hub_name)
assert_single_auth_method_enabled(cluster_name, hub_name)
with get_decrypted_file(config_path) as decrypted_f... | 26,701 |
def split_by_rank(faf, ranks, outdir, verbose=False):
"""
Split the fasta file
:param faf: fasta file
:param ranks: dict of taxid and rank
:param outdir: output directory
:param verbose: more output
:return:
"""
s = re.compile('TaxID=(\d+)')
if args.v:
sys.stderr.write(... | 26,702 |
def auth_optional(request):
"""
view method for path '/sso/auth_optional'
Return
200 reponse: authenticated and authorized
204 response: not authenticated
403 reponse: authenticated,but not authorized
"""
res = _auth(request)
if res:
#authenticated, but can be aut... | 26,703 |
def main():
"""docstring for main"""
#set system default encoding to utf-8 to avoid encoding problems
reload(sys)
sys.setdefaultencoding( "utf-8" )
#load channel configurations
channels = json.load(open('conf/channel.json'))
#find one account
rr = SNSPocket()
for c in channels:
... | 26,704 |
def is_pip_main_available():
"""Return if the main pip function is available. Call get_pip_main before calling this function."""
return PIP_MAIN_FUNC is not None | 26,705 |
def energy_target(flattened_bbox_targets, pos_bbox_targets,
pos_indices, r, max_energy):
"""Calculate energy targets based on deep watershed paper.
Args:
flattened_bbox_targets (torch.Tensor): The flattened bbox targets.
pos_bbox_targets (torch.Tensor): Bounding box lrtb value... | 26,706 |
def dashtable(df):
"""
Convert df to appropriate format for dash datatable
PARAMETERS
----------
df: pd.DataFrame,
OUTPUT
----------
dash_cols: list containg columns for dashtable
df: dataframe for dashtable
drop_dict: dict containg dropdown list for dashtable
"""
... | 26,707 |
def validate_gradient():
"""
Function to validate the implementation of gradient computation.
Should be used together with gradient_check.py.
This is a useful thing to do when you implement your own gradient
calculation methods.
It is not required for this assignment.
"""
from gradient_c... | 26,708 |
def other_identifiers_to_metax(identifiers_list):
"""Convert other identifiers to comply with Metax schema.
Arguments:
identifiers_list (list): List of other identifiers from frontend.
Returns:
list: List of other identifiers that comply to Metax schema.
"""
other_identifiers = []... | 26,709 |
def print_formatted_table(delimiter):
"""Read tabular data from standard input and print a table."""
data = []
for line in sys.stdin:
line = line.rstrip()
data.append(line.split(delimiter))
print(format_table(data)) | 26,710 |
def enforce_excel_cell_string_limit(long_string, limit):
"""
Trims a long string. This function aims to address a limitation of CSV
files, where very long strings which exceed the char cell limit of Excel
cause weird artifacts to happen when saving to CSV.
"""
trimmed_string = ... | 26,711 |
def gaussian_blur(image: np.ndarray, sigma_min: float, sigma_max: float) -> np.ndarray:
"""
Blurs an image using a Gaussian filter.
Args:
image: Input image array.
sigma_min: Lower bound of Gaussian kernel standard deviation range.
sigma_max: Upper bound of Gaussian kernel standard ... | 26,712 |
def get_number_of_pcs_in_pool(pool):
"""
Retrun number of pcs in a pool
"""
pc_count = Computer.objects.filter(pool=pool).count()
return pc_count | 26,713 |
def save_images(scene_list, video_manager, num_images=3, frame_margin=1,
image_extension='jpg', encoder_param=95,
image_name_template='$VIDEO_NAME-Scene-$SCENE_NUMBER-$IMAGE_NUMBER',
output_dir=None, downscale_factor=1, show_progress=False,
scale=None, hei... | 26,714 |
def get_used_http_ports() -> List[int]:
"""Returns list of ports, used by http servers in existing configs."""
return [rc.http_port for rc in get_run_configs().values()] | 26,715 |
def test_show_environment(session):
"""Session.show_environment() returns dict."""
_vars = session.show_environment()
assert isinstance(_vars, dict) | 26,716 |
def get_img_from_fig(fig, dpi=180, color_cvt_flag=cv2.COLOR_BGR2RGB) -> np.ndarray:
"""Make numpy array from mpl fig
Parameters
----------
fig : plt.Figure
Matplotlib figure, usually the result of plt.imshow()
dpi : int, optional
Dots per inches of the image to save. Note, that defau... | 26,717 |
def split_data_by_target(data, target, num_data_per_target):
"""
Args:
data: np.array [num_data, *data_dims]
target: np.array [num_data, num_targets]
target[i] is a one hot
num_data_per_target: int
Returns:
result_data: np.array [num_data_per_target * num_targets... | 26,718 |
def test_sa_new_list_odd(test_sa):
"""
function to ensure empty list to populate is available
"""
test_sa.insert_shift_array(test_sa.test_list, test_sa.test_num, 2.5)
assert test_sa.zero == 6
assert test_sa.new_list == [3, 4, 5, 6, 7, 8] | 26,719 |
def top_mutations(mutated_scores, initial_score, top_results=10):
"""Generate list of n mutations that improve localization probability
Takes in the pd.DataFrame of predictions for mutated sequences and the
probability of the initial sequence. After substracting the initial value
from the values of the... | 26,720 |
def npmat4_to_pdmat4(npmat4):
"""
# updated from cvtMat4
convert numpy.2darray to LMatrix4 defined in Panda3d
:param npmat3: a 3x3 numpy ndarray
:param npvec3: a 1x3 numpy ndarray
:return: a LMatrix3f object, see panda3d
author: weiwei
date: 20170322
"""
return Mat4(npmat4[0, 0],... | 26,721 |
def is_at_NWRC(url):
"""
Checks that were on the NWRC network
"""
try:
r = requests.get(url)
code = r.status_code
except Exception as e:
code = 404
return code==200 | 26,722 |
def _key_press(event, params):
"""Handle key presses for the animation."""
if event.key == 'left':
params['pause'] = True
params['frame'] = max(params['frame'] - 1, 0)
elif event.key == 'right':
params['pause'] = True
params['frame'] = min(params['frame'] + 1, len(params['fra... | 26,723 |
def lmo(x,radius):
"""Returns v with norm(v, self.p) <= r minimizing v*x"""
shape = x.shape
if len(shape) == 4:
v = torch.zeros_like(x)
for first_dim in range(shape[0]):
for second_dim in range(shape[1]):
inner_x = x[first_dim][second_dim]
rows, co... | 26,724 |
def test_user_class():
"""
User supplied meta class.
"""
class First(object):
"User class."
def __init__(self, seconds, a, b, c):
"Constructor must be without parameters."
# Testing that additional attributes
# are preserved.
self.some_att... | 26,725 |
def _transform_index(index, func):
"""
Apply function to all values found in index.
This includes transforming multiindex entries separately.
"""
if isinstance(index, MultiIndex):
items = [tuple(func(y) for y in x) for x in index]
return MultiIndex.from_tuples(items, names=index.na... | 26,726 |
def add_to_cmake(list_file: Path, comp_path: Path):
""" Adds new component to CMakeLists.txt"""
print("[INFO] Found CMakeLists.txt at '{}'".format(list_file))
with open(list_file, "r") as file_handle:
lines = file_handle.readlines()
topology_lines = [(line, text) for line, text in enumerate(line... | 26,727 |
def extractQualiTeaTranslations(item):
"""
# 'QualiTeaTranslations'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Harry Potter and the Rise of the Ordinary Person' in item['tags']:
return None
i... | 26,728 |
def feature_norm_ldc(df):
"""
Process the features to obtain the standard metrics in LDC mode.
"""
df['HNAP'] = df['HNAC']/df['ICC_abs']*100
df['TCC'] = (df['ICC_abs']+df['DCC_abs'])/df['VOL']
df['ICC'] = df['ICC_abs']/df['VOL']
df['DCC'] = df['DCC_abs']/df['VOL']
return df | 26,729 |
def configure():
"""Configure HIL."""
config_testsuite()
config.load_extensions() | 26,730 |
def dice_jaccard(y_true, y_pred, y_scores, shape, smooth=1, thr=None):
"""
Computes Dice and Jaccard coefficients.
Args:
y_true (ndarray): (N,4)-shaped array of groundtruth bounding boxes coordinates in xyxy format
y_pred (ndarray): (N,4)-shaped array of predicted bounding boxes coordinates... | 26,731 |
def forward_pass(output_node, sorted_nodes):
"""
Performs a forward pass through a list of sorted nodes.
Arguments:
`output_node`: A node in the graph, should be the output node (have no outgoing edges).
`sorted_nodes`: A topologically sorted list of nodes.
Returns the output Node's v... | 26,732 |
def qr_decomposition(q, r, iter, n):
"""
Return Q and R matrices for iter number of iterations.
"""
v = column_convertor(r[iter:, iter])
Hbar = hh_reflection(v)
H = np.identity(n)
H[iter:, iter:] = Hbar
r = np.matmul(H, r)
q = np.matmul(q, H)
return q, r | 26,733 |
def main(args=None):
"""Main entry point for `donatello`'s command-line interface.
Args:
args (List[str]): Custom arguments if you wish to override sys.argv.
Returns:
int: The exit code of the program.
"""
try:
init_colorama()
opts = get_parsed_args(args)
... | 26,734 |
def build_detection_train_loader(cfg, mapper=None):
"""
A data loader is created by the following steps:
1. Use the dataset names in config to query :class:`DatasetCatalog`, and obtain a list of dicts.
2. Coordinate a random shuffle order shared among all processes (all GPUs)
3. Each process spawn ... | 26,735 |
def cond_scatter(ary, indexes, values, mask):
"""
scatter(ary, indexes, values, mask)
Scatter 'values' into 'ary' selected by 'indexes' where 'mask' is true.
The values of 'indexes' are absolute indexed into a flatten 'ary'
The shape of 'indexes', 'value', and 'mask' must be equal.
Parameters... | 26,736 |
def discRect(radius,w,l,pos,gap,layerRect,layerCircle,layer):
"""
This function creates a disc that is recessed inside of a rectangle. The
amount that the disc is recessed is determined by a gap that surrounds the
perimeter of the disc. This much hangs out past the rectangle to couple to
a bus waveguide.Calls sub... | 26,737 |
def sub_factory():
"""Subscript text: <pre>H[sub]2[/sub]O</pre><br />
Example:<br />
H[sub]2[/sub]O
"""
return make_simple_formatter("sub", "<sub>%(value)s</sub>"), {} | 26,738 |
def train_test_split(
structures: list, targets: list, train_frac: float = 0.8
) -> Tuple[Tuple[list, list], Tuple[list, list]]:
"""Split structures and targets into training and testing subsets."""
num_train = floor(len(structures) * train_frac)
return (
(structures[:num_train], targets[:num_tr... | 26,739 |
def reset_password(token):
"""
Handles the reset password process.
"""
if not current_user.is_anonymous():
return redirect(url_for("forum.index"))
form = ResetPasswordForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
expired... | 26,740 |
def writePlist(path, data):
"""Write a property list to file."""
if Path(path).exists():
_data = readPlist(path)
_data.update(data)
else:
_data = data
if DEPRECATED:
with open(path, 'wb') as _f:
plistlib.dump(_data, _f)
else:
plistlib.writePlist(... | 26,741 |
def parse():
"""
格式化账户信息,并输出
:return:
"""
x = prettytable.PrettyTable()
x.field_names = ["Address", "Health", "B. ETH", "B.Tokens", "Supply", "Estimated profit", "On Chain Liquidity"]
req = requests.get("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD").json()
account_l... | 26,742 |
async def config_doc(ctx, items):
"""Display configuration documentation."""
config = ctx.obj
config.doc(*items) | 26,743 |
def delete(vol_path):
"""
Delete a kv store object for this volume identified by vol_path.
Return true if successful, false otherwise
"""
return kvESX.delete(vol_path) | 26,744 |
def auto_adjust_xlsx_column_width(df, writer, sheet_name, margin=3, length_factor=1.0, decimals=3, index=True):
"""
Auto adjust column width to fit content in a XLSX exported from a pandas DataFrame.
How to use:
```
with pd.ExcelWriter(filename) as writer:
df.to_excel(writer, sheet_name="My... | 26,745 |
def insert_event(events: List[str], service: Resource, calendar_id: str) -> None:
"""Add events to calendar."""
batch = service.new_batch_http_request()
# Add each event to batch
for i, event in enumerate(events):
batch.add(service.events().insert(calendarId=calendar_id, body=event))
batch... | 26,746 |
def get_tablespace_data(tablespace_path, db_owner):
"""This function returns the tablespace data"""
data = {
"name": "test_%s" % str(uuid.uuid4())[1:8],
"seclabels": [],
"spcacl": [
{
"grantee": db_owner,
"grantor": db_owner,
"p... | 26,747 |
def join_chunks(chunks):
"""empty all chunks out of their sub-lists to be split apart again by split_chunks(). this is because chunks now
looks like this [[t,t,t],[t,t],[f,f,f,][t]]"""
return [item for sublist in chunks for item in sublist] | 26,748 |
def urls_equal(url1, url2):
"""
Compare two URLObjects, without regard to the order of their query strings.
"""
return (
url1.without_query() == url2.without_query()
and url1.query_dict == url2.query_dict
) | 26,749 |
def bytes_to_ints(bs):
"""
Convert a list of bytes to a list of integers.
>>> bytes_to_ints([1, 0, 2, 1])
[256, 513]
>>> bytes_to_ints([1, 0, 1])
Traceback (most recent call last):
...
ValueError: Odd number of bytes.
>>> bytes_to_ints([])
[]
"""
if len(bs) % 2 != 0:... | 26,750 |
def validate_cesion_and_dte_montos(cesion_value: int, dte_value: int) -> None:
"""
Validate amounts of the "cesión" and its associated DTE.
:raises ValueError:
"""
if not (cesion_value <= dte_value):
raise ValueError('Value of "cesión" must be <= value of DTE.', cesion_value, dte_value) | 26,751 |
def create_default_yaml(config_file):
"""This function creates and saves the default configuration file."""
config_file_path = config_file
imgdb_config_dir = Config.IMGDB_CONFIG_HOME
if not imgdb_config_dir.is_dir():
try:
imgdb_config_dir.mkdir(parents=True, exist_ok=True)
... | 26,752 |
def canRun(page):
""" Returns True if the given check page is still set to "Run";
otherwise, returns false. Accepts one required argument, "page."
"""
print("Checking checkpage.")
page = site.Pages[page]
text = page.text()
if text == "Run":
print("We're good!")
return True
re... | 26,753 |
def parse_configs_for_multis(conf_list):
"""
parse list of condor config files searching for multi line configurations
Args:
conf_list: string, output of condor_config_val -config
Returns:
multi: dictionary. keys are first line of multi line config
values are the ... | 26,754 |
def _bgp_predict_wrapper(model, *args, **kwargs):
"""
Just to ensure that the outgoing shapes are right (i.e. 2D).
"""
mean, cov = model.predict_y(*args, **kwargs)
if len(mean.shape) == 1:
mean = mean[:, None]
if len(cov.shape) == 1:
cov = cov[:, None]
return mean, cov | 26,755 |
def create_waninterface(config_waninterface, waninterfaces_n2id, site_id):
"""
Create a WAN Interface
:param config_waninterface: WAN Interface config dict
:param waninterfaces_n2id: WAN Interface Name to ID dict
:param site_id: Site ID to use
:return: New WAN Interface ID
"""
# make a c... | 26,756 |
def max_pool(images, imgshp, maxpoolshp):
"""
Implements a max pooling layer
Takes as input a 2D tensor of shape batch_size x img_size and performs max pooling.
Max pooling downsamples by taking the max value in a given area, here defined by
maxpoolshp. Outputs a 2D tensor of shape batch_size x out... | 26,757 |
def rmean(A):
""" Removes time-mean of llc_4320 3d fields; axis=2 is time"""
ix,jx,kx = A.shape
Am = np.repeat(A.mean(axis=2),kx)
Am = Am.reshape(ix,jx,kx)
return A-Am | 26,758 |
def default_pruning_settings():
"""
:return: the default pruning settings for optimizing a model
"""
mask_type = "unstructured" # TODO: update based on quantization
sparsity = 0.85 # TODO: dynamically choose sparsity level
balance_perf_loss = 1.0
filter_min_sparsity = 0.4
filter_min_pe... | 26,759 |
def claim_node(vars=None):
"""
Claim the node connected to the given serial port
(Get cloud credentials)
:param vars: `port` as key - Serial Port, defaults to `None`
:type vars: str | None
:raises Exception: If there is an HTTP issue while claiming
:return: None on Success
:rtype: Non... | 26,760 |
def build_request_url(base_url, sub_url, query_type, api_key, value):
"""
Function that creates the url and parameters
:param base_url: The base URL from the app.config
:param sub_url: The sub URL from the app.config file. If not defined it will be: "v1/pay-as-you-go/"
:param query_type: The query ... | 26,761 |
def snake_to_camel(action_str):
"""
for all actions and all objects unsnake case and camel case.
re-add numbers
"""
if action_str == "toggle object on":
return "ToggleObjectOn"
elif action_str == "toggle object off":
return "ToggleObjectOff"
def camel(match):
return m... | 26,762 |
def todayDate() -> datetime.date:
"""
:return: ex: datetime.date(2020, 6, 28)
"""
return datetime.date.today() | 26,763 |
def lookup_facade(name, version):
"""
Given a facade name and version, attempt to pull that facade out
of the correct client<version>.py file.
"""
for _version in range(int(version), 0, -1):
try:
facade = getattr(CLIENTS[str(_version)], name)
return facade
ex... | 26,764 |
def create_service(netUrl, gwUrl, attributes, token):
"""
Create NFN Service in MOP Environment.
:param netUrl: REST Url endpoint for network
:param gwUrl: REST Url endpoint for gateway
:param serviceAttributes: service paramaters, e.g. service type or name, etc
:param token: seesion token for... | 26,765 |
def _drawBlandAltman(mean, diff, md, sd, percentage, limitOfAgreement, confidenceIntervals, detrend, title, ax, figureSize, dpi, savePath, figureFormat, meanColour, loaColour, pointColour):
"""
Sub function to draw the plot.
"""
if ax is None:
fig, ax = plt.subplots(1,1, figsize=figureSize, dpi=dpi)
plt.r... | 26,766 |
def reader(args):
"""
Realign BAM hits to miRBase to get better accuracy and annotation
"""
samples = []
database = mapper.guess_database(args)
args.database = database
precursors = fasta.read_precursor(args.hairpin, args.sps)
args.precursors = precursors
matures = mapper.read_gtf_to... | 26,767 |
def rename_columns(df):
"""This function renames certain columns of the DataFrame
:param df: DataFrame
:type df: pandas DataFrame
:return: DataFrame
:rtype: pandas DataFrame
"""
renamed_cols = {"Man1": "Manufacturer (PE)",
"Pro1": "Model (PE)",
"Man2"... | 26,768 |
def retseq(seq_fh):
"""
Parse a fasta file and returns non empty records
:seq_fh: File handle of the input sequence
:return: Non empty sequences
"""
for record in SeqIO.parse(seq_fh, 'fasta'):
if len(record.seq):
yield record | 26,769 |
def get_github_emoji(): # pragma: no cover
"""Get Github's usable emoji."""
try:
resp = requests.get(
'https://api.github.com/emojis',
timeout=30
)
except Exception:
return None
return json.loads(resp.text) | 26,770 |
def transport_stable(p, q, C, lambda1, lambda2, epsilon, scaling_iter, g):
"""
Compute the optimal transport with stabilized numerics.
Args:
p: uniform distribution on input cells
q: uniform distribution on output cells
C: cost matrix to transport cell i to cell j
lambda1: re... | 26,771 |
def clean(files, nite, wave, refSrc, strSrc, badColumns=None, field=None,
skyscale=False, skyfile=None, angOff=0.0, fixDAR=True,
raw_dir=None, clean_dir=None,
instrument=instruments.default_inst, check_ref_loc=True):
"""
Clean near infrared NIRC2 or OSIRIS images.
This program... | 26,772 |
def add(A: Coord, B: Coord, s: float = 1.0, t: float = 1.0) -> Coord:
"""Return the point sA + tB."""
return (s * A[0] + t * B[0], s * A[1] + t * B[1]) | 26,773 |
def from_binary(bin_data: str, delimiter: str = " ") -> bytes:
"""Converts binary string into bytes object"""
if delimiter == "":
data = [bin_data[i:i+8] for i in range(0, len(bin_data), 8)]
else:
data = bin_data.split(delimiter)
data = [int(byte, 2) for byte in data]
return bytes(da... | 26,774 |
def test_list_date_time_length_2_nistxml_sv_iv_list_date_time_length_3_2(mode, save_output, output_format):
"""
Type list/dateTime is restricted by facet length with value 7.
"""
assert_bindings(
schema="nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-length-3.xsd",
... | 26,775 |
def send_raw(task, raw_bytes):
"""Send raw bytes to the BMC. Bytes should be a string of bytes.
:param task: a TaskManager instance.
:param raw_bytes: a string of raw bytes to send, e.g. '0x00 0x01'
:returns: a tuple with stdout and stderr.
:raises: IPMIFailure on an error from ipmitool.
:raise... | 26,776 |
def one_on_f_weight(f, normalize=True):
""" Literally 1/f weight. Useful for fitting linspace data in logspace.
Parameters
----------
f: array
Frequency
normalize: boolean, optional
Normalized the weight to [0, 1].
Defaults to True.
Returns
-------
... | 26,777 |
def PCSPRE1M2SOC(p0, meas_pcs, meas_pre, x_pcs ,y_pcs, z_pcs, \
x_pre ,y_pre, z_pre, wt_pcs=1.0, wt_pre=1.0, \
tol_pcs=None, tol_pre=None):
"""
Optimize two X-tensors and two PRE centres to two common sites
@param p0: List containing initial guesses for (17 unknowns):
... | 26,778 |
def copy_asset_file(source, destination, context=None, renderer=None):
# type: (unicode, unicode, Dict, BaseRenderer) -> None
"""Copy an asset file to destination.
On copying, it expands the template variables if context argument is given and
the asset is a template file.
:param source: The path t... | 26,779 |
def load_randomdata(dataset_str, iter):
"""Load data."""
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
if sys.version_info > (3, 0):
objects.append... | 26,780 |
def plot(figsize=None, formats=None, limit=100, titlelen=10, **kwargs):
"""Display an image [in a Jupyter Notebook] from a Quilt fragment path.
Intended for use with `%matplotlib inline`.
Convenience method that loops over supblots that call
`plt.imshow(image.imread(FRAG_PATH))`.
Keyword arguments... | 26,781 |
async def ws_adapter(in_q: curio.Queue,
out_q: curio.Queue,
client: curio.io.Socket, _):
"""A queue-based WebSocket bridge. Sits between a
a `curio.tcp_server` and a user-defined handler; the handler
should accept an ingoing and outgoing queue which will be loaded
... | 26,782 |
def tresize(tombfile, keyfile, passphrase, newsize):
"""
Resize a tomb.
Keyfile, passphrase and new size are needed.
"""
cmd = ['tomb',
'resize',
tombfile,
'-k',
keyfile,
'--unsafe',
'--tomb-pwd',
sanitize_passphrase(passphrase),
'-s',
... | 26,783 |
def auto_z_levels(fid, x, y, variable, t_idx, n_cont, n_dec):
"""
list(float) = auto_z_levels(fid, variable, t_idx, n_cont, n_dec)
... # contour lines
... # post .
"""
fig, ax = plt.subplo... | 26,784 |
def test_Get_Histogram_key():
"""
Standard use test
"""
PauliWord = 'I0 Z1 Z2 I3 I4 X5'
Histogram_key = Get_Histogram_key(PauliWord)
expected = '1,2,5'
assert expected and Histogram_key | 26,785 |
def test_get_source_files():
"""
Should probably be removed or altered, but this does help test that pytest is
importing correctly.
"""
list_of_files = utils.get_source_files()
assert os.path.join("drivers", "experiment1.py") in list_of_files
assert os.path.join("src", "utils.py") in list_of... | 26,786 |
def spider_next(url, lev):
"""
# spider_next
@Description:
core function of spider
with recursive structure to traverse all the nodes in it
---------
@Param:
url: str
lev: recursive level
-------
@Returns:
recursion, void type
-------
"""
# choose spider_clas... | 26,787 |
def canonicalize(curie: str):
"""Return the best CURIE."""
# TODO maybe normalize the curie first?
norm_prefix, norm_identifier = normalize_curie(curie)
if norm_prefix is None or norm_identifier is None:
return jsonify(
query=curie,
normalizable=False,
)
norm... | 26,788 |
def _DefaultValueConstructorForField(field):
"""Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in... | 26,789 |
async def test_http_errors(hass, mock_setup):
"""Test HTTP Errors."""
with patch("flipr_api.FliprAPIRestClient.search_flipr_ids", side_effect=Timeout()):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={... | 26,790 |
def create_work_database(target_work_database_path, country_vector_path):
"""Create a runtime status database if it doesn't exist.
Parameters:
target_work_database_path (str): path to database to create.
Returns:
None.
"""
LOGGER.debug('launching create_work_database')
# proc... | 26,791 |
def clean_text(dirty_text):
"""
Given a string, this function tokenizes the words of that string.
:param dirty_text: string
:return: list
input = "American artist accomplishments american"
output = ['accomplishments', 'american', 'artist']
"""
lower_dirty_text = dirt... | 26,792 |
def write_json(data, file_out):
"""
Write JSON to a file.
:param data: In-memory JSON.
:param file_out: The file to output the JSON to.
"""
with open(file_out, "w") as jf:
jf.seek(0)
jf.write(json.dumps(data, sort_keys=False, indent=4))
jf.truncate() | 26,793 |
def test_create_file_data_json():
"""Unit test
Given
- Raw response of an attachment in email reply.
When
- There is an attachment in the email reply.
Then
- Validate that the file data is in the right json format.
"""
from SendEmailReply import create_fil... | 26,794 |
def GetCurrentUserController(AuthJSONController):
""" Return the CurrentUserController in the proper scope """
class CurrentUserController(AuthJSONController):
""" Controller to return the currently signed in user """
def __init__(self, toJson):
""" Initialize with the... | 26,795 |
def configure_blueprints(app, blueprints):
"""Registers blueprints for given 'app' and
associates with @before_request and @errorhandler functions.
"""
for blueprint in blueprints:
blueprint.before_request(before_request)
app.register_blueprint(blueprint) | 26,796 |
def fft_in_range(audiomatrix, startindex, endindex, channel):
"""
Do an FFT in the specified range of indices
The audiomatrix should have the first index as its time domain and
second index as the channel number. The startindex and endinex
select the time range to use, and the channel parameter ... | 26,797 |
def drop_arrays_by_name(gt_names, used_classes):
"""Drop irrelevant ground truths by name.
Args:
gt_names (list[str]): Names of ground truths.
used_classes (list[str]): Classes of interest.
Returns:
np.ndarray: Indices of ground truths that will be dropped.
"""
inds = [i fo... | 26,798 |
def test_SimplePulsar_atnf():
"""Test functions against ATNF pulsar catalog values"""
atnf = load_atnf_sample()
P = Quantity(atnf['P0'], 's')
P_dot = Quantity(atnf['P1'], '')
simple_pulsar = SimplePulsar(P=P, P_dot=P_dot)
assert_allclose(simple_pulsar.tau.to('yr'), atnf['AGE'], rtol=0.01)
as... | 26,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.