content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def detect_or_create_config(config_file, output_root, theseargs,
newname=None, logger=None):
""" return path to config file, or die trying.
if a config file exists, just return the path. If not,
create it using "make_riboSeed_config.py"
"""
assert logger is not None, "mu... | 5,334,200 |
def convert_to_file(genotype_input, output_file):
"""Convert a Family Tree DNA file and output GFF-formatted data to file"""
output = output_file # default assumes writable file object
if isinstance(output_file, str):
output = autozip.file_open(output_file, 'w')
conversion = convert(genotype_in... | 5,334,201 |
def gaussian(x, p):
"""
Gaussian function
@param x : variable
@param p : parameters [height, center, sigma]
"""
return p[0] * (1/np.sqrt(2*pi*(p[2]**2))) * np.exp(-(x-p[1])**2/(2*p[2]**2)) | 5,334,202 |
def get_exploration_ids_subscribed_to(user_id):
"""Returns a list with ids of all explorations that the given user
subscribes to.
WARNING: Callers of this function should ensure that the user_id is valid.
Args:
user_id: str. The user ID of the subscriber.
Returns:
list(str). IDs o... | 5,334,203 |
def JC_LAIeffective(self, k):
"""
REQUIRED INPUT:
- LAI (-)
PARAMETERS:
- none (Allen et al., 2006 & Zhou et al., 2006)
"""
self.JC_laiEff = self.LAI / (0.2 * self.LAI + 1) | 5,334,204 |
def generate_trials(olh_samples: np.array, roi_space: Space) -> list[dict]:
"""
Generates trials from the given normalized orthogonal Latin hypercube samples
Parameters
----------
olh_samples: `numpy.array`
Samples from the orthogonal Latin hypercube
roi_space: orion.algo.space.Space
... | 5,334,205 |
def check_all_flash(matrix_2d):
"""
Check if all octopuses flashed.
:param matrix_2d: 2D matrix
:return: Boolean
"""
for line in matrix_2d:
for digit in line:
if digit != 0:
return True
return False | 5,334,206 |
def validate_content_length_header_not_too_large(
request_headers: Dict[str, str],
request_body: bytes,
) -> None:
"""
Validate the ``Content-Length`` header is not too large.
Args:
request_headers: The headers sent with the request.
request_body: The body of the request.
Raise... | 5,334,207 |
def train(request, pretrained):
"""
Train a model, and save it to disk.
"""
if pretrained:
return dash.no_update
dataset = get_dataset(request["dataset_name"])
train_set = dataset["train_set"]
val_set = dataset["val_set"]
lake_set = dataset["lake_set"]
n_classes = dataset["n_... | 5,334,208 |
def test_create_programs_without_revise(data_dir: str):
"""Tests creating programs without revise calls.
It should not use refer calls even with a valid salience model.
"""
utterance_tokenizer = UtteranceTokenizer()
salience_model = VanillaSalienceModel()
for trade_dialogue in load_test_trade_... | 5,334,209 |
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Add sensors for passed config_entry in HA."""
wind = hass.data[DOMAIN][config_entry.entry_id]
new_devices = []
for windturbine in wind.windturbines:
new_devices.append(PulsingSensor(windturbine))
if new_devices:
... | 5,334,210 |
def cache_get(cache, key, fcn, force=False):
"""Get key from cache, or compute one."""
if cache is None:
cache = {}
if force or (key not in cache):
cache[key] = fcn()
return cache[key] | 5,334,211 |
def savefig(path):
"""matplotlib.savefig"""
plt.savefig(path) | 5,334,212 |
def _BreadthFirstSearch(to_visit, children, visited_key=lambda x: x):
"""Runs breadth first search starting from the nodes in |to_visit|
Args:
to_visit: the starting nodes
children: a function which takes a node and returns the nodes adjacent to it
visited_key: a function for deduplicating node visits.... | 5,334,213 |
def readfq(fp): # this is a generator function
"""
FASTA/Q parser from Heng Li:
https://github.com/lh3/readfq/blob/master/readfq.py
"""
last = None # this is a buffer keeping the last unprocessed line
while True: # mimic closure; is it a bad idea?
if not last: # the first record or a re... | 5,334,214 |
def get_receptor_from_receptor_ligand_model(receptor_ligand_model):
"""
This function obtains the name of receptor based on receptor_ligand_model
Example of input: compl_ns3pro_dm_0_-_NuBBE_485_obabel_3D+----+20
"""
separator_model = get_separator_filename_mode()
separator_receptor = "_-_"... | 5,334,215 |
def build_model():
"""
Selects the best model with optimal parameters
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('svd', TruncatedSVD()),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier(class_weight='balan... | 5,334,216 |
def monthly_expenses(costs, saleprice, propvalue, boyprincipal, rent):
"""Calculate monthly expenses
costs list of MonthlyCost objects
saleprice sale price of the property
propvalue actual value of the property
boyprincipal principal at beginning of year to calculate for
... | 5,334,217 |
def test_reg_user_cannot_view_user_dne(reg_user_headers):
""" regular user cannot view user that doesn't exist """
org = reg_user_headers['CVE-API-ORG']
user = str(uuid.uuid4())
res = requests.get(
f'{env.AWG_BASE_URL}{ORG_URL}/{org}/user/{user}',
headers=reg_user_headers
)
asser... | 5,334,218 |
def get_spitfire_template_class(prefer_c_extension=True):
"""Returns an appropriate SpitfireTemplate class.
Args:
prefer_c_extension: If set True and _template loaded properly, use the
C extension's baseclass implementation.
Returns:
A SpitfireTemplate class with an appropriate base cl... | 5,334,219 |
def _create_player_points(
pool: pd.DataFrame,
teams: np.ndarray,
n_iterations: int,
n_teams: int,
n_players: int,
team_points: np.ndarray
) -> np.ndarray:
"""Calculates playerpoints
Args:
pool (pd.DataFrame): the player pool
statscols... | 5,334,220 |
def generate_system_exe_funcs():
""" Generates the functions needed to process the `System`s. """
max_parameters = 30
path = "./systems/system_exe_funcs.gen.h"
internal_generate_system_exe_funcs(False, max_parameters, path) | 5,334,221 |
def get_SolverSettings(instance):
""" get solver settings """
instance.sSolver = ""
instance.dicPyomoOption = {}
instance.dicSolverOption = {}
file_setting = "../Input/1_model_config/01_SolverConfig.csv"
dt_data = genfromtxt(file_setting, dtype = str, skip_header=0, delimiter=',')
... | 5,334,222 |
def on_reported(client, userdata, message):
"""
*Callback function parses a FireReported message, switches FireState from "detected" to "reported", and records time of first report, name of satellite reporting the fire, and groundId receiving the report*
.. literalinclude:: /../examples/firesat/fires/main_... | 5,334,223 |
def demod_from_array(mod_array, faraday_sampling_rate = 5e6, start_time = 0, end_time = 'max', reference_frequency = 736089.8, reference_phase_deg = 0, lowpas_freq = 10000, plot_demod = False, decimate_factor = 4, time_stamp = '', label = '', save = False):
"""
Sweet lord above this function washes the dishes as w... | 5,334,224 |
def listen(path, calfile=None, transitspeed=3,
platform='Unknown', savepng=False, reportrows=10, recipient=None):
"""
Listen for new raw files. When find a new one, it carries out the following
actions:
1) Read RAW data
2) Process RAW data (calibration, de-noising and target ... | 5,334,225 |
def test_provider_system_hook_dicts_merge(change_dir, clean_outputs):
"""Verify the hook call works properly."""
output = tackle('.', context_file='merge.yaml', no_input=True)
assert output['merge_map']['stuff'] == 'blah'
assert len(output['merge_map']) == 3 | 5,334,226 |
async def test_dimmable_light(hass):
"""Test dimmable light discovery."""
device = (
'light.test_2', 'on', {
'brightness': 128,
'friendly_name': "Test light 2", 'supported_features': 1
})
appliance = await discovery_test(device, hass)
assert appliance['endpointId... | 5,334,227 |
def find_many_files_gridrad(
top_directory_name, radar_field_names, radar_heights_m_agl,
start_time_unix_sec, end_time_unix_sec, one_file_per_time_step=True,
raise_error_if_all_missing=True):
"""Finds many files with storm-centered images from GridRad data.
T = number of "file times"
... | 5,334,228 |
def cli_num_postproc_workers(
usage_help: str = "Number of workers to post-process the network output.",
default: int = 0,
) -> callable:
"""Enables --num-postproc-workers option for cli."""
return click.option(
"--num-postproc-workers",
help=add_default_to_usage_help(usage_help, default... | 5,334,229 |
def create_cluster(redshift, iam, ec2, cluster_config, wait_status=False):
""" Create publicly available redshift cluster per provided cluster configuration.
:param redshift: boto.redshift object to use
:param iam: boto.iam object to use
:param ec2: boto.ec2 object to use
:param cluster_config: con... | 5,334,230 |
def index():
""" Application entry point. """
return render_template("index.html") | 5,334,231 |
def add_filepath(parent, filename, definition=''):
"""returns the path to filename under `parent`."""
if filename is None:
raise ValueError("filename cannot be None")
# FIXME implementation specifics! only works with FileSystemDatabase
parent_path = parent._repr
file_path = parent_path / f... | 5,334,232 |
def silhouette_to_prediction_function(
silhouette: np.ndarray
) -> Callable[[np.ndarray], bool]:
"""
Takes a silhouette and returns a function.
The returned function takes x,y point and
returns wether it is in the silhouette.
Args:
silhouette:
Returns:
"""
def predi... | 5,334,233 |
def create_calendar(year=None, month=None):
"""
Create an inline keyboard with the provided year and month
"""
now = datetime.datetime.now()
if year is None:
year = now.year
if month is None:
month = now.month
data_ignore = create_calendar_callback_data("IGNORE", year, month,... | 5,334,234 |
def read_image(link, size):
""" Read image on link and convert it to given size
Usage:
image = readImage(link, size)
Input variables:
link: path to image
size: output size of image
Output variables:
image: read and resized image
"""
image ... | 5,334,235 |
def make_send_data(application_preset):
"""Generate the data to send to the protocol."""
if application_preset == 'none':
# data = bytes([i for i in range(32)])
# data = bytes([i for i in range(54)]) # for teensy 4.0
data = bytes([i for i in range(54)]) # for teensy lc & micro
... | 5,334,236 |
def dp4a(x_scope="local", y_scope="local", z_scope="local", dtypes=("int8", "int8")):
"""
Int8 dot product reduced by every 4 elements using __dp4a
Parameters
----------
x_scope : str, optional
The storage scope of buffer for lhs
y_scope : str, optional
The storage scope of buff... | 5,334,237 |
def _bytes_iterator_py2(bytes_):
"""
Returns iterator over a bytestring in Python 2.
Do not call directly, use bytes_iterator instead
"""
for b in bytes_:
yield b | 5,334,238 |
def test_and():
"""Test the and instruction."""
and_regex = Instructions["and"].regex
assert re.match(and_regex, "and $t1, $t2, $t1") is not None
assert re.match(and_regex, "and $t1, $t2") is None
assert re.match(and_regex, "and $t1, $t2, 33") is None | 5,334,239 |
def fileexists(filename):
"""Replacement method for os.stat."""
try:
f = open( filename, 'r' )
f.close()
return True
except:
pass
return False | 5,334,240 |
def debug_print(message, *args):
""" Method similar to LOGGER.log, but also replaces all TF ops/tensors with their names
e.g. debug_print('see tensors %s for %s', tensor_list, [1,2,3])
"""
if not DEBUG_LOGGING:
return
LOGGER.debug(message, *[format_ops(arg) for arg in args]) | 5,334,241 |
def test_knowledge_graph_init(graph_mutation_client, graph_mutation_responses):
"""Test knowldge graph client initialization."""
return graph_mutation_client.named_types | 5,334,242 |
def read_camera_matrix(filename):
"""
Read camera matrix from text file exported by PhotoScan
"""
with open(filename, 'r') as f:
s = f.read()
s = s.split(',')
s = [x.strip('\Matrix([[') for x in s]
s = [x.strip(']])') for x in s]
s = [x.strip('[') for x in s]
s = [x.strip(']... | 5,334,243 |
def level_18():
"""
Challenge 18: Telling the difference with deltas
URL: http://www.pythonchallenge.com/pc/return/balloons.html
Split lines from [0:53] and [56:109]
"""
deltas = open('text/lv18-delta.txt', 'r').read()
lines = deltas.splitlines()
left, right, png = [], [], ['', '', '']
... | 5,334,244 |
def plot_boxplots(data, hidden_states):
"""
Plot boxplots for all variables in the dataset, per state
Parameters
------
data : pandas DataFrame
Data to plot
hidden_states: iteretable
the hidden states corresponding to the timesteps
"""
column_names = data.columns
fig... | 5,334,245 |
def find_child_joints(model, joint_name):
""" Find all the joints parented to the given joint. """
joint_id = joint_name_to_index(model)
link_id = link_name_to_index(model)
# FIXME : Add exception to catch invalid joint names
joint = model.joints[joint_id[joint_name]]
clink = joint.child
ret... | 5,334,246 |
def main():
"""cli entrypoint"""
parser = argparse.ArgumentParser(description="Cleanup docker registry")
parser.add_argument("-i", "--image",
dest="image",
required=True,
help="Docker image to cleanup")
parser.add_argument("-v", "--... | 5,334,247 |
def stem(path: str) -> str:
"""returns the stem of a path (path without parent directory and without extension)
e.g
j.sals.fs.stem("/tmp/tmp-5383p1GOmMOOwvfi.tpl") -> 'tmp-5383p1GOmMOOwvfi'
Args:
path (str): path we want to get its stem
Returns:
str: path without parent direct... | 5,334,248 |
def fluent_text(field, schema):
"""
Accept multilingual text input in the following forms
and convert to a json string for storage:
1. a multilingual dict, eg.
{"en": "Text", "fr": "texte"}
2. a JSON encoded version of a multilingual dict, for
compatibility with old ways of loading ... | 5,334,249 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Tasmota sensor dynamically through discovery."""
@callback
def async_discover(
tasmota_entity: HATasmotaEntity, discovery_hash: DiscoveryHashType
... | 5,334,250 |
def palette_color_brewer_q_Set3(reverse=False):
"""Generate set3 Brewer palette of a given size ... interpolate as needed ... best for discrete mapping
Args:
reverse: order the colors backward as compared to standard Brewer palette
Returns:
lambda: generates a list of colors
See Also:... | 5,334,251 |
def process_file(path, proc_mode, series=None, subimg_offset=None,
subimg_size=None, roi_offset=None, roi_size=None):
"""Processes a single image file non-interactively.
Assumes that the image has already been set up.
Args:
path (str): Path to image from which MagellanMapper-s... | 5,334,252 |
def get_loss_function(identifier):
"""
Gets the loss function from `identifier`.
:param identifier: the identifier
:type identifier: str or dict[str, str or dict]
:raise ValueError: if the function is not found
:return: the function
:rtype: function
"""
return _get(identifier, loss_... | 5,334,253 |
def find_defender(ships, side):
"""Crude method to find something approximating the best target when attacking"""
enemies = [x for x in ships if x['side'] != side and x['hp'] > 0]
if not enemies:
return None
# shoot already wounded enemies first
wounded = [x for x in enemies if x['hp... | 5,334,254 |
def get_parameters(image_path):
"""
Parses the image path to dictionary
:param str image_path: image path
:rtype dict
"""
image_path = image_path
image_directory = os.path.dirname(image_path)
image_filename = os.path.basename(image_path)
image_name = image_filename.split('.')[0]
... | 5,334,255 |
def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):
"""
对网关和目标进行投毒攻击后,我们就能嗅探到目标机器进出的流量了
:param gateway_ip:
:param gateway_mac:
:param target_ip:
:param target_mac:
:return:
"""
global poisoning
# 构建欺骗目标IP的ARP请求
poison_target = ARP()
poison_target.op = 2
... | 5,334,256 |
def Create_clump_summaries(feature_file,simplify_threshold):
""" Employs Panda Shapely library to simplify polygons by eliminating almost
colinear vertices. Generates two data structures: First - sort_clump_df: Panda Dataframe
containing the longest line in the simplified and unsimplified polygon, po... | 5,334,257 |
def norm(point):
"""Returns the Euclidean norm of a point from origin.
Parameters
==========
point: This denotes a point in the dimensional space.
Examples
========
>>> from sympy.integrals.intpoly import norm
>>> from sympy.geometry.point import Point
>>> norm(Point(2, 7))
sqr... | 5,334,258 |
def read_reducing():
"""Return gas resistance for reducing gases.
Eg hydrogen, carbon monoxide
"""
setup()
return read_all().reducing | 5,334,259 |
def access_rights_to_metax(data):
"""
Cherry pick access right data from the frontend form data and make it comply with Metax schema.
Arguments:
data {object} -- The whole object sent from the frontend.
Returns:
object -- Object containing access right object that comply to Metax schem... | 5,334,260 |
def read_toml_file(input_file, config_name = None, confpaths = [".", TCFHOME + "/" + "config"]):
"""
Function to read toml file and returns the toml content as a list
Parameters:
- input_file is any toml file which need to be read
- config_name is particular configuration to pull
- d... | 5,334,261 |
def assert_images_equal(image_1: str, image_2: str):
"""
Assert wether 2 images are the same
"""
img1 = Image.open(image_1)
img2 = Image.open(image_2)
# Convert to same mode and size for comparison
img2 = img2.convert(img1.mode)
img2 = img2.resize(img1.size)
sum_sq_diff = np.sum((n... | 5,334,262 |
def and_sum (phrase):
"""Returns TRUE iff every element in <phrase> is TRUE"""
for x in phrase:
if not x:
return False
return True | 5,334,263 |
def history_menu(chatid, message_id=False):
"""
Вывод истории заказов
:param chatid: id пользователя, которому нужно отправить
:param message_id: если нужно отредактировать существующее сообщение, то отпредактирует его, иначе отправит новым сообщением
:return:
"""
menu = types.InlineKeyboar... | 5,334,264 |
def load_data(filename: str):
"""
Load house prices dataset and preprocess data.g
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Series]
"""
... | 5,334,265 |
def eccanom(M, e):
"""Finds eccentric anomaly from mean anomaly and eccentricity
This method uses algorithm 2 from Vallado to find the eccentric anomaly
from mean anomaly and eccentricity.
Args:
M (float or ndarray):
mean anomaly
e (float or ndarray):
eccentrici... | 5,334,266 |
def transform_frame(frame: np.array,
transform: AffineTransformation,
rotate: bool = False,
center_crop: bool = False) -> np.array:
""" Perform affine transformation of a single image-frame.
Parameters
----------
frame : array
Image fr... | 5,334,267 |
def _check_nvidia_driver_version(args):
"""If --nvidia-driver-version is set, warn that it is ignored."""
if args.nvidia_driver_version:
print('***WARNING: The --nvidia-driver-version flag is deprecated and will '
'be ignored.') | 5,334,268 |
def run_check(cmd: typing.Sequence[typing.Union[os.PathLike, str]], *,
input_lines: typing.Optional[BytesOrStrIterator] = ...,
encoding: typing.Optional[str] = ...,
capture_output: bool = ...,
quiet: bool = ...,
**kwargs) -> subprocess.CompletedProce... | 5,334,269 |
def TEMA(equity, start=None, end=None, timeperiod=30):
"""Triple Exponential Moving Average
:param timeperiod:
:return:
"""
close = np.array(equity.hp.loc[start:end, 'close'], dtype='f8')
real = talib.TEMA(close, timeperiod=timeperiod)
return real | 5,334,270 |
def get_miner_pool_by_owner_id():
"""
存储提供者详情
:return:
"""
owner_id = request.form.get("owner_id")
data = MinerService.get_miner_pool_by_no(owner_id)
return response_json(data) | 5,334,271 |
def notFound(e):
"""View for 404 page."""
return render_template('content/notfound.jinja.html'), 404 | 5,334,272 |
def watch_graph_with_blacklists(run_options,
graph,
debug_ops="DebugIdentity",
debug_urls=None,
node_name_regex_blacklist=None,
op_type_regex_blacklist=None):
... | 5,334,273 |
def get_stay(admission_date, exit_date):
"""Method to get exit date."""
try:
if not exit_date:
exit_date = datetime.now().date()
no_days = exit_date - admission_date
# Get More
years = ((no_days.total_seconds()) / (365.242 * 24 * 3600))
years_int = int(years)
... | 5,334,274 |
def compress(X, halve, g = 0, indices = None):
"""Returns Compress coreset of size 2^g sqrt(n) or, if indices is not None,
of size 2^g sqrt(len(indices)) as row indices into X
Args:
X: Input sequence of sample points with shape (n, d)
halve: Algorithm that takes an input a set of points an... | 5,334,275 |
def filter_objects(objs, labels, none_val=0):
"""Keep objects specified by label list"""
out = objs.copy()
all_labels = set(nonzero_unique(out))
labels = set(labels)
remove_labels = all_labels - labels
for l in remove_labels:
remove_object(out, l)
return out | 5,334,276 |
def print_rule(rule,counter):
""" Helper function to print a rule """
print ("------------------------------------------------")
print (" NORM Number={}".format(str(counter)))
print ("------------------------------------------------")
if rule[0]=="Per":
print (" > PERMITTED ... | 5,334,277 |
def test_restarting_completed_job(spark_client, feature_table):
""" Job has succesfully finished on previous try """
job = SimpleStreamingIngestionJob(
"", "default", feature_table, SparkJobStatus.COMPLETED
)
spark_client.feature_store.list_feature_tables.return_value = [feature_table]
spar... | 5,334,278 |
def get_index_freq(freqs, fmin, fmax):
"""Get the indices of the freq between fmin and fmax in freqs
"""
f_index_min, f_index_max = -1, 0
for freq in freqs:
if freq <= fmin:
f_index_min += 1
if freq <= fmax:
f_index_max += 1
# Just check if f_index_max is not... | 5,334,279 |
def get_gene_mod(gene_id, marker_id):
"""Retrieves a GeneMod model if the gene / marker pair already exists,
or creates a new one
"""
if gene_id in ("None", None):
gene_id = 0
if marker_id in ("None", None):
marker_id = 0
gene_mod = GeneMod.query.filter_by(gene_id=gene_id, mar... | 5,334,280 |
def random_matrix(shape, tt_rank=2, mean=0., stddev=1.,
dtype=tf.float32, name='t3f_random_matrix'):
"""Generate a random TT-matrix of the given shape with given mean and stddev.
Entries of the generated matrix (in the full format) will be iid and satisfy
E[x_{i1i2..id}] = mean, Var[x_{i1i2..id... | 5,334,281 |
def set_dict_defaults_inplace(dct, *args):
"""
Modifies a dictionary in-place by populating key/value pairs present in the
default dictionaries which have no key in original dictionary `dct`. Useful
for passing along keyword argument dictionaries between functions.
Parameters
----------
dct... | 5,334,282 |
def triangulate_polylines(polylines, holePts, lowQuality = False, maxArea = 0.01):
"""
Convenience function for triangulating a polygonal region using the `triangle` library.
Parameters
----------
polylines
List of point lists, each defining a closed polygon (with coinciding
first a... | 5,334,283 |
def inclination(x, y, z, u, v, w):
"""Compute value of inclination, I.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
... | 5,334,284 |
def test_ConstantsValues():
"""Test :mod:`~utilipy.constants.values.ConstantsValues`."""
# ----------------------------
# Frozen
f = values.ConstantsValues(frozen=True)
assert f.from_frozen is True
_names = set(data.__all_constants__)
_names.update({"c_ms", "c_kms", "AU_to_pc", "pc_to_AU"... | 5,334,285 |
def tile_bbox(bbox, grid_width):
"""
Tile bbox into multiple sub-boxes, each of `grid_width` size.
>>> list(tile_bbox((-1, 1, 0.49, 1.51), 0.5)) #doctest: +NORMALIZE_WHITESPACE
[(-1.0, 1.0, -0.5, 1.5),
(-1.0, 1.5, -0.5, 2.0),
(-0.5, 1.0, 0.0, 1.5),
(-0.5, 1.5, 0.0, 2.0),
(0.0, 1.0, ... | 5,334,286 |
def OctahedralGraph():
"""
Return an Octahedral graph (with 6 nodes).
The regular octahedron is an 8-sided polyhedron with triangular faces. The
octahedral graph corresponds to the connectivity of the vertices of the
octahedron. It is the line graph of the tetrahedral graph. The octahedral is
s... | 5,334,287 |
def peak_detect(y, delta, x=None):
""" Find local maxima in y.
Args:
y (array): intensity data in which to look for peaks
delta (float): a point is considered a maximum peak if it has the maximal value, and was preceded (to the left) by a value lower by DELTA.
x (array, optional):... | 5,334,288 |
def quadruplet_fixated_egomotion( filename ):
"""
Given a filename that contains 4 different point-view combos, parse the filename
and return the pair-wise camera pose.
Parameters:
-----------
filename: a filename in the specific format.
Returns:
-----------
egomotion: a nu... | 5,334,289 |
def test_filter_log_entries_incomplete_entries():
"""
Checks if filter removes incomplete entries.
"""
filter_instance = _create_log_filter()
entries = [
{
'some_field': 'value0',
'filtered_field': 'no filter0',
'additional_field': ''
},
{
... | 5,334,290 |
def moshinsky(state1,state2,stater,statec,state,type):
"""
calculates the moshinsky coefficients used to transform between the two-particle and relative-center of mass frames.
w1 x w2->w
wr x wc->w
type can be either "SU3" or "SO3"
if type=="SU3":
state1,state2,stater,statec,state are simply SU3State class
... | 5,334,291 |
def test_lie_algebra_nqubits_check():
"""Test that we warn if the system is too big."""
@qml.qnode(qml.device("default.qubit", wires=5))
def circuit():
qml.RY(0.5, wires=0)
return qml.expval(qml.Hamiltonian(coeffs=[-1.0], observables=[qml.PauliX(0)]))
with pytest.warns(UserWarning, mat... | 5,334,292 |
def _write_k_file(output_k, causal_snp_number):
"""
Writes the Casual SNP K file.
Let's just write the file that I used in the example.
0.6 0.3 0.1
"""
# Write the number of K files.
causal_snp_number = 3
threshold = 1.0/(causal_snp_number)
thresh_list = [threshold] *... | 5,334,293 |
def get_elastic_apartments_not_for_sale():
"""
Get apartments not for sale but with published flags
"""
s_obj = (
ApartmentDocument.search()
.filter("term", publish_on_oikotie=True)
.filter("term", publish_on_etuovi=True)
.filter("term", apartment_state_of_sale__keyword=A... | 5,334,294 |
def promptYesNoCancel(prompt, prefix=''):
"""Simple Yes/No/Cancel prompt
:param prompt: string, message to the user for selecting a menu entry
:param prefix: string, text to print before the menu entry to format the display
:returns: string, menu entry text
"""
menu = [
{'index': 1, 'te... | 5,334,295 |
def gradcheck_naive(f, x):
"""
Implements a manual gradient check: this functions is used as a helper function in many places
- f should be a function that takes a single argument and outputs the cost and its gradients
- x is the point (numpy array) to check the gradient at
"""
rndstate = ran... | 5,334,296 |
def cal_mae_loss(logits, gts, reduction):
"""
:param preds: (N,C,H,W) logits predicted by the model.
:param gts: (N,1,H,W) ground truths.
:param reduction: specifies how all element-level loss is handled.
:return: mae loss
"""
probs = logits.sigmoid()
loss = (probs - gts).abs()
retur... | 5,334,297 |
def runserver():
"""Run CRIPTs using the built-in runserver."""
with cd(APP_ROOT):
run("python manage.py runserver 0.0.0.0:8080") | 5,334,298 |
def divideByFirstColumn(matrix):
"""This function devide a matrix by its first column to resolve
wrong intemsity problems"""
result = (matrix.T / matrix.sum(axis=1)).T
return result | 5,334,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.