content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def yuv444to420p(img: np.ndarray, inter=cv2.INTER_LINEAR) -> np.ndarray:
"""
yuv444转420p,可自定义方法
:param img: 图像
:param inter: 插值方法
:return: 一维数组
"""
[y, u, v] = img.astype(np.uint8).transpose((2, 0, 1))
w, h = y.shape[1] >> 1, y.shape[0] >> 1
u, v = resize(u, w, h, inter), resize(v, w... | 5,299,800 |
def compute_rotation_matrix(w, phi, k, degrees=False):
"""
Computes Rotation matrix from the rotation angle w, phi, k
related to x, y and z.
Returns
-------
r_matrix: Rotational Matrix M
[cos(phi)cos(k) sin(w)sin(phi)cos(k)+cos(w)sin(k) -cos(w)sin(phi)cos(k)+sin(w)sin(k)]
M = [... | 5,299,801 |
def iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no def... | 5,299,802 |
def mailserver(port=1025):
"""Run a SMTP test server."""
cmd = 'python -m smtpd -n -c DebuggingServer localhost:{port}'.format(port=port)
run(bin_prefix(cmd), pty=True) | 5,299,803 |
def _album_candidates(items, artist, album, va_likely):
"""Search for album matches. ``items`` is a list of Item objects
that make up the album. ``artist`` and ``album`` are the respective
names (strings), which may be derived from the item list or may be
entered by the user. ``va_likely`` is a boolean ... | 5,299,804 |
def create_disk_v3_onion_service(onion_service_dir, tor_control_port, client_pub_key,
port, ip_address="127.0.0.1", client_name=None):
"""Creates a permanent Tor v3 Onion Service.
Args:
onion_service_dir: A pathlib object containing the path to the Tor Onion Service dir... | 5,299,805 |
def machine_available():
""" Display an input, validate the client choice and returns the corresponding choice. """
client_choice = input(f"What would you like? ({menu_object.get_items()}):").lower()
if client_choice in menu_object.get_items():
menu_item = menu_object.find_drink(client_choice)
... | 5,299,806 |
def log_updates_scheduled(message):
"""
Process used to log information easily in other modules
Gathers number of items that have been updates
"""
log.info(" updates_scheduled size: {}".format(len(updates_scheduled)))
for index, item in enumerate(updates_scheduled):
log.info("ITEM {} {}... | 5,299,807 |
def tree_stats(directory, align_directory, split_directory, ci_phones, num_jobs, fmllr=False):
"""
Multiprocessing function that computes stats for decision tree training
See http://kaldi-asr.org/doc/acc-tree-stats_8cc.html for more details
on the Kaldi binary this runs.
Parameters
----------
... | 5,299,808 |
def strict_type_hints(func):
"""
Enforce type hints on the parameters and return types of the decorated
function.
Also require type hints to be provided for all parmeters and the return
value.
"""
return EnforceTypeHints(func, require_args=True, require_return=True) | 5,299,809 |
def extract_zip(filename):
"""
Uses zipfile package to extract a single zipfile
:param filename:
:return: new filename
"""
try:
file = zipfile.ZipFile(filename, 'r')
except FileNotFoundError:
puts(colored.red(f"{filename} Does not exist"))
sys.exit()
# Save the n... | 5,299,810 |
def initializeCentroids(points, k):
"""returns k centroids from the initial points"""
centroids = points.copy()
np.random.shuffle(centroids)
return centroids[:k] | 5,299,811 |
def split_text(text, sep='\n'):
"""Split text."""
if isinstance(text, bytes):
text = text.decode("utf8")
return [elm.strip() for elm in text.split(sep) if elm.strip()] | 5,299,812 |
def parse_config(configfile='config.yml'):
"""
Loads the config file
Arguments:
- configfile: File to parse, default config.yml
Returns:
Configuration dict
Raises:
YAMLError if config file is not a valid YML
ValueError if configuration... | 5,299,813 |
async def finish_setup(hass, gateways):
"""Load any persistent devices and platforms and start gateway."""
discover_tasks = []
start_tasks = []
for gateway in gateways.values():
discover_tasks.append(_discover_persistent_devices(hass, gateway))
start_tasks.append(_gw_start(hass, gateway)... | 5,299,814 |
def fit_linear_models(train_embs, train_labels, val_embs, val_labels,
model_type='svm'):
"""Fit Log Regression and SVM Models."""
if model_type == 'linear':
_, train_acc, val_acc = fit_linear_model(train_embs, train_labels,
val_embs, val_labels)... | 5,299,815 |
def test_correlation_id():
""" Test the correlation id is logged when coming from the headers """
_user_logging(
{'X-Correlation-ID': '298ebf9d-be1d-11e7-88ff-2c44fd152860'},
{},
{'correlation_id': v_str('298ebf9d-be1d-11e7-88ff-2c44fd152860')}
) | 5,299,816 |
def test_extract_informative_reads(include_tails, soft_clip_minimum_length, answer):
"""
Tests read extraction parsing and filtering.
"""
data_path = os.path.dirname(os.path.realpath(__file__)) + '/data/testPreprocessInput-2017-07-28.bam'
query = list(extract_informative.extract_informative_reads(da... | 5,299,817 |
def make_pip_cmd(pip_args, constraint_file_path):
"""Inject a lockfile constraint into the pip command if present.
:param pip_args: pip arguments.
:param constraint_file_path: Path to a ``constraints.txt``-compatible file.
:returns: pip command.
"""
pip_cmd = [sys.executable, '-m', 'pip'] + pi... | 5,299,818 |
def play_music1(music_file):
"""
stream music with mixer.music module in blocking manner
this will stream the sound from disk while playing
"""
clock = pygame.time.Clock()
try:
pygame.mixer.music.load(music_file)
print ("Music file %s loaded!" % music_file)
except pygame.erro... | 5,299,819 |
def GetWindowsProcesses_method2():
"""
Gets list of windows processes using BAT file
"""
batFile = 'GETWINPROCESS.BAT'
print('creating BAT file - ' + batFile)
with open(batFile,'w') as f:
cols = 'description,WorkingSetSize,PrivatePageCount,ReadOperationCount, WriteOperationCount,U... | 5,299,820 |
def flatten(*, src: str, dst: str, input_format: str, output_format: str, format: str):
"""flatten jsonschema sub definitions"""
from dictknife.swaggerknife.flatten import flatten
input_format = input_format or format
data = loading.loadfile(src, format=input_format)
d = flatten(data)
loading.d... | 5,299,821 |
def jwt_get_secret_key(payload=None):
"""
For enchanced security you may use secret key on user itself.
This way you have an option to logout only this user if:
- token is compromised
- password is changed
- etc.
"""
User = get_user_model() # noqa
if api_settings.JWT_GET... | 5,299,822 |
def freezeAtoms(inputFile,domainBox):
"""Freeze (change type to 2) all atoms
"""
outfile = 'In_Frozen.in'
with open(inputFile,'r') as f:
read_data = f.read()
read_data = read_data.replace(' 1 ',' 2 ')
with open(outfile, 'w') as fileout:
fileout.write(read_data)
print('Cre... | 5,299,823 |
async def api_will_snow():
"""Find out if it will snow in Berlin soon."""
wx = await get_weather()
return {"willSnow": will_snow(wx), "dataUpdated": wx["currently"]["time"]} | 5,299,824 |
def write_csv(df, **kwargs):
"""
write csv
:param df:
:param kwargs: file_name: file name
file_path: file path
sep: sep
path_or_buf: path or buffer
header: ['A', 'B']
index: ... | 5,299,825 |
def run(args):
"""Partition command. Prepares models from the specified module for partitioning"""
names = []
mod = args['module']
try:
mod_clss = filter(lambda obj: isinstance(obj, type), __import__(mod, fromlist=mod).__dict__.values())
except ImportError as e:
raise ImportProblemE... | 5,299,826 |
def test_comment_link():
"""a simple little test to verify that the function replace_links() is
being called on comment save and inserting the correct to a ticket into
the comments's html description.
"""
desc_text = """this is similar to the problem identifed on ticket: 23"""
comment = Follow... | 5,299,827 |
def get_available_configs(config_file_path):
"""Retrieves all of the exiting configurations.
Args:
config_file_path: str, the name or the full path of the config file.
Returns:
A list of available config keys.
"""
with open(_get_config_file_path(config_file_path)) as config_file:
configs = yaml.... | 5,299,828 |
def move(
src_fp: pathlib.Path, dest_dirpath: pathlib.Path, if_exists: str = "raise"
) -> None:
"""Moves a file to another directory. If the destination directory
does not exist, it is created, as well as all intermediate directories."""
if not dest_dirpath.exists():
os.makedirs(dest_dirpath)
... | 5,299,829 |
def smin(x: Tensor, y: float) -> Tensor:
"""Take the element-wise minimum of a tensor and a scalar.
:param x: Tensor
:param y: float
:returns: min(x, y)
"""
pass | 5,299,830 |
def run_as_admin(function):
"""check if we're admin, and if not relaunch the script as admin.""",
rc = 0
if not isUserAdmin():
logging.warning("Access Denied - Admin Priveleges Required.", os.getpid(), "params: ", sys.argv)
rc = runAsAdmin()
exit(0)
else:
#print("You are ... | 5,299,831 |
def create_app(test_config=None) -> Flask:
"""Main entry point of the service. The application factory is responsible for
creating and confguring the flask app. It also defines a http ping endpoint and registers blueprints.
Returns:
Flask: the flask app
"""
app = Flask(__name__, instance_re... | 5,299,832 |
def test_invalid_method():
"""Assert that an error is raised when the model doesn't have the method."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
atom.run("SGD")
pytest.raises(AttributeError, atom.sgd.predict_proba, X_bin) | 5,299,833 |
def dir_is_git_repo(path: str) -> bool:
"""Check if directory is a Git repository.
Args:
path: (str) path to directory.
Returns:
bool: True if successful, False otherwise.
"""
try:
Repo(path)
except InvalidGitRepositoryError:
return False
return True | 5,299,834 |
def to_vertices_sequence(points: Sequence[Point[Scalar]],
size: int,
context: Context) -> Sequence[Point[Scalar]]:
"""
Based on chi-algorithm by M. Duckham et al.
Time complexity:
``O(len(points) * log len(points))``
Memory complexity:
`... | 5,299,835 |
def setup_tasmanian(vs_path=None,download=True,unzip=False,folder='cppfuncs/',do_print=False):
"""download and setup Tasmanian 5.1
Args:
vs_path (str,optional): path to vs compiler
download (bool,optional): download Tasmanian 5.1
unzip (bool,optional): unzip even if not downloaded
... | 5,299,836 |
def replace_image_link(target_str):
"""
Replace the shorthand of an image link { image.jpg } with the full link {{ img_tag("image.jpg") | safe }}
:param target_str: String with images in it to be edited
:return: string with images formatted as {{ img_tag("image.jpg") | safe }}
"""
# Find all ima... | 5,299,837 |
def ST_Affinediffeo_transformer_batch(U, thetas, out_size):
""" Batch version of the diffeomorphic affine transformer. Applies a batch
of affine transformations to each image in U.
Arguments:
U: 4D-`Tensor` [n_batch, height, width, n_channels]. Input images to
transform.
... | 5,299,838 |
def histoGauss(ax,array):
"""
Plot a histogram and fit a Gaussian to it. Modeled after IDL histogauss.pro.
parameters
----------
ax: Plot axis object
If None, return coefficients but do not plot
array: float array to plot
returns
-------
coeff: tuple (A, mu, sigma, fail)
... | 5,299,839 |
def release_all(services: Services, grpc_server: Server):
"""
Release all resources
"""
logger.info("Releasing scheduler service resources")
if grpc_server:
logger.info("gRPC server stopping")
stop_grpc_server(grpc_server)
logger.info("gRPC server stopped")
shutdown_servi... | 5,299,840 |
def _maybe_get_mask(
values: np.ndarray, skipna: bool, mask: Optional[np.ndarray]
) -> Optional[np.ndarray]:
"""
Compute a mask if and only if necessary.
This function will compute a mask iff it is necessary. Otherwise,
return the provided mask (potentially None) when a mask does not need to be
... | 5,299,841 |
def test_lowpass_biquad_eager():
""" mindspore eager mode normal testcase:lowpass_biquad op"""
# Original waveform
waveform = np.array([[0.8236, 0.2049, 0.3335], [0.5933, 0.9911, 0.2482],
[0.3007, 0.9054, 0.7598], [0.5394, 0.2842, 0.5634], [0.6363, 0.2226, 0.2288]])
# Expect wav... | 5,299,842 |
def create_option(option, display, window, active=True):
"""
Returns an option `dict` to be used by lottus
:param option `str`: the value of the option
:param option `str`: the value that will be displayed
:param window `str`: the name of the window that this option points to
... | 5,299,843 |
def create_customer_address(access_token, customer_position, cart_id):
"""
Create customer address.
Args:
access_token: required to get access to the API.
customer_position: location of customer.
cart_id: ID for the customer's cart.
"""
headers = {
'Authorization': '... | 5,299,844 |
def main():
""" Main function which calls other functions to create a data frame from multiple pickles/read from an existing dataframe
and to call functions to calculate the Mann Kendall and Theil sen statistics."""
# Define a list with column names for the percentage docs for each year
year_columns = [... | 5,299,845 |
def fetch_ts(data_dir, clean=False):
"""
convenience function to read in new data
uses csv to load quickly
use clean=True when you want to re-create the files
"""
ts_data_dir = os.path.join(data_dir,"ts-data")
if clean:
shutil.rmtree(ts_data_dir)
if not os.path.exists(ts_da... | 5,299,846 |
def arg_fetchlive(args):
"""Parse the fetchlive parameter from the command line."""
fetchlive = 1
if len(args) >= 1 and is_int(args[0]):
fetchlive = 0
dbg_print(1, "Fetchlive: %s" % fetchlive)
return fetchlive | 5,299,847 |
def get_level_1_xml(
node: et.Element,
key: str,
search_keys: typing.List[str],
data_dict: typing.Dict[str, str]
) -> None:
"""
Return the key/value pair for the xml case
<key>
<subkey>value</subkey>
</key>
Arguments:
node - Node in the xml tree
key ... | 5,299,848 |
def test_submit(tmpdir, file, smiles):
"""Make sure to schema failures are cleanly handled."""
with requests_mock.Mocker() as m:
mock_href = (
f"http://127.0.0.1:"
f"{settings.BEFLOW_GATEWAY_PORT}"
f"{settings.BEFLOW_API_V1_STR}/"
f"{settings.BEFLOW_COOR... | 5,299,849 |
def boggle(board, trie):
"""Searches for words on the assumed-nonempty board."""
height = len(board)
width = len(board[0])
matches = set()
def dfs(i, j, node):
if not (0 <= i < height and 0 <= j < width):
return
ch = board[i][j]
if ch is None:
return... | 5,299,850 |
def make_archive(source, destination):
"""
From https://stackoverflow.com/questions/32640053/compressing-directory-using-shutil-make-archive-while-preserving-directory-str
"""
base = os.path.basename(destination)
name = base.split('.')[0]
fmt = base.split('.')[1]
archive_from = os.path.dirna... | 5,299,851 |
def aw_terrain_delete_all() -> None:
"""
Resets all terrain data.
Raises:
Exception: If the terrain data could not be reset.
"""
rc = SDK.aw_terrain_delete_all()
if rc:
raise Exception(f"Failed to delete all terrain: {rc}") | 5,299,852 |
def run_entrainments(model_particles, bed_particles, event_particle_ids, avail_vertices, unverified_e, h):
""" This function mimics an 'entrainment event' through
calls to the entrainment-related functions.
Uniqueness of entrainments is forced post-event. Particles
which select non-unique entrainm... | 5,299,853 |
def opamp_voltage_normalizer(supply_voltage):
"""
Normalize supply voltage values.
"""
parse = split_val_condition(supply_voltage)
if parse["value"].startswith("± "):
parse["value"] = parse["value"].replace("± ", "±")
(value, unit) = [i for i in parse["value"].split(" ") if i != ""]
... | 5,299,854 |
def get_L_star_CS_d_t(L_star_CS_d_t_i):
"""(32)
Args:
get_L_star_CS_d_t_i: 日付dの時刻tにおける暖冷房区画iの1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
L_star_CS_d_t_i: returns: 日付dの時刻tにおける1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
Returns:
日付dの時刻tにおける1時間当たりの熱取得を含む負荷バランス時の冷房顕熱負荷(MJ/h)
"""
return np.sum(L_star_CS... | 5,299,855 |
def create_function_signature_model(fn: AnyCallable, plugins: List[PluginProtocol]) -> Type[SignatureModel]:
"""
Creates a subclass of SignatureModel for the signature of a given function
"""
try:
signature = Signature.from_callable(fn)
field_plugin_mappings: Dict[str, PluginMapping] = ... | 5,299,856 |
def angacc_2_genangacc(angacc, r, dr, angvel):
"""
:param angacc: np.array
:param r: np.array
:param dr: np.array
:param angvel: np.array
:return: np.array
"""
m_rQ = r
m_rDq = dr
V = angvel
W = V
DW = angacc
t = np.linalg.norm(m_rQ)
qw = np.dot(m_rQ, W)
t2 =... | 5,299,857 |
def execute_tasks_in_a_new_thread(event_loop):
""" Button-Event-Handler starting the asyncio part. """
threading.Thread(target=asyncio_thread, args=(event_loop, )).start() | 5,299,858 |
def random_play(data):
"""Generate a random play with plausible values for debugging purposes."""
features = data['features']
situation = OrderedDict.fromkeys(features)
situation['dwn'] = 4
situation['ytg'] = random.randint(1, 10)
situation['yfog'] = random.randint(1, (100 - situation['ytg']))... | 5,299,859 |
def remove_proximity_around_booleans(query_str):
"""
Clients like PEP-Web (Gavant) send fulltext1 as a proximity string.
This removes the proximity if there's a boolean inside.
We could have the client "not do that", but it's actually easier to
remove than to parse and add.
>>> a = '(articl... | 5,299,860 |
def extension_from_file(path):
"""Returns extension (like '.jpg') based on content of image file at path.
An empty string is returned if no match is found."""
f = file(path, 'r')
ext = extension_from_data(f.read(11))
f.close()
return ext | 5,299,861 |
def flux_radius(components, observation=None, frac=0.5, weight_order=0):
"""
Determine the radius R (in pixels, along semi-major axis),
the flux within R has a fraction of `frac` over the total flux.
Parameters
----------
components: a list of `scarlet.Component` or `scarlet.ComponentTree`
... | 5,299,862 |
def get_instances_for_description(x=None, labels=None, metrics=None, instance_indexes=None):
""" Returns indexes of instances for which we need descriptions
The instances are selected as follows:
- If the instance indexes are directly passed, then select those
- If instance indexes are not passed, ... | 5,299,863 |
def test_actor_level_gc(start_cluster, option: str):
"""Tests that actor-level working_dir is GC'd when the actor exits."""
NUM_NODES = 3
cluster, address = start_cluster
for _ in range(NUM_NODES - 1): # Head node already added.
cluster.add_node(num_cpus=1)
ray.init(address)
@ray.remo... | 5,299,864 |
def _hyperbolic_distance(x, y):
"""Compute hyperbolic distance between batches x and y.
Args:
x: 2D Numpy array.
y: 2D Numpy array.
Returns:
distances: 2D Numpy array such that distances[i,j] =
hyperbolic(x[i,:], y[j,:]).
"""
sq_norm_x = (x ** 2).sum(axis=1)[:,None]
sq_norm_y = (y ** 2).... | 5,299,865 |
def test_register_user_no_email_config(app, session, monkeypatch):
"""Ensure a confirmation email is not sent when CONFIRM_REGISTRATION_EMAIL is set."""
monkeypatch.setitem(app.config, '_JT_SERVER_MODE', 'public')
monkeypatch.setitem(app.config, 'CONFIRM_REGISTRATION_EMAIL', False)
with app.app_context(... | 5,299,866 |
def generalized_intervals_union(
interval_list:Union[List[GeneralizedInterval],Tuple[GeneralizedInterval]],
join_book_endeds:bool=True
) -> GeneralizedInterval:
""" finished, checked,
calculate the union of a list (or tuple) of `GeneralizedInterval`s
Parameters
----------
interval_list: li... | 5,299,867 |
def translate_node_in_world_space(node, translation_list, **kwargs):
"""
Translates given node with the given translation vector
:param node: str
:param translation_list: list(float, float, float)
"""
raise NotImplementedError() | 5,299,868 |
def _provenance_str(provenance):
"""Utility function used by compare_provenance to print diff
"""
return ["%s==%s" % (key, value) for (key, value) in provenance] | 5,299,869 |
def _lines_as_list(path, pattern, ignore_pattern):
"""
Helper function for config. Process lines as list of strings.
"""
try:
# All lines as list of strings
if not pattern and not ignore_pattern:
with open(path, 'r') as input_file:
ret = input_file.readlines()... | 5,299,870 |
def run(argv=None):
"""The main function which creates the pipeline and runs it."""
parser = argparse.ArgumentParser()
# Here we add some specific command line arguments we expect. S
# This defaults the output table in your BigQuery you'll have
# to create the example_data dataset yourself using b... | 5,299,871 |
def cdmi_str_to_aceflag(cdmi_str):
"""
Return the aceflag from a cdmi string
:param cdmi_str: A comma-separated list of aceflags
:type cdmi_str: str
:return: The aceflag created from the string
:rtype: int
"""
aceflag = 0
ls_flag = cdmi_str.split(",")
for flag in ls_fla... | 5,299,872 |
def group_configurations_list_handler(request, course_key_string):
"""
A RESTful handler for Group Configurations
GET
html: return Group Configurations list page (Backbone application)
POST
json: create new group configuration
"""
course_key = CourseKey.from_string(course_key_st... | 5,299,873 |
def phik_from_binned_array(x: Union[np.ndarray, pd.Series], y: Union[np.ndarray, pd.Series], noise_correction:bool=True, dropna:bool=True, drop_underflow:bool=True, drop_overflow:bool=True) -> float:
"""
Correlation matrix of bivariate gaussian derived from chi2-value
Chi2-value gets converted into correla... | 5,299,874 |
def api_client(application, request):
"""
Fixture that returns api_client
Parameters:
app (Application): Application for which create the client.
Returns:
api_client (HttpClient): Api client for application
"""
def _api_client(app=application, **kwargs):
client = app.api_... | 5,299,875 |
def main(params_path: str, words: str, secret_path: str) -> None:
"""
generate a secret
example:
python3 gen_secret --words "0 1 2 3" [--params-path params.json]
[--secret-path secret.json]"
"""
work(params_path, words, secret_path) | 5,299,876 |
def massCheck(proj, geom, label):
"""
Calculate the total liquid mass and the variation between views.
:param numpy.array(float) proj: Projection data.
:param list(dict): Geometry dict for each line of sight.
:param str label: Label defining the current projection (res/avg, Re).
:returns: Tuple... | 5,299,877 |
def get_store(name=DEFAULT_STORE_NAME, factory=DEFAULT_FACTORY):
"""
Gets store provider from factory
:param factory:
:param store_name:
:return: Storage Provider
:rtype: deployer.services.storage.base.AbstractStore
"""
return factory.get(name) | 5,299,878 |
def get_domain_adapt_config(cfg):
"""Get the configure parameters for video data for action recognition domain adaptation from the cfg files"""
config_params = {
"data_params": {
"dataset_root": cfg.DATASET.ROOT,
"dataset_src_name": cfg.DATASET.SOURCE,
"dataset_src_t... | 5,299,879 |
def rgb2hex(r,g,b):
"""
Convert a RGB vector to hexadecimal values
"""
hexfmt = "#%02x%02x%02x"%(r,g,b)
return hexfmt | 5,299,880 |
def commonInitialization(target):
"""
Routine to initialize common variables for both position forms.
"""
target.stdfont = QtGui.QFont()
target.stdfont.setFamily("Arial")
target.stdfont.setPointSize(11)
target.stdfontbold = QtGui.QFont()
target.stdfontbold.setFamily("Arial")
tar... | 5,299,881 |
def index():
"""
Renders the 'index' page
:return:
"""
return flask.render_template('index.jinja2', my_server=flask.request.url_root) | 5,299,882 |
def match_hadamards(g: BaseGraph[VT,ET],
vertexf: Optional[Callable[[VT],bool]] = None
) -> List[VT]:
"""Matches all the H-boxes with arity 2 and phase 1, i.e. all the Hadamard gates."""
if vertexf is not None: candidates = set([v for v in g.vertices() if vertexf(v)])
else: candidates = g.ve... | 5,299,883 |
def MakePartition():
"""Make train/dev/test split."""
all_images = []
label_to_images = collections.defaultdict(list)
with open(IDENT_FILE) as f:
for line in f:
image_file, label = line.strip().split(' ')
label_to_images[label].append(image_file)
all_images.ap... | 5,299,884 |
def align_right_position(anchor, size, alignment, margin):
"""Find the position of a rectangle to the right of a given anchor.
:param anchor: A :py:class:`~skald.geometry.Rectangle` to anchor the
rectangle to.
:param size: The :py:class:`~skald.geometry.Size` of the rectangle.
:param alignment:... | 5,299,885 |
def test_renyi():
"""
Consistency test for Renyi entropy and Renyi divergence
"""
dist1 = Distribution(['0', '1', '2'], [1/4, 1/2, 1/4])
uniform = Distribution(['0', '1', '2'], [1/3, 1/3, 1/3])
alphas = [0, 1, 2, 0.5]
for alpha in alphas:
h = renyi_entropy(dist1, alpha)
h_u =... | 5,299,886 |
async def PUT_Attribute(request):
""" Handler for PUT /(obj)/<id>/attributes/<name>
"""
log.request(request)
app = request.app
params = request.rel_url.query
obj_id = get_obj_id(request)
attr_name = request.match_info.get('name')
log.info("PUT attribute {} in {}".format(attr_name, obj_i... | 5,299,887 |
def update_clusters_progress():
"""Calculate the installing progress of the given cluster."""
logging.info('update_clusters_progress')
try:
update_progress.update_progress()
except Exception as error:
logging.exception(error) | 5,299,888 |
def check_conflicting_args(args, hashtype):
"""
Check argparse args object for conflicts.
e.g. --loadgraph and --ksize being set.
"""
if getattr(args, "quiet", None):
configure_logging(args.quiet)
loadgraph_table_conflicts = {"ksize": DEFAULT_K,
"n_tabl... | 5,299,889 |
def _parse_docstring_field(field_lines):
"""
@param field_string:
@type field_string:
@return: return pair:
argument name, dict of updates for argument info
@rtype: C{dict}
"""
if field_lines.startswith('@type'):
field_data = field_lines.split(None, 2)
arg_name = fie... | 5,299,890 |
def get_discount_rate(n: float, s: float, p: float) -> float:
""""
Повертає значення облікової ставки.
Parameters
----------
n : float
Термін кредиту у роках
s : float
Нарощена сума боргу
p : float
Банківський облік
Returns
-------
d : float Облікова ... | 5,299,891 |
def run_test(case_id):
"""
:param case_id: case_id is test_case_id
:return: it does the utils on test_case_id based on its test_name
"""
save_test_status(case_id, 3)
case_log = save_case_log(case_id.test_case_id, None, None, None, None)
if case_id.test_status == 3:
if case_id.test_n... | 5,299,892 |
def _is_num_tuple(t,size):
"""Returns: True if t is a sequence of numbers; False otherwise.
If the sequence is not of the given size, it also returns False.
Parameter t: The value to test
Precondition: NONE
Parameter size: The size of the sequence
Precondition: size is an int >= 0... | 5,299,893 |
def resBlock(x,kernelSize,outMaps):
"""
block of resnet units, resolution halves
"""
with tf.variable_scope(None, default_name="resBlock"):
res1 = resLayerStride(x,kernelSize,outMaps)
res2 = resLayer(res1,kernelSize,outMaps)
return res2 | 5,299,894 |
def load_gene_gene_dat(gene_dat_path):
"""
Load gene annotation data (transcript data).
:param gene_dat_path: str, filepath for gene_gene_dat_wsize (Part of ExcisionFinder package).
:return: Refseq gene annotations file.
"""
gene_gene_dat = pd.read_csv(
gene_dat_path,
sep="\t",
... | 5,299,895 |
def finish(tm_env, zkclient, container_dir, watchdog):
"""Frees allocated resources and mark then as available.
"""
with lc.LogContext(_LOGGER, os.path.basename(container_dir),
lc.ContainerAdapter) as log:
log.info('finishing %r', container_dir)
_stop_container(contai... | 5,299,896 |
def ComputeThickness2(meshes, maximumThickness, sharpAngle, cancelToken, multiple=False):
"""
Compute thickness metrics for this mesh.
Args:
meshes (IEnumerable<Mesh>): Meshes to include in thickness analysis.
maximumThickness (double): Maximum thickness to consider. Use as small a thicknes... | 5,299,897 |
def dfs(adj_matrix, minsize):
""" depth first search
Returns subsets with at least minsize or more nodes.
"""
visited = set()
connected_sets = []
for ind, row in enumerate(adj_matrix):
if ind not in visited:
connected_sets.append(set())
stack = [ind]
... | 5,299,898 |
def display_login_message(sender, **kwargs):
"""Inform user they've successfully logged in"""
request = kwargs.get("request")
user = kwargs.get("user")
name = user.get_short_name()
success(
request,
f"Successfully logged in as {name}",
fail_silently=True,
) | 5,299,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.