content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_start_sep_graph() -> nx.Graph:
"""test graph with known clique partition that needs start_separate"""
G = nx.Graph()
G.add_nodes_from(range(6))
G.add_edges_from([(0, 1, {'weight': 1.0}), (0, 2, {'weight': -10}), (0, 3, {'weight': 1}), (0, 4, {'weight': -10}), (0, 5, {'weight': -10}),
... | 24,600 |
def structure(table_toplevels):
"""
Accepts an ordered sequence of TopLevel instances and returns a navigable object structure representation of the
TOML file.
"""
table_toplevels = tuple(table_toplevels)
obj = NamedDict()
last_array_of_tables = None # The Name of the last array-of... | 24,601 |
def evaluate(exe, metric, loss, correct, dev_program, data_loader,
phase="eval"):
"""
The evaluate process, calcluate the eval loss and metric.
"""
metric.reset()
returns = [loss]
if isinstance(correct, list) or isinstance(correct, tuple):
returns.extend(list(correct))
e... | 24,602 |
def h(q):
"""Binary entropy func"""
if q in {0, 1}:
return 0
return (q * math.log(1 / q, 2)) + ((1 - q) * math.log(1 / (1 - q), 2)) | 24,603 |
def job_scheduler_sequential(dict_of_jobs):
"""
Choose a gpum then launches jobs sequentially on that GPU in tmux sessions.
:param dict_of_jobs:
"""
keys = list(dict_of_jobs.keys())
while get_first_available_gpu() < 0:
time.sleep(15) # Sleeps for 30 sec
gpu_id = get_first_available... | 24,604 |
def has_next_page(page_info: dict) -> bool:
"""
Extracts value from a dict with hasNextPage key, raises an error if the key is not available
:param page_info: pagination info
:return: a bool indicating if response hase a next page
"""
has_next_page = page_info.get('hasNextPage')
if has_next... | 24,605 |
def _stuw_code(current_name=None):
""""
Zoekt door TYPESTUW naar de naam van het stuwtype, geeft attribuut waarde uit DAMO
"""
if current_name not in TYPESTUW.values():
return 99
for i, name in TYPESTUW.items():
if name == current_name:
return i | 24,606 |
def test_edge_width():
"""Test setting edge width."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert layer.edge_width == 1
layer.edge_width = 2
assert layer.edge_width == 2
layer = Vectors(data, edge_width=3)
... | 24,607 |
def test_three_column_image_text_section_under_homepage():
"""
Three column image text section subpage should provide expected values.
"""
home_page = HomePageFactory.create()
assert home_page.three_column_image_text_section is None
assert models.ThreeColumnImageTextSection.can_create_at(home_pa... | 24,608 |
def _build_init_nodes(context, device):
"""
Build initial inputs for beam search algo
"""
decoder_input = _prepare_init_inputs(context, device)
root_node = BeamSearchNode(None, None, decoder_input, 0, len(context))
return [root_node] | 24,609 |
def fetch_preset(output_filename=None, nproc=8, add_structure=True):
"""
Fetches preset list of docs determined via trial and error,
An initial query via the frontend on 06/28/2019 showed 12870,
and subsequent sampling of ids from 8000-25000 yielded all 12820.
Successful query ids were stored in in... | 24,610 |
def parse_args():
"""Function to read CCB-ID command line arguments
Args:
None - reads from sys.argv
Returns:
an argparse object
"""
# create the argument parser
parser = args.create_parser(description='Apply a CCB-ID species classification model to csv or image da... | 24,611 |
def compute_accuracy(data):
"""Return [wpm, accuracy]."""
prompted_text = data["promptedText"][0]
typed_text = data.get("typedText", [""])[0]
start_time = float(data["startTime"][0])
end_time = float(data["endTime"][0])
return [typing.wpm(typed_text, end_time - start_time),
typing.ac... | 24,612 |
def drop_talbes():
"""
Drop all model tables
"""
models = (
m for m in globals().values() if isinstance(
m, type) and issubclass(
m, db.Model))
drop_model_tables(models, fail_silently=True) | 24,613 |
def write_file(filename: str, content: str, mode: str = "w") -> IO:
"""Save content to a file, overwriting it by default."""
with open(filename, mode) as file:
file.write(content)
return file | 24,614 |
def get_minimum_integer_attribute_value(node, attribute_name):
"""
Returns the minimum value that a specific integer attribute has set
:param node: str
:param attribute_name: str
:return: float
"""
return maya.cmds.attributeQuery(attribute_name, min=True, node=node)[0] | 24,615 |
def get_star_locs(plotfile):
"""Given a plotfile, return the location of the primary and the secondary."""
import numpy as np
import yt
import string
ds = yt.load(plotfile)
# Get a numpy array corresponding to the density.
problo = ds.domain_left_edge.v
probhi = ds.domain_right_edge.... | 24,616 |
def get_list(_list, persistent_attributes):
"""
Check if the user supplied a list and if its a custom list, also check for for any saved lists
:param _list: User supplied list
:param persistent_attributes: The persistent attribs from the app
:return: The list name , If list is custom or not
"""... | 24,617 |
def num_active_mesos_tasks():
"""
An example metric used by the relay.mesos demo to query mesos master
for the number of currently running tasks.
"""
while True:
data = json.load(urllib2.urlopen(
os.environ['RELAY_MESOS_MASTER_STATE_FOR_DEMO']))
yield data['started_tasks'... | 24,618 |
def inode_for_pid_sock(pid, addr, port):
"""
Given a pid that is inside a network namespace, and the address/port of a LISTEN socket,
find the inode of the socket regardless of which pid in the ns it's attached to.
"""
expected_laddr = '%02X%02X%02X%02X:%04X' % (addr[3], addr[2], addr[1], addr[0], ... | 24,619 |
def print_mem_usage(df):
""" print memory footprint of a pandas dataframe"""
mb_usage = df.memory_usage(deep=True).sum() / 1e6
print(f"Memory usage:{mb_usage:.2f} MB") | 24,620 |
def get_edges_from_route_matrix(route_matrix: Matrix) -> List[Tuple]:
"""Returns a list of the edges used in a route according to the route matrix
:param route_matrix: A matrix indicating which edges contain the optimal route
:type route_matrix: Matrix
:return: The row and column for the edge in the ma... | 24,621 |
def nicer(string):
"""
>>> nicer("qjhvhtzxzqqjkmpb")
True
>>> nicer("xxyxx")
True
>>> nicer("uurcxstgmygtbstg")
False
>>> nicer("ieodomkazucvgmuy")
False
"""
pair = False
for i in range(0, len(string) - 3):
for j in range(i + 2, len(string) - 1):
if ... | 24,622 |
def cloud():
"""
cloud drawing
"""
cloud = GOval(100, 30, x=70, y=150)
cloud.filled = True
cloud.color = 'white'
cloud.fill_color = 'white'
window.add(cloud)
cloud = GOval(100, 30, x=170, y=100)
cloud.filled = True
cloud.color = 'white'
cloud.fill_color = 'white'
win... | 24,623 |
def multiple_choice(value: Union[list, str]):
""" Handle a single string or list of strings """
if isinstance(value, list):
# account for this odd [None] value for empty multi-select fields
if value == [None]:
return None
# we use string formatting to handle the possibility t... | 24,624 |
def Jnu_vD82(wav):
"""Estimate of ISRF at optical wavelengths by van Dishoeck & Black (1982)
see Fig 1 in Heays et al. (2017)
Parameters
----------
wav : array of float
wavelength in angstrom
Returns
-------
Jnu : array of float
Mean intensity Jnu in cgs units
... | 24,625 |
def _coexp_ufunc(m0, exp0, m1, exp1):
""" Returns a co-exp couple of couples """
# Implementation for real
if (m0 in numba_float_types) and (m1 in numba_float_types):
def impl(m0, exp0, m1, exp1):
co_m0, co_m1 = m0, m1
d_exp = exp0 - exp1
if m0 == 0.:
... | 24,626 |
def get_lorem(length=None, **kwargs):
""" Get a text (based on lorem ipsum.
:return str:
::
print get_lorem() # -> atque rerum et aut reiciendis...
"""
lorem = ' '.join(g.get_choices(LOREM_CHOICES))
if length:
lorem = lorem[:length]
return lorem | 24,627 |
def try_get_graphql_scalar_type(property_name, property_type_id):
"""Return the matching GraphQLScalarType for the property type id or None if none exists."""
maybe_graphql_type = ORIENTDB_TO_GRAPHQL_SCALARS.get(property_type_id, None)
if not maybe_graphql_type:
warnings.warn(
'Ignoring ... | 24,628 |
def get(path):
"""Get GCE metadata value."""
attribute_url = (
'http://{}/computeMetadata/v1/'.format(_METADATA_SERVER) + path)
headers = {'Metadata-Flavor': 'Google'}
operations_timeout = environment.get_value('URL_BLOCKING_OPERATIONS_TIMEOUT')
response = requests.get(
attribute_url, headers=hea... | 24,629 |
def greedy_helper(hyper_list, node_dict, fib_heap, total_weight, weight=None):
"""
Greedy peeling algorithm. Peel nodes iteratively based on their current degree.
Parameters
----------
G: undirected, graph (networkx)
node_dict: dict, node id as key, tuple (neighbor list, heap node) as value. He... | 24,630 |
def test_medicationrequest_1(base_settings):
"""No. 1 tests collection for MedicationRequest.
Test File: medicationrequest0302.json
"""
filename = base_settings["unittest_data_dir"] / "medicationrequest0302.json"
inst = medicationrequest.MedicationRequest.parse_file(
filename, content_type="... | 24,631 |
def CleanFloat(number, locale = 'en'):
"""\
Return number without decimal points if .0, otherwise with .x)
"""
try:
if number % 1 == 0:
return str(int(number))
else:
return str(float(number))
except:
return number | 24,632 |
def ssd_bboxes_encode(boxes):
"""
Labels anchors with ground truth inputs.
Args:
boxex: ground truth with shape [N, 5], for each row, it stores [y, x, h, w, cls].
Returns:
gt_loc: location ground truth with shape [num_anchors, 4].
gt_label: class ground truth with shape [num_an... | 24,633 |
def _get_partial_prediction(input_data: dt.BatchedTrainTocopoData,
target_data_token_ids: dt.NDArrayIntBO,
target_data_is_target_copy: dt.NDArrayBoolBOV,
target_data_is_target_pointer: dt.NDArrayBoolBOV
) -> ... | 24,634 |
def get_energy_spectrum_old(udata, x0=0, x1=None, y0=0, y1=None,
z0=0, z1=None, dx=None, dy=None, dz=None, nkout=None,
window=None, correct_signal_loss=True, remove_undersampled_region=True,
cc=1.75, notebook=True):
"""
DEPRECATED: TM clean... | 24,635 |
def createDefaultClasses(datasetTXT):
"""
:param datasetTXT: dict with text from txt files indexed by filename
:return: Dict with key:filename, value:list of lists with classes per sentence in the document
"""
classesDict = {}
for fileName in datasetTXT:
classesDict[fileName] = []
... | 24,636 |
def getGlobals():
"""
:return: (dict)
"""
return globals() | 24,637 |
def split_text_to_words(words: Iterable[str]) -> List[Word]:
"""Transform split text into list of Word."""
return [Word(word, len(word)) for word in words] | 24,638 |
def init_module_operation():
"""This function imports the primary modules for the package and returns ``True`` when successful."""
import khorosjx
khorosjx.init_module('admin', 'content', 'groups', 'spaces', 'users')
return True | 24,639 |
def connect_to_rds(aws, region):
"""
Return boto connection to the RDS in the specified environment's region.
"""
set_progress('Connecting to AWS RDS in region {0}.'.format(region))
wrapper = aws.get_api_wrapper()
client = wrapper.get_boto3_client(
'rds',
aws.serviceaccount,
... | 24,640 |
def export_graphviz(DecisionTreeClassificationModel, featureNames=None, categoryNames=None, classNames=None,
filled=True, roundedCorners=True, roundLeaves=True):
"""
Generates a DOT string out of a Spark's fitted DecisionTreeClassificationModel, which
can be drawn with any library capable... | 24,641 |
def _get_next_sequence_values(session, base_mapper, num_values):
"""Fetches the next `num_values` ids from the `id` sequence on the `base_mapper` table.
For example, if the next id in the `model_id_seq` sequence is 12, then
`_get_next_sequence_values(session, Model.__mapper__, 5)` will return [12, 13, 14, ... | 24,642 |
def overview(request):
"""
Dashboard: Process overview page.
"""
responses_dict = get_data_for_user(request.user)
responses_dict_by_step = get_step_responses(responses_dict)
# Add step status dictionary
step_status = get_step_completeness(responses_dict_by_step)
responses_dict_by_step['... | 24,643 |
def _normalize(y, data, width, height, depth, dim):
"""
功能:将图像数据归一化(从 0~255 归一为 0~1)\n
参数:\n
y: 图像数据归一化的结果\n
data:图像数据\n
width:图像 width\n
height:图像 height\n
depth:图像 depth\n
dim:图像数据维度(2维 or 3维数组)\n
返回值:NULL\n
"""
# 2维数组
if ArrayDim.TWO == dim:
for i in range... | 24,644 |
def _guess_os():
"""Try to guess the current OS"""
try:
abi_name = ida_typeinf.get_abi_name()
except:
abi_name = ida_nalt.get_abi_name()
if "OSX" == abi_name:
return "macos"
inf = ida_idaapi.get_inf_structure()
file_type = inf.filetype
if file_type in (ida_ida.f_ELF... | 24,645 |
def create_conf(name, address, *services):
"""Create an Apple TV configuration."""
atv = conf.AppleTV(name, address)
for service in services:
atv.add_service(service)
return atv | 24,646 |
def log_transform(x):
""" Log transformation from total precipitation in mm/day"""
tp_max = 23.40308390557766
y = np.log(x*(np.e-1)/tp_max + 1)
return y | 24,647 |
def test_bigquery_run_sql():
"""Test run_sql against bigquery database"""
statement = "SELECT 1 + 1;"
database = BigqueryDatabase(conn_id=DEFAULT_CONN_ID)
response = database.run_sql(statement)
assert response.first()[0] == 2 | 24,648 |
def get_flight(arguments):
"""
connects to skypicker servive and get most optimal flight base on search criteria
:param arguments: inputs arguments from parse_arg
:return dict: flight
"""
api_url = 'https://api.skypicker.com/flights?v=3&'
adults = '1'
# convert time format 2018-04-13 ->... | 24,649 |
def use_ip_alt(request):
"""
Fixture that gives back 2 instances of UseIpAddrWrapper
1) use ip4, dont use ip6
2) dont use ip4, use ip6
"""
use_ipv4, use_ipv6 = request.param
return UseIPAddrWrapper(use_ipv4, use_ipv6) | 24,650 |
def radius_gaussian(sq_r, sig, eps=1e-9):
"""Compute a radius gaussian (gaussian of distance)
Args:
sq_r: input radiuses [dn, ..., d1, d0]
sig: extents of gaussians [d1, d0] or [d0] or float
Returns:
gaussian of sq_r [dn, ..., d1, d0]
"""
return torch.exp(-sq_r / (2 * sig**... | 24,651 |
def index_papers_to_geodata(papers: List[Paper]) -> Dict[str, Any]:
"""
:param papers: list of Paper
:return: object
"""
geodata = {}
for paper in papers:
for file in paper.all_files():
for location in file.locations.all():
if location.id not in geodata:
... | 24,652 |
def _get_all_prefixed_mtds(
prefix: str,
groups: t.Tuple[str, ...],
update_groups_by: t.Optional[t.Union[t.FrozenSet[str],
t.Set[str]]] = None,
prefix_removal: bool = False,
custom_class_: t.Any = None,
) -> t.Dict[str, t.Tuple... | 24,653 |
def _extract_values_from_certificate(cert):
"""
Gets Serial Number, DN and Public Key Hashes. Currently SHA1 is used
to generate hashes for DN and Public Key.
"""
logger = getLogger(__name__)
# cert and serial number
data = {
u'cert': cert,
u'issuer': cert.get_issuer().der(),... | 24,654 |
def cartesian_product(arrays):
"""Create a cartesian product array from a list of arrays.
It is used to create x-y coordinates array from x and y arrays.
Stolen from stackoverflow
http://stackoverflow.com/a/11146645
"""
broadcastable = np.ix_(*arrays)
broadcasted = np.broadcast_arrays(*bro... | 24,655 |
def advanced_split(string, *symbols, contain=False, linked='right'):
"""
Split a string by symbols
If contain is True, the result will contain symbols
The choice of linked decides symbols link to which adjacent part of the result
"""
if not isinstance(string, str):
raise Exception('Strin... | 24,656 |
def _get_resource_info(
resource_type="pod",
labels={},
json_path=".items[0].metadata.name",
errors_to_ignore=("array index out of bounds: index 0",),
verbose=False,
):
"""Runs 'kubectl get <resource_type>' command to retrieve info about this resource.
Args:
... | 24,657 |
def rotate_line_about_point(line, point, degrees):
"""
added 161205
This takes a line and rotates it about a point a certain number of degrees.
For use with clustering veins.
:param line: tuple contain two pairs of x,y values
:param point: tuple of x, y
:param degrees: number of degrees t... | 24,658 |
def arith_relop(a, t, b):
"""
arith_relop(a, t, b)
This is (arguably) a hack.
Represents each function as an integer 0..5.
"""
return [(t == 0).implies(a < b),
(t == 1).implies(a <= b),
(t == 2).implies(a == b),
(t == 3).implies(a >= b),
(t == 4).implies(a > b),
... | 24,659 |
def test_normal_errors():
"""
Test the reconstruction of normal vector errors from PCA
and conversion back to hyperbolic errors
"""
o = random_pca()
hyp_axes = sampling_axes(o)
v = to_normal_errors(hyp_axes)
axes_reconstructed = from_normal_errors(v)
assert N.allclose(hyp_axes, axe... | 24,660 |
def initialise_framework(options):
"""This function initializes the entire framework
:param options: Additional arguments for the component initializer
:type options: `dict`
:return: True if all commands do not fail
:rtype: `bool`
"""
logging.info("Loading framework please wait..")
# No... | 24,661 |
def docmd(cmd):
"""Execute a command."""
if flag_echo:
sys.stderr.write("executing: " + cmd + "\n")
if flag_dryrun:
return
u.docmd(cmd) | 24,662 |
def get_registration_form() -> ConvertedDocument:
"""
Вернуть параметры формы для регистрации
:return: Данные формы профиля + Логин и пароль
"""
form = [
gen_field_row('Логин', 'login', 'text', validate_rule='string'),
gen_field_row('Пароль', 'password', 'password'),
... | 24,663 |
def get_docker_stats(dut):
"""
Get docker ps
:param dut:
:return:
"""
command = 'docker stats -a --no-stream'
output = st.show(dut, command)
return output | 24,664 |
def parse_commandline_arguments():
"""Parses command line arguments and adjusts internal data structures."""
# Define script command line arguments
parser = argparse.ArgumentParser(description='Run object detection inference on input image.')
parser.add_argument('-w', '--workspace_dir',
help='s... | 24,665 |
def fetch_latency(d: str, csim: bool = False):
"""Fetch the simulated latency, measured in cycles."""
tb_sim_report_dir = os.path.join(
d, "tb" if not csim else "tb.csim", "solution1", "sim", "report"
)
if not os.path.isdir(tb_sim_report_dir):
return None
tb_sim_report = get_single_... | 24,666 |
def enthalpyvap(temp=None,pres=None,dvap=None,chkvals=False,
chktol=_CHKTOL,temp0=None,pres0=None,dvap0=None,chkbnd=False,
mathargs=None):
"""Calculate ice-vapour vapour enthalpy.
Calculate the specific enthalpy of water vapour for ice and water
vapour in equilibrium.
:arg temp: Temper... | 24,667 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Setup binary_sensor platform."""
coordinator = hass.data[DOMAIN]
entities = []
for binary_sensor in BINARY_SENSOR_TYPES:
_LOGGER.debug("Adding %s binary sensor", binary_sensor)
entity = GrocyBinarySensor(coordinator, entry... | 24,668 |
async def get_eng_hw(module: tuple[str, ...], task: str) -> Message:
"""
Стандартный запрос для английского
"""
return await _get_eng_content('zadanie-{}-m-{}-z'.format(*module), task) | 24,669 |
def _choose_split_axis(v: Variable) -> Axis:
"""
For too-large texture `v`, choose one axis which is the best one to reduce texture size by splitting `v` in that axis.
Args:
v: Variable, whose size is too large (= this variable has :code:`SplitTarget` attribute)
Returns:
axis
"""
... | 24,670 |
def import_ratings(LIKED_RATING):
""" Load ratings csv files to ratings and user classes """
id_list = []
import csv
with open('lessRatings.csv', encoding='utf-8') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
# Count the rows and discount ... | 24,671 |
def get_image_blobs(pb):
""" Get an image from the sensor connected to the MicroPython board,
find blobs and return the image, a list of blobs, and the time it
took to find the blobs (in [ms])
"""
raw = json.loads(run_on_board(pb, script_get_image, no_print=True))
img = np.flip(np.transpose(np.resha... | 24,672 |
def update_alliances_from_esi():
"""
Updates the alliances properties from the ESI.
"""
for alliance in Alliance.objects:
scheduler.add_job(update_alliance_from_esi, args=(alliance,)) | 24,673 |
def classification_report(y_true, y_pred, digits=2, suffix=False):
"""Build a text report showing the main classification metrics.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a classifier.
digits : int. Number of dig... | 24,674 |
def test_open_and_close(get_camera):
"""
Tests the uvccamera's open, open_count, and close methods.
"""
camera = get_camera
connected = camera.is_device_connected()
assert connected is True
orig_count = camera.open_count()
assert isinstance(orig_count, int)
count = camera.close()
... | 24,675 |
def tidy_conifer(ddf: DataFrame) -> DataFrame:
"""Tidy up the raw conifer output."""
result = ddf.drop(columns=["marker", "identifier", "read_lengths", "kraken"])
result[["name", "taxonomy_id"]] = result["taxa"].str.extract(
r"^(?P<name>[\w ]+) \(taxid (?P<taxonomy_id>\d+)\)$", expand=True
)
... | 24,676 |
def test_set_illegal_backing_type():
"""The backing type for a set MUST be one of S/N/B, not BOOL"""
for typedef in [Boolean, Set(Integer)]:
with pytest.raises(TypeError):
Set(typedef) | 24,677 |
def load(name=None):
"""
Loads or initialises a convolutional neural network.
"""
if name is not None:
path = os.path.join(AmfConfig.get_appdir(), 'trained_networks', name)
else:
path = AmfConfig.get('model')
if path is not None and os.path.isfile(path):
pri... | 24,678 |
def get_duplicates(lst):
"""Return a list of the duplicate items in the input list."""
return [item for item, count in collections.Counter(lst).items() if count > 1] | 24,679 |
def relu(x, alpha=0):
"""
Rectified Linear Unit.
If alpha is between 0 and 1, the function performs leaky relu.
alpha values are commonly between 0.1 and 0.3 for leaky relu.
Parameters
----------
x : numpy array
Values to be activated.
alpha : float, optional
Th... | 24,680 |
def build_unique_dict(controls):
"""Build the disambiguated list of controls
Separated out to a different function so that we can get
the control identifiers for printing.
"""
name_control_map = UniqueDict()
# collect all the possible names for all controls
# and build a list of... | 24,681 |
def serialize_thrift_object(thrift_obj, proto_factory=Consts.PROTO_FACTORY):
"""Serialize thrift data to binary blob
:param thrift_obj: the thrift object
:param proto_factory: protocol factory, set default as Compact Protocol
:return: string the serialized thrift payload
"""
return Serializer... | 24,682 |
def signal(
fn: Optional[WorkflowSignalFunc] = None,
*,
name: Optional[str] = None,
dynamic: Optional[bool] = False,
):
"""Decorator for a workflow signal method.
This is set on any async or non-async method that you wish to be called upon
receiving a signal. If a function overrides one wit... | 24,683 |
def cmap_RdBu(values, vmin = None, vmax = None):
"""Generates a blue/red colorscale with white value centered around the value 0
Parameters
----------
values : PandasSeries, numpy array, list or tuple
List of values to be used for creating the color map
vmin : type
Minimum value in ... | 24,684 |
def _add_noise(audio, snr):
"""
Add complex gaussian noise to signal with given SNR.
:param audio(np.array):
:param snr(float): sound-noise-ratio
:return: audio with added noise
"""
audio_mean = np.mean(audio**2)
audio_mean_db = 10 * np.log10(audio_mean)
noise_mean_db = snr - audio... | 24,685 |
def mlp_net():
"""The MLP test from Relay.
"""
from tvm.relay.testing import mlp
return mlp.get_net(1) | 24,686 |
def build_ind_val_dsets(dimensions, is_spectral=True, verbose=False, base_name=None):
"""
Creates VirtualDatasets for the position or spectroscopic indices and values of the data.
Remember that the contents of the dataset can be changed if need be after the creation of the datasets.
For example if one o... | 24,687 |
def chunks(lst, n):
"""Chunks.
Parameters
----------
lst : list or dict
The list or dictionary to return chunks from.
n : int
The number of records in each chunk.
"""
if isinstance(lst, list):
for i in tqdm(range(0, len(lst), n)):
yield lst[i:i + n]
... | 24,688 |
def groupByX(grp_fn, messages):
"""
Returns a dictionary keyed by the requested group.
"""
m_grp = {}
for msg in getIterable(messages):
# Ignore messages that we don't have all the timing for.
if msg.isComplete() or not ignore_incomplete:
m_type = grp_fn(msg)
... | 24,689 |
def regular_poly_circ_rad_to_side_length(n_sides, rad):
"""Find side length that gives regular polygon with `n_sides` sides an
equivalent area to a circle with radius `rad`."""
p_n = math.pi / n_sides
return 2 * rad * math.sqrt(p_n * math.tan(p_n)) | 24,690 |
def dbl_colour(days):
"""
Return a colour corresponding to the number of days to double
:param days: int
:return: str
"""
if days >= 28:
return "orange"
elif 0 < days < 28:
return "red"
elif days < -28:
return "green"
else:
return "yellow" | 24,691 |
def error(s, buffer=''):
"""Error msg"""
prnt(buffer, '%s%s %s' % (weechat.prefix('error'), script_nick, s))
if weechat.config_get_plugin('debug'):
import traceback
if traceback.sys.exc_type:
trace = traceback.format_exc()
prnt('', trace) | 24,692 |
def _infraslow_pac_model(
alg, kernel, permute=False, seed=None, output_dir=None, rois=None):
"""Predict DCCS using infraslow PAC."""
if not output_dir:
output_dir = os.path.abspath(os.path.dirname(__file__))
if not rois:
rois = glasser_rois
infraslow_pac = utils.load_phase_amp_... | 24,693 |
def create_model(data_format):
"""Model to recognize digits in the MNIST data set.
Network structure is equivalent to:
https://github.com/tensorflow/tensorflow/blob/r1.5/tensorflow/examples/tutorials/mnist/mnist_deep.py
and
https://github.com/tensorflow/models/blob/master/tutorials/image/mn... | 24,694 |
def run_noncentered_hmc(model_config,
num_samples=2000,
burnin=1000,
num_leapfrog_steps=4,
num_adaptation_steps=500,
num_optimization_steps=2000):
"""Given a (centred) model, this function transform... | 24,695 |
def get_project_apps(in_app_list):
""" Application definitions for app name.
Args:
in_app_list: (list) - names of applications
Returns:
tuple (list, dictionary) - list of dictionaries with apps definitions
dictionary of warnings
"""
apps = []
warnings = collections.... | 24,696 |
def hang_me(timeout_secs=10000):
"""Used for debugging tests."""
print("Sleeping. Press Ctrl-C to continue...")
try:
time.sleep(timeout_secs)
except KeyboardInterrupt:
print("Done sleeping") | 24,697 |
def read(G):
""" Wrap a NetworkX graph class by an ILPGraph class
The wrapper class is used store the graph and the related variables of an optimisation problem
in a single entity.
:param G: a `NetworkX graph <https://networkx.org/documentation/stable/reference/introduction.html#graphs>`__
:retur... | 24,698 |
def slog_det(obs, **kwargs):
"""Computes the determinant of a matrix of Obs via np.linalg.slogdet."""
def _mat(x):
dim = int(np.sqrt(len(x)))
if np.sqrt(len(x)) != dim:
raise Exception('Input has to have dim**2 entries')
mat = []
for i in range(dim):
row ... | 24,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.