content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def openapi_endpoint_name_from_rule(rule):
"""Utility function to generate the Open API endpoint name.
It replace '/users/<user_id>' with the OpenAPI standard: '/users/{user_id}'.
"""
name = rule.rule
for argument in rule.arguments:
openapi_name = f"{{{argument}}}"
name = re.sub(fr... | 5,299,200 |
def _fix_axes(tensors, axes, allow_negative):
"""Makes all axes positive and checks for out of bound errors."""
axes = [
axis + tensor.shape.ndims if axis < 0 else axis
for tensor, axis in zip(tensors, axes)
]
if not all(
((allow_negative or
(not allow_negative ... | 5,299,201 |
def get_monthly_biasfile(yyyy, mm, ccdid):
"""
format: cal/bias/yyyy/mm/ztfin2p3_yyyymm_000000_bi_ccdid_bias.fits
"""
filestructure = f"ztfin2p3_{yyyy:04d}{mm:02d}_000000_bi_c{ccdid:02d}_bias.fits"
return os.path.join(BIAS_DIR, f"{yyyy:04d}",f"{mm:02d}",
filestructure... | 5,299,202 |
def yaml_loader(filepath: str) -> dictionary:
"""
Loads a yaml file specified by the filepath and returns it as a dictionary
:param filepath: A string containing the filepath to load
:return: A dictionary containing the contents of the yaml file
"""
with open(filepath, 'r') as file_descriptor:
... | 5,299,203 |
def _wire_list_iter(wgraph: Any, align_default: Alignment) -> Iterable[List[Any], Alignment]:
"""Iterates over wire lists in the given wire graph.
wgraph format:
WireGraph = Union[WireGroup, List[WireGroup]]
WireGroup = Union[WireList, {wires=WireList, align=Alignment}]
WireList = List[Wire]
W... | 5,299,204 |
def pw_create_rsa_key(pattern, bits=4096):
"""
Create a pair of keys (private and public) based on RSA. The keys are saved to
<pattern>.pem and <pattern>.pem.pub, respectively.
https://en.wikipedia.org/wiki/RSA_(cryptosystem)
https://pycryptodome.readthedocs.io/en/latest/src/examples.html
Arg... | 5,299,205 |
def new_deit_tiny_patch16_224(pretrained=False, **kwargs):
"""
the same as vit_base_patch16_224
"""
default_kwargs = {
'embed_dim': 192,
'num_heads': 3,
}
default_kwargs.update(_cfg)
default_kwargs.update(kwargs)
vit = VisionTransformer(**default_kwargs)
if pretrained... | 5,299,206 |
def calc_rgb_each_hue_dEz_base(
hue, cusp, focal_point_l, chroma_num, delta_Ez,
color_space_name, luminance):
"""
Parameters
----------
hue : float
hue angle (0.0-360)
focal_point_l : float
lightness value of the focal_point.
chroma_num : int
the number of... | 5,299,207 |
def page_not_found(error):
"""Error 404: Page not found
"""
return render_template('page_not_found.html'), 404 | 5,299,208 |
def bigram(words, score_fn=BigramAssocMeasures.likelihood_ratio, n=500,freq=1):
"""
tmp_words=[]
for w in words:
tmp_words.append(w)
words=tmp_words
"""
if len(words)<=0:
return {}
tmp_dict={}
for w in words:
tmp_dict[w]=1
if len(tm... | 5,299,209 |
def test_basic_local_update_using_distgit(
cwd_upstream, api_instance, mock_remote_functionality_upstream
):
""" basic propose-update test: mock remote API, use local upstream and dist-git """
u, d, api = api_instance
mock_spec_download_remote_s(d)
api.sync_release("master", "0.1.0")
assert (d... | 5,299,210 |
def sample(sample_type="const", a=None, b=None, *, random_state: np.random.RandomState = None):
"""
Example
-------
>>> sample(sample_type="const",a=5,random_state=np.random.RandomState())
5
>>> isinstance(sample(sample_type="randint",a=1,b=10,random_state=np.random.RandomState()),int)
True
... | 5,299,211 |
def adam_consensus(trees):
"""Search Adam Consensus tree from multiple trees.
:Parameters:
trees : list
list of trees to produce consensus tree.
"""
clades = [tree.root for tree in trees]
return BaseTree.Tree(root=_part(clades), rooted=True) | 5,299,212 |
def decode_geometry(ewkb):
"""Decode encoded wkb into a shapely geometry"""
# it's already a shapely object
if hasattr(ewkb, 'geom_type'):
return ewkb
from shapely import wkb
from shapely import wkt
if ewkb:
try:
return wkb.loads(ba.unhexlify(ewkb))
except Ex... | 5,299,213 |
def handle_udp(packet):
"""
Handle a captured UDP packet.
:param packet: captured packet
:return: None
"""
global interesting_udp_ports
app = None
sport = packet[UDP].sport
dport = packet[UDP].dport
if sport in interesting_udp_ports:
app = interesting_udp_ports[sport]
... | 5,299,214 |
def deploy_django_application(stage="production"):
"""
Deploy application in selected server(s)
"""
set_stage(stage)
set_user()
execute(Project.push, hosts=env.hosts)
execute(Project.environment, hosts=env.hosts)
execute(Project.install, hosts=env.hosts)
execute(Project.clean, hosts=... | 5,299,215 |
def mask():
"""Example mask for testing."""
filename = '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits'
return SkyImage.read(filename, hdu='EXCLUSION') | 5,299,216 |
def main(url: str, local: bool):
"""Test the API."""
url = url.rstrip("/")
if local:
url = "http://localhost:5000"
click.echo(f"Testing resolution API on {url}")
failure = False
prefixes = tqdm(bioregistry.read_registry())
for prefix in prefixes:
identifier = bioregistry.get... | 5,299,217 |
def plot_2LinesPoint2():
""" Plot one or two Point(s) at minimum distance of two Lines.
"""
msg = verbose
error_msg = "Unable to create (Line,Line) Intersection(s): \nSelect two Lines !"
result_msg = ": (Line,Line) Intersection(s) are created !"
createFolders('WorkPoints')
name = "Intersec... | 5,299,218 |
def parse_filepaths(fp, studies=None):
"""
Summary
-------
Function to parse filepath and optional study names into a format readable
for the calsim_toolkit read/write functions.
"""
# Check that inputs provided are compatible and zip data into list.
if isinstance(fp, str) and (isinstan... | 5,299,219 |
def is_dunder(attr_name: str) -> bool:
"""
Retuns whether the given attr is a magic/dunder method.
:param attr_name:
"""
return attr_name.startswith("__") and attr_name.endswith("__") | 5,299,220 |
def feature(self):
"""Check LDAP user DN detection.
"""
self.context.node = self.context.cluster.node("clickhouse1")
self.context.ldap_node = self.context.cluster.node("openldap1")
with Given("I fix LDAP access permissions"):
fix_ldap_permissions(node=self.context.cluster.node("openldap1"))... | 5,299,221 |
def doc(descriptor, indent=0):
"""
Format ``doc`` attribute of ``descriptor``.
If doc is ``None`` returns warning admonition. If ``indent`` argument
is specified, the result will be indented by the number of spaces.
"""
if descriptor.doc is None:
result = dedent("""
.. warning::
M... | 5,299,222 |
def draw_box(im, np_boxes, labels, threshold=0.5):
"""
Args:
im (PIL.Image.Image): PIL image
np_boxes (np.ndarray): shape:[N,6], N: number of box,
matix element:[class, score, x_min, y_min, x_max, y_max]
labels (list): labels:['class1', ..., 'classn']
... | 5,299,223 |
def get_patch_generator(image, patch_size, overlay_size):
""" Patch Generator to split image by grid
:param numpy image: source image
:param int patch_size: patch size that width and height of patch is equal
:param overlay_size: overlay size in patches
:return: generator for patch image, row and co... | 5,299,224 |
def make_dir(dir_name):
""" проверяет наличие директории и в случае отсуствия создаёт ёё """
dir_name = Path.cwd() / dir_name
if not dir_name.exists():
Path.mkdir(dir_name) | 5,299,225 |
def get_mnist_default_transform():
""" The default transform come with data augmentation """
return transforms.Compose([
transforms.Pad(2),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
]) | 5,299,226 |
def test_index_new_post(mocker):
"""
Test that index_new_post calls the indexing task with the right parameters
"""
fake_serialized_data = {"serialized": "post"}
mock_post = mocker.Mock(post_id="abc")
mock_post_proxy = mocker.Mock(_self_post=mock_post)
patched_serialize_func = mocker.patch(
... | 5,299,227 |
def HideUnusedScalarBars(view=None):
"""Hides all unused scalar bars from the view. A scalar bar is used if some
data is shown in that view that is coloring using the transfer function
shown by the scalar bar."""
if not view:
view = active_objects.view
if not view:
raise ValueError (... | 5,299,228 |
def rename(name, new_name):
"""
.. versionadded:: 2017.7.0
Renames a container. Returns ``True`` if successful, and raises an error if
the API returns one. If unsuccessful and the API returns no error (should
not happen), then ``False`` will be returned.
name
Name or ID of existing con... | 5,299,229 |
def validate_serial(req_data):
"""Verify serial in data validates
Args:
req_data (dict): request with serial and possibly models
Returns:
object: None if all ok, or json response (bad)
"""
with _global_lock:
sim_type = sirepo.template.assert_sim_type(req_data['simulationTyp... | 5,299,230 |
def bisect_trajectory(
env: "CompilerEnv", # noqa: F821
hypothesis: Hypothesis = environment_validation_fails,
reverse: bool = False,
flakiness: int = 1,
) -> Iterable["CompilerEnv"]: # noqa: F821
"""Run a binary search to remove the suffix or prefix of a trjectory.
Requires worst-case O(log ... | 5,299,231 |
def read_megares_annotations(annotations_file):
"""Read MEGARes annotations.
"""
annotations = pd.read_csv(annotations_file, index_col=0)
return annotations.to_dict() | 5,299,232 |
def risings_and_settings(ephemeris, target, topos,
horizon_degrees=-34.0/60.0, radius_degrees=0): #?
"""Build a function of time that returns whether a body is up.
This returns a function taking a :class:`~skyfield.timelib.Time`
argument returning ``True`` if the body’s altazimuth ... | 5,299,233 |
def get_all_metric_names():
"""Return a list of all metric names."""
from metric import all_metrics
return all_metrics.keys() | 5,299,234 |
def __get_weather_message_at_location(bot: SopelWrapper, location: dict) -> str:
"""
Gets the formatted weather message at a location based on a supplied location dictionary
"""
log.debug(
"Getting weather message for location '%s'", construct_location_name(location)
)
is_location_best... | 5,299,235 |
def scan_FO(target,in_path,out_path):
"""Searches an in_path csv file for any of the genes in target. Escapes on the first instance. Only gives whether or not those genes exist, prints total number of hits/total
"""
tfile = open(target, "r")
infile = open(in_path,"r")
outfile = open(out_path,"x")
... | 5,299,236 |
def getRootLogger():
"""
Return the root logger. Note that getLogger('') now does the same thing,
so this function is deprecated and may disappear in the future.
"""
return root | 5,299,237 |
def clean_cube(
in_p: Path,
out_p: Path,
label=None,
width=5,
replacement=None,
axis=0,
plot=False,
saveplot=False,
dryrun=False,
keep=False,
):
"""ISIS Cube version of clean().
Please see clean() for argument details.
"""
to_del = isis.PathSet()
# Bit-flip... | 5,299,238 |
def trajectories_and_new_observations_steps(
traj_not_updated,
remaining_new_observations,
next_nid,
return_trajectories_queue,
sep_criterion,
mag_criterion_same_fid,
mag_criterion_diff_fid,
angle_criterion,
orbfit_limit,
max_traj_id,
ram_dir,
store_kd_tree,
run_metri... | 5,299,239 |
def steiner_echo_gen_source(ext, build_dir):
"""
Add Steiner echo classifier source if Fortran 90 compliler available,
if not compiler is found do not try to build the extension.
"""
try:
config.have_f90c()
return [join(config.local_path, '_echo_steiner.pyf'),
join(co... | 5,299,240 |
def ft_flow(flow: nn.ModuleList, x: torch.Tensor):
"""Pass `x` through (forward) through each layer in `flow`."""
# if torch.cuda.is_available():
# f = f.cuda()
for layer in flow:
x, logdet = layer.forward(x)
return x.detach() | 5,299,241 |
def recurse():
"""return (sum, value)"""
child_count = next(it)
metadata_count = next(it)
if child_count == 0:
total_value = total_sum = sum(islice(it, metadata_count))
return total_sum, total_value
total_sum = total_value = 0
child_values = []
for _ in range(child_count):
... | 5,299,242 |
def load_yaml(filename='config.yml', logger=None):
"""
Convenience wrapper around toolchest.yaml::parse to allow you to parse a
file by path+name
:param filename: A yaml file to be parsed
:param logger: Optional logger for potential errors
:return: A dictionary formed out of the yaml data
"... | 5,299,243 |
def par_EORC_JERS_SLC(CEOS_SAR_leader, SLC_par, CEOS_data='-', SLC='-', logpath=None, outdir=None, shellscript=None):
"""
| Reformat EORC processed JERS-1 SLC and generate the ISP parameter file
| Copyright 2008, Gamma Remote Sensing, v1.4 9-Oct-2008 clw
Parameters
----------
CEOS_SAR_leader:
... | 5,299,244 |
def generate(path=None) -> Tuple[np.ndarray, np.ndarray]:
"""
Description: Outputs the daily price of bitcoin from 2013-04-28 to 2018-02-10
"""
data = pd.read_csv(
path or os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../data/crypto.csv")
)
data = jnp.asarray(data[data.C... | 5,299,245 |
def Int():
"""
Returns the intelligence of the player
"""
pass | 5,299,246 |
def generate_seq(length):
"""
Generates a sequence of given length using black magic
Sequence is a string of AGCT
"""
global VALUES
seq = []
intseq = np.floor(np.random.rand(length) * 4)
for i in range(length):
seq.append(VALUES[intseq[i]])
return ''.join(seq) | 5,299,247 |
def load_pakistan_kml(filename, observed):
"""Loads a Pakistan MapMaker KML file w/ defaults for the URL and author."""
setup.setup_datastore()
if isinstance(observed, basestring):
observed = parse_datetime(observed)
user = users.User(PAKISTAN_EMAIL)
load(filename, kml.parse_file, convert_pa... | 5,299,248 |
def find_roles(dbs, role_name=None, page_no=1, filter_sys=False):
"""
角色列表
:param dbs:
:param role_name:
:param page_no:
:param filter_sys:
:return:
"""
roles = dbs.query(SysRole.role_id,
SysRole.role_name,
SysRole.role_desc,
... | 5,299,249 |
def mark_point(image, x, y, color=(255, 255, 0), size=2, show=True, cross=True):
"""
marks a point on the image at the (x,y) position and displays it
"""
ran = list(range(-size, size + 1))
# for i in ran:
# for j in ran:
# if not cross or i == j or i == -j:
# if 0... | 5,299,250 |
def invalid_data_response(request_serializer):
"""
Returns the error message depending on missing/invalid data in serializer.
"""
return Response({'detail': request_serializer.errors,
'data': {}}, status=status.HTTP_400_BAD_REQUEST) | 5,299,251 |
def test_leave_timestamps(src_tree, tmp_path, get_build):
""" Tests creating an export with unchanged timestamps. """
cfg = CFG.format(path=src_tree) + "\ntimestamps='leave'"
export = get_build(cfg, tmp_path)
tree = etree.parse(BytesIO(export))
assert tree.docinfo.root_name == 'Export'
fo... | 5,299,252 |
def plugin( script, **kwargs ):
""" Run external plugins written in R or Python.
Run python code file in parameter `script` or run R code (or code file) given in parameter `script` using rpy2.
You can provide the R code python variables in kwargs and those are automatically transfered to suitable R ... | 5,299,253 |
def FNV64HashString (string: str) -> int:
"""
Hash string using the 64 bit Fowler-Noll-Vo hash function.
:type string: str
:return: Returns hashed string in integer form. Use the ConvertIntegerToHexadecimal function to get it in a base 16 format.
:rtype: int
"""
if not isinstance(string, str):
raise Exception... | 5,299,254 |
def index_generation_with_scene_list(crt_i, max_n, N, scene_list, padding='replicate'):
"""Generate an index list for reading N frames from a sequence of images (with a scene list)
Args:
crt_i (int): current center index
max_n (int): max number of the sequence of images (calculated from 1)
... | 5,299,255 |
def show_coverage():
"""Launch the coverage report."""
if Options.show_coverage:
subprocess.call(['make', 'read-coverage'])
Options.show_coverage = False | 5,299,256 |
def all_paths(directory, extension=None, ignore_dirs=None):
"""Walks a directory and yields all the file paths, possibly filtering by file
extension.
Args:
directory: Path to a directory.
extension: File extension. Optional.
ignore_dirs: Set of absolute directory paths to ignore. Optional.
Yields:... | 5,299,257 |
def add_resource_label(label, resource, policyref, policy_type):
"""Adds a resource label to the global resource label file.
"""
if xm_main.serverType != xm_main.SERVER_XEN_API:
old = server.xend.security.get_resource_label(resource)
if len(old) == 0:
try:
rc = s... | 5,299,258 |
def svn_stream_set_skip(*args):
"""svn_stream_set_skip(svn_stream_t stream, svn_stream_skip_fn_t skip_fn)"""
return _core.svn_stream_set_skip(*args) | 5,299,259 |
def load_manifest(filepath):
"""
Reads k8s manifest files and returns as string
:param str filepath: filename of k8s manifest file to read
:return: k8s resource definition as string
"""
with open(filepath) as handle:
data = handle.read()
try:
manifest = json.loads(data)
... | 5,299,260 |
def regularize_layer_weighted(layers, penalty, tags={'regularizable': True}, **kwargs):
"""
Computes a regularization cost by applying a penalty to a group of layers, weighted by a coefficient for each layer.
Parameters
----------
layers : dict
A mapping from : tuple of class:`Layer` instances to coefficients.
... | 5,299,261 |
def django_icon(name, color=None):
"""Add font-awesome icons in your HTML code"""
return mark_safe(
'<i class="di di-{name}" {color}></i>'.format(
name=name, color='style="color:%s;"' % color if color else ""
)
) | 5,299,262 |
def delGroup(session, name, *args, **kwds):
"""
Delete a group.
"""
getGroup(session, name, *args, **kwds).delete() | 5,299,263 |
def xattr_del(xfile, xsetter):
"""
Remove extended file attributes
Accepts a list/array with attrib names that are not prefixed with the 'user.' namespace
"""
for k in xsetter:
try:
xattr.removexattr(xfile, 'user.'+str(k))
except Exception as e:
logthis("Faile... | 5,299,264 |
def compressibility_drag_wing_total(state,settings,geometry):
"""Sums compressibility drag for all wings combined
Assumptions:
None
Source:
adg.stanford.edu (Stanford AA241 A/B Course Notes)
Inputs:
state.conditions.aerodynamics.drag_breakdown.compressible[wing.tag].compressibility_drag ... | 5,299,265 |
def convert_df_2_string(df):
"""
Convert data frame rows to string output where each new line is defined as \n
"""
# ititialise string
output = 'agent,wkt\n'
for i, row in df.iterrows():
if i == len(df) - 1:
output += str(row['label']) + ',' + str(row['geometry'])
els... | 5,299,266 |
def remove_admin_auth_token(auth_token: str) -> bool:
"""
Removes an admin auth token.
:param auth_token: The auth token to remove.
:return: True/False indicating success of operation.
"""
try:
query = db.session.query(AdminAPIKeyData)
instance = query.get(ident=auth_token)
... | 5,299,267 |
def findinvwindows(s, reffa, svlength):
"""Convert an inversion alignment to an inversion SV window, and yield the window. """
if not is_inv_aln(s) or s.query_alignment_length < svlength:
raise StopIteration
qseq = s.query_sequence.upper()
rseq = reffa.fetch(s.reference_name, s.reference_start, ... | 5,299,268 |
def Packet_genWriteBinaryOutput1(errorDetectionMode, buffer, size, asyncMode, rateDivisor, commonField, timeField, imuField, gpsField, attitudeField, insField):
"""Packet_genWriteBinaryOutput1(vn::protocol::uart::ErrorDetectionMode errorDetectionMode, char * buffer, size_t size, uint16_t asyncMode, uint16_t rateDi... | 5,299,269 |
def energy_window(lower, upper):
"""
Creates an eigenvalue weighting function that only takes into account eigenvalues in a certain energy window.
:param lower: Lower bound of the energy window.
:type lower: float
:param upper: Upper bound of the energy window.
:type upper: float
"""
l... | 5,299,270 |
def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):
"""
Call in a loop to create terminal progress bar
:param iteration: - Required : current iteration (Int)
:param total: - Required : total iterations (Int)
:param prefix: - Optional : prefix string (Str)
:... | 5,299,271 |
def main():
"""
Main routine: shows disclaimer, initializes database, gets case details, determines which files to parse
:return: n/a
"""
easygui.buttonbox(msg=' '.join(['CDR Mapper\n', '--------------------------\n',
'CDR Mapper will plot CDR and cell site / towe... | 5,299,272 |
def svn_fs_upgrade(*args):
"""svn_fs_upgrade(char const * path, apr_pool_t pool) -> svn_error_t"""
return _fs.svn_fs_upgrade(*args) | 5,299,273 |
def parse_args():
""" Parse input arguments
"""
parser = argparse.ArgumentParser(description='Prepare MCG roidb')
parser.add_argument('--input', dest='input_dir',
help='folder contain input mcg proposals',
default='data/MCG-raw/', type=str)
parser.add_... | 5,299,274 |
def mitm_dummy(message: Message, topic: Topic):
"""
Generic dummy function for the mitm. Just sends each message twice
:param message: The last received message from the publisher
:param topic: the topic
:return:
"""
topic.publish(message)
topic.publish(message) | 5,299,275 |
def update_rt():
"""runs Dijkstra to update the Routing Table"""
global start_dijkstra
if start_dijkstra:
global routingTable
threadLock.acquire()
rt = dijkstra(lsdb)
routingTable = rt
threadLock.release()
for key in routingTable.keys():
print("... | 5,299,276 |
def get_distance_map(img, bbox):
"""
img: croped image, PIL image (h,w,3)
bbox: (x1,y1,x2,y2) bbox from annotation
return:
distance_map: numpy array of (h,w) with distance map in
ECCV paper "Deep GrabCut for Object Selection"
"""
img_arr = np.asarray(img)
distance_map ... | 5,299,277 |
def multi(ldict, selfname, production, sep=None):
"""
Usage:
multi(locals(), NAME, P[, sep=SEP])
where P and SEP are production names.
This produces a production named NAME of the form
NAME ::= empty | P (SEP P)*
that produces tuples of whatever P produces.
"""
if sep... | 5,299,278 |
def make_channel_eroded_layer(
name,
layer_size,
channel_width,
edge_width,
color_RGB=None,
z_position=0.0,
parent=None,
material=None,
**kwargs,
):
"""Create a 3D print eroded channel layer.
Args:
name (str): Name to give the object.
layer_size (3-element tu... | 5,299,279 |
def deletealertrulebasedonip(ip, file_name=None):
"""
Deletes a Snort rule to alert based on traffic incoming from an ip address.
Arguments:
ip: String with an ip address.
filename: String with a path to a Snort rule file. Passed directly to writerule.
"""
found = Fal... | 5,299,280 |
def create(path):
"""
Create the HDF5 backup database with the required arrays.
The required arrays are an array for the simulation results, an array for
the simulation timings, and an array for tracking the status.
Parameters
----------
path : str
The path of the HDF5 backup datab... | 5,299,281 |
def handle_piecewise_function(universe, x_values, fx_values):
"""
This function receives the universe and the values for x (`x_values`)
and f(x) (`fx_values`).
It generate new fx values for the given arguments, considering that it will fill the
return np.array with zeroes for the f(x) of x that wher... | 5,299,282 |
def submit_new_experiment():
# TODO: start new experiment track
"""
Submit a new experiment action.
1. Retrieve the config from user's config table
2. Retrieve the csv to user's csv table
x. Create ABEX Config
y. Submit the ABEX experiment
"""
data = request.get_data()
print(f"D... | 5,299,283 |
def export_file(isamAppliance, instance_name, file_name, file_path, check_mode=False, force=False):
"""
Exporting a file in the API Access Control documentation root
"""
if os.path.exists(file_path) is True:
warn_str = "File {0} already exists".format(file_path)
warnings = [warn_str]
... | 5,299,284 |
def to_binary(x, num_bits):
"""Transform an array of floats into binary representation.
Parameters
----------
x: ndarray
Input array containing float values. The first dimension has to be of
length 1.
num_bits: int
The fixed point precision to be used when converting to bin... | 5,299,285 |
def import_difmap_model(mdl_fname, mdl_dir=None, remove_last_char=True):
"""
Function that reads difmap-format model and returns list of ``Components``
instances.
:param mdl_fname:
File name with difmap model.
:param mdl_dir: (optional)
Directory with difmap model. If ``None`` then ... | 5,299,286 |
def load_user_roles(user, roles):
"""
Loads user roles from keycloak to django on user login
Args:
user: (Not user. Could remove)
user_name: user_name of user
roles: List of keycloak roles
Returns: None
"""
# Remove any existing roles that ar... | 5,299,287 |
def random_image(breed=None, subbreed=None):
"""Gets a random dog image. Returns a url as a string"""
if breed == None and subbreed == None:
return _get('breeds/image/random')
elif subbreed == None:
return _get('breed/{0}/images/random'.format(breed))
else:
return _get('breed/{0}... | 5,299,288 |
def get_calibration_info():
"""
Gets the last modified date for any existing homography calibration files.
"""
camera_pairs_dict = redis_tools.get_dict(db,'camera_pairs_dict')
calibration_info = mct_introspection.get_transform_2d_calibration_info()
calibration_info_mod = {}
for pairs_list i... | 5,299,289 |
def bold(string: str) -> str:
"""Add bold colour codes to string
Args:
string (str): Input string
Returns:
str: Bold string
"""
return "\033[1m" + string + "\033[0m" | 5,299,290 |
def random_quat_biax():
"""Return a random rotation quat for biaxial molecules."""
phi = random.uniform(0, 2*math.pi)
ct = random.uniform(-1, 1)
theta = math.acos(ct) # mozna tez -ct
psi = random.uniform(0, 2*math.pi)
quat = Quat.from_eulers(phi, theta, psi)
return quat | 5,299,291 |
def global_step_from_engine(engine: Engine) -> Callable:
"""Helper method to setup `global_step_transform` function using another engine.
This can be helpful for logging trainer epoch/iteration while output handler is attached to an evaluator.
Args:
engine (Engine): engine which state is used to pr... | 5,299,292 |
def test_superuser_can_change_password_for_existing_user(superuser, user, testapp):
"""Change password for an existing user."""
# Check expected premises.
user_creator = user.created_by
initial_modified_by = user.modified_by
assert user_creator != superuser and initial_modified_by != superuser
#... | 5,299,293 |
def extract_lut_priors_from_atlas(atlas_file,contrast_name):
"""
Given an MGDM segmentation priors atlas file, extract the lut and identify the start index (in the file) of the
contrast of interest, and the number of rows of priors that it should have. Returns pandas dataframe of lut,
contrast index, nu... | 5,299,294 |
def load_environment(context, key, primary=True):
"""
Loads an environment dict from persistent storage. This helps get
around the 8192 character limit in ECS Tasks.
:param context: a aws_lambda_fsm.fsm.Context instance
:param key: a str key as returned from store_environment
:param primary: if... | 5,299,295 |
def get_trans_co(x2ys, n_trans):
"""Use co-occurrences to compute scores."""
x2ys_co = dict()
for x, ys in x2ys.items():
ys = [y for y, cnt in sorted(ys.items(), key=operator.itemgetter(1), reverse=True)[:n_trans]]
x2ys_co[x] = ys
return x2ys_co | 5,299,296 |
def ShowZalloc(cmd_args=None):
""" Prints a zallocation from the zallocations array based off its index and prints the associated symbolicated backtrace.
Usage: showzalloc <index>
"""
if not cmd_args:
print ShowZalloc.__doc__
return
if unsigned(kern.globals.zallocations) == 0:
... | 5,299,297 |
def replace(
source: Union[list, set, str, tuple], var: Dict[str, Union[str, int, bool, float]]
) -> None:
"""
Various types of multi-replace.
Parameters
==========
source: typing.Union[list, set, str, tuple]
string or list before being replaced.
var: typing.Dict[str, typing.Union[s... | 5,299,298 |
def constraints(logits, attributes):
""" E[XZ] - E[X]E[Z]
"""
EPS = 1e-8
group_a = jnp.where(attributes > 0, logits, 0).sum() / (jnp.where(attributes > 0, 1, 0).sum() + EPS)
group_b = jnp.where(attributes <= 0, logits, 0).sum() / (jnp.where(attributes <= 0, 1, 0).sum() + EPS)
# correlation = jnp.where(attri... | 5,299,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.