content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_mfp(g, gv):
"""Calculate mean free path from inverse lifetime and group velocity."""
g = np.where(g > 0, g, -1)
gv_norm = np.sqrt((gv**2).sum(axis=2))
mean_freepath = np.where(g > 0, gv_norm / (2 * 2 * np.pi * g), 0)
return mean_freepath | bcef3e92de1b81a8688b3a732dd7af0dd9ce6b8c | 3,654,400 |
from glob import glob
import os
import pandas as pd
def collate_participant_tables(subject_ids, base_dir):
"""
Generate a pandas dataframe across all subjects
Parameters
----------
subject_ids: list
a list of subject identifiers in
base_dir: str
path to a mindboggle output bas... | eb367b9d790c4d7a5583b65fc12b60c7d7cc6198 | 3,654,401 |
import os
def convert_to_format(file: str, output: str, output_format: str):
"""
Converts a HOCON file to another format
Parameters
----------
file : str
hocon file to convert
output : str
output file to produce
output_format : str
format of the output file
Re... | e7ec08d9167f30717e7f11cf5e234837b6c2da66 | 3,654,402 |
def find_prime_root(l, blum=True, n=1):
"""Find smallest prime of bit length l satisfying given constraints.
Default is to return Blum primes (primes p with p % 4 == 3).
Also, a primitive root w is returned of prime order at least n.
"""
if l == 1:
assert not blum
assert n == 1
... | be2d465fdb8de45dc2574788c12b8f78f4601508 | 3,654,403 |
import json
def set_parameters(_configs, new=False):
"""
Sets configuration parameters
Parameters
----------
_configs :
Dictionary containing configuration options from the config file (config.json)
new : bool
Do you want to start from a new file?
Returns
-------
... | 7c0d52f5a2ee5df9b54278162570606d684a6a64 | 3,654,404 |
import traceback
import sys
def create_all_files(sizes):
"""Create all files.
Parameters
----------
sizes : a list of lists of the form [(filesize,[block_size_1, block_size_2,...])]
Returns
-------
List of file names, a dictionary of measurements
"""
Stats=[]; files=[]
try:
... | af3d0c0876b61019acf0e9e61aae266794c66682 | 3,654,405 |
import os
def read_requirements(filename='requirements.txt'):
"""Reads the list of requirements from given file.
:param filename: Filename to read the requirements from.
Uses ``'requirements.txt'`` by default.
:return: Requirements as list of strings
"""
# allow for some lee... | fcade21b1aaff9320b32f5572fc28f8a6d31b5ab | 3,654,406 |
def vgg16(mask_init='1s', mask_scale=1e-2, threshold_fn='binarizer', **kwargs):
"""VGG 16-layer model (configuration "D")."""
model = VGG(make_layers(cfg['D'], mask_init, mask_scale, threshold_fn),
mask_init, mask_scale, threshold_fn, **kwargs)
return model | fa3a17460988a2c87ca63b287674b9836c7f69ac | 3,654,407 |
def sort(X):
"""
Return sorted elements of :param:`X` and array of corresponding
sorted indices.
:param X: Target vector.
:type X: :class:`scipy.sparse` of format csr, csc, coo, bsr, dok, lil,
dia or :class:`numpy.matrix`
"""
assert 1 in X.shape, "X should be vector."
X = X.flatten(... | a176e2538fd1c0042eefc6962d1b354b7b4ca736 | 3,654,408 |
def get_query(sf, query_text, verbose=True):
"""
Returns a list of lists based on a SOQL query with the fields as
the header column in the first list/row
"""
# execute query for up to 2,000 records
gc = sf.query(query_text)
records = gc['records']
if verbose:
print('Reading fro... | ea93b6652a2d455b368a831d8c6d6b4554023313 | 3,654,409 |
import io
import csv
def strip_blank(contents):
"""
strip the redundant blank in file contents.
"""
with io.StringIO(contents) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",", quotechar='"')
rows = []
for row in csvreader:
rows.append(",".join(['"{}"'.for... | d446f2123aa3cfe3b1966151f323fa1c4e41cb08 | 3,654,410 |
def generate_id() -> str:
"""Generates an uuid v4.
:return: Hexadecimal string representation of the uuid.
"""
return uuid4().hex | 674d0bea01f9109e02af787435d7cee5c37f0a5a | 3,654,411 |
def perms_of_length(n, length):
"""Return all permutations in :math:`S_n` of the given length (i.e., with the specified number of inversion).
This uses the algorithm in `<http://webhome.cs.uvic.ca/~ruskey/Publications/Inversion/InversionCAT.pdf>`_.
:param n: specifies the permutation group :math:`S_n`.
... | da18a1a8b2dad5a0084f3d557a2cc1018798d33e | 3,654,412 |
def rank_by_entropy(pq, kl=True):
""" evaluate kl divergence, wasserstein distance
wasserstein: http://pythonhosted.org/pyriemann/_modules/pyriemann/utils/distance.html
"""
# to avoid Inf cases
pq = pq + 0.0000001
pq = pq/pq.sum(axis=0)
if kl: # entropy actually can calculate KL diverge... | 0b47e2ba8de66148a50dbb1b4637897ac7bdee4b | 3,654,413 |
def generate_graph_properties(networks):
"""
This function constructs lists with centrality rankings of nodes in multiple networks.
Instead of using the absolute degree or betweenness centrality, this takes metric bias into account.
If the graph is not connected, the values are calculated for the large... | e135c4211d924ab9f1af6baec06b8b313a96b11f | 3,654,414 |
def anova_old(
expression, gene_id, photoperiod_set, strain_set, time_point_set, num_replicates
):
"""One-way analysis of variance (ANOVA) using F-test."""
num_groups = len(photoperiod_set) * len(strain_set) * len(time_point_set)
group_size = num_replicates
total_expression = 0
# First scan: cal... | f809e0e2be877e1a0f21ca1e05a7079db80254a1 | 3,654,415 |
import struct
def _make_ext_reader(ext_bits, ext_mask):
"""Helper for Stroke and ControlPoint parsing.
Returns:
- function reader(file) -> list<extension values>
- function writer(file, values)
- dict mapping extension_name -> extension_index
"""
# Make struct packing strings from the extension details... | 2f85ab0f09d5a4cbd2aad7a9819440b610bcf20c | 3,654,416 |
def resolve_covariant(n_total, covariant=None):
"""Resolves a covariant in the following cases:
- If a covariant is not provided a diagonal matrix of 1s is generated, and symmetry is checked via a comparison with the datasets transpose
- If a covariant is provided, the symmetry is checked
args:... | cd32136786d36e88204574a739006239312bb99e | 3,654,417 |
from typing import Optional
from typing import Union
def create_generic_constant(
type_spec: Optional[computation_types.Type],
scalar_value: Union[int,
float]) -> building_blocks.ComputationBuildingBlock:
"""Creates constant for a combination of federated, tuple and tensor types.
... | e440ef6470eacd66fc51210f288c3bf3c14486c6 | 3,654,418 |
def all_same(lst: list) -> bool:
"""test if all list entries are the same"""
return lst[1:] == lst[:-1] | 4ef42fc65d64bc76ab1f56d6e03def4cb61cf6f0 | 3,654,419 |
def binary_find(N, x, array):
"""
Binary search
:param N: size of the array
:param x: value
:param array: array
:return: position where it is found. -1 if it is not found
"""
lower = 0
upper = N
while (lower + 1) < upper:
mid = int((lower + upper) / 2)
if x < arr... | ed6e7cc15de238381dbf65eb6c981676fd0525f5 | 3,654,420 |
def _add_data_entity(app_context, entity_type, data):
"""Insert new entity into a given namespace."""
old_namespace = namespace_manager.get_namespace()
try:
namespace_manager.set_namespace(app_context.get_namespace_name())
new_object = entity_type()
new_object.data = data
ne... | 864e12973ad7cfd4c89fbefb211b8b940913590f | 3,654,421 |
def scalarmat(*q):
"""multiplies every object in q with each object in q. Should return a unity matrix for an orthonormal system"""
ret=[]
for a in q:
toa=[]
for b in q:
toa.append(a*b)
ret.append(toa)
return ret | a61c813b548f1934e16517efc4d203c6390097fe | 3,654,422 |
import time
def frames_per_second():
""" Return the estimated frames per second
Returns the current estimate for frames-per-second (FPS).
FPS is estimated by measured the amount of time that has elapsed since
this function was previously called. The FPS estimate is low-pass filtered
to reduce noi... | 0ac78e052d1e3f4d09a332bd71df041f14a46111 | 3,654,423 |
def modularity(partition, graph, weight='weight'):
"""Compute the modularity of a partition of a graph
Parameters
----------
partition : dict
the partition of the nodes, i.e a dictionary where keys are their nodes
and values the communities
graph : networkx.Graph
the networkx g... | 371c3f5e362114896bf0559efe452d79af6e79f8 | 3,654,424 |
def config_lst_bin_files(data_files, dlst=None, atol=1e-10, lst_start=0.0, fixed_lst_start=False, verbose=True,
ntimes_per_file=60):
"""
Configure lst grid, starting LST and output files given input data files and LSTbin params.
Parameters
----------
data_files : type=list ... | b91cd59bf8d9693bb255c10ef9fb5ce3ef219a41 | 3,654,425 |
def get_str_arr_info(val):
""" Find type of string in array val, and also the min and max length. Return
None if val does not contain strings."""
fval = np.array(val).flatten()
num_el = len(fval)
max_length = 0
total_length = 0
for sval in fval:
len_sval = len(sval)
if len_s... | 283233c780379ca637f621510fa09c359ff53784 | 3,654,426 |
import torch
def generate_priors(image_size=300,
layer_sizes=None,
pool_ratios=None,
min_sizes=None,
max_sizes=None,
aspect_ratios=None):
# TODO update feature maps, min_sizes, max_sizes for inputs size 5xx
"""... | 208fa7402f6260d21cb23893cd178fac09ba5739 | 3,654,427 |
import os
def listFiles(dir):
"""
Walks the path and subdirectories to return a list of files.
Parameters
----------
dir : str
the top directory to search
subdirectories are also searched
Returns
-------
listname: list
a list of files in dir and subdirecto... | e2cc32ffd29971fc11df0378f02f801932234569 | 3,654,428 |
from typing import Callable
from typing import Any
def wrap(
module: nn.Module,
cls: Callable = FullyShardedDataParallel,
activation_checkpoint: bool = False,
**wrap_overrides: Any
) -> nn.Module:
"""
Annotate that a module should be wrapped. Annotated modules will only be
wrapped if insid... | cdf313b9100ee2a2f3a9d3ed47fafa76dea16b74 | 3,654,429 |
def _is_multiple_state(state_size):
"""Check whether the state_size contains multiple states."""
return (hasattr(state_size, '__len__') and not isinstance(state_size, tensor_shape.TensorShape)) | f034b2a4656edf72be515d99093efc3b03591af0 | 3,654,430 |
def deque_to_yaml(representer, node):
"""Convert collections.deque to YAML"""
return representer.represent_sequence("!collections.deque", (list(node), node.maxlen)) | 5ff503b4f21af58cf96d26171e078ddd5d754141 | 3,654,431 |
from bs4 import BeautifulSoup
def parse_webpage(url, page_no):
"""
Parses the given webpage using 'BeautifulSoup' and returns html content of
that webpage.
"""
page = urllib2.urlopen(url + page_no)
parsed_page = BeautifulSoup(page, 'html.parser')
return parsed_page | 774046c85cc38f3575cabc473c93b92b6dbc3d25 | 3,654,432 |
import random
def randomDigits(length=8):
"""
生成随机数字串
randomDigits() ==> 73048139
"""
return ''.join([random.choice(digits) for _ in range(length)]) | cb4200ea4d6850888461880bc3d9cc0ea6804993 | 3,654,433 |
from imcsdk.mometa.adaptor.AdaptorGenProfile import AdaptorGenProfile
import time
def adaptor_set_all(handle, adaptors=None, server_id=1, **kwargs):
"""
Example:
adaptor_set_all(handle,
adaptors=[
{id: 1,
lldp: "enabled",
... | cc36c2e2104f74ed4a1e2239f979d89d42691cf9 | 3,654,434 |
from typing import Callable
def some_func(string: str, function: Callable) -> bool:
"""Check if some elements in a string match the function (functional).
Args:
string: <str> string to verify.
function: <callable> function to call.
Returns:
True if some of elements are in the seq... | e67af6613975a6757905087397ff8b68e83ddbf6 | 3,654,435 |
def UseExceptions(*args):
"""UseExceptions()"""
return _ogr.UseExceptions(*args) | 71a8e36c0554796298a5e8c9a3e88bf423acef5b | 3,654,436 |
def get_mlm_logits(input_tensor, albert_config, mlm_positions, output_weights):
"""From run_pretraining.py."""
input_tensor = gather_indexes(input_tensor, mlm_positions)
with tf.variable_scope("cls/predictions"):
# We apply one more non-linear transformation before the output layer.
# This matrix is not u... | 36a2f10fe33aea371fcbf23ac856bf910998e1c9 | 3,654,437 |
def spm_hrf(TR, t1=6, t2=16, d1=1, d2=1, ratio=6, onset=0, kernel=32):
"""Python implementation of spm_hrf.m from the SPM software.
Parameters
----------
TR : float
Repetition time at which to generate the HRF (in seconds).
t1 : float (default=6)
Delay of response relative to onset ... | be07acb0980000a59f4df39f0ab7147dbb5d258e | 3,654,438 |
def prob_active_neuron(activity_matrix):
"""Get expected co-occurrence under independence assumption.
Parameters
----------
activity_matrix : np.array
num_neurons by num_bins, boolean (1 or 0)
Returns
-------
prob_active : np.array
Fraction of bins each cell participates in... | fd5eb513598d840602117adb0223c75b71660f8a | 3,654,439 |
def translate_x(image: tf.Tensor, pixels: int, replace: int) -> tf.Tensor:
"""Equivalent of PIL Translate in X dimension."""
image = translate(wrap(image), [-pixels, 0])
return unwrap(image, replace) | 53ea2bf905487a310d6271b37adef0523bcdf4de | 3,654,440 |
def reduce_time_space_seasonal_regional( mv, season=seasonsyr, region=None, vid=None,
exclude_axes=[] ):
"""Reduces the variable mv in all time and space dimensions. Any other dimensions will remain.
The averages will be restricted to the the specified season and region... | ec2005564ccaca881e2737cb8f51f05ba091e64d | 3,654,441 |
import argparse
def get_args():
"""
Function to retrieve and parse the command line arguments,
then to return these arguments as an ArgumentParser object.
Parameters:
None.
Returns:
parser.parse_args(): inputed or default argument objects.
"""
parser = argparse.ArgumentP... | 6ff328f56f0a12a736d41130dd34b49848ba7dad | 3,654,442 |
import os
import tempfile
def apply_modifications(model, custom_objects=None):
"""Applies modifications to the model layers to create a new Graph. For example, simply changing
`model.layers[idx].activation = new activation` does not change the graph. The entire graph needs to be updated
with modified inbo... | 16f230511fe689c724b40e08d1f8d2fb52abc71d | 3,654,443 |
import math
def fuel_requirement(mass: int) -> int:
"""Fuel is mass divide by three, round down and subtract 2"""
return math.floor(mass / 3) - 2 | 5899d9260fe7e353c3a1d882f624257d5009248d | 3,654,444 |
def data_head(fname):
"""
Get the columns-names of the csv
Parameters
----------
fname: str
Filename of the csv-data
Returns
----------
str-list:
header-names of the csv-data
"""
return pd.read_csv(fname, encoding='ISO-8859-1').columns | 2b10f0465b30371560a5bc009a2d3a945a80f493 | 3,654,445 |
def format(serverDict, sortKeyword='id'):
"""
Returns an array of nicely formatted servers, sorted by whatever the user prefers, or id by default.
"""
sortDict = {'id': lambda server: int(server.name[4:-3]),
'uptime': lambda server: server.uptime}
sortFunction = sortDict[sortKeyword... | 67058d6c0dd6c64a2540be371fa7ba24d081d273 | 3,654,446 |
def moray_script():
"""
JavaScript関数を公開するためのjsモジュールを生成
Returns:
JavaScript関数を公開するためのjsモジュール
"""
return bottle.static_file('moray.js', root=_root_static_module) | 35eebb14902513a2a0e12bf8ce866a8c6d00e193 | 3,654,447 |
def load_compdat(wells, buffer, meta, **kwargs):
"""Load COMPDAT table."""
_ = kwargs
dates = meta['DATES']
columns = ['DATE', 'WELL', 'I', 'J', 'K1', 'K2', 'MODE', 'Sat',
'CF', 'DIAM', 'KH', 'SKIN', 'ND', 'DIR', 'Ro']
df = pd.DataFrame(columns=columns)
for line in buffer:
... | fb28b82ba6ad36c3aea45e31c684c9302cdf511c | 3,654,448 |
from typing import Optional
def scale_random(a: float, b: float, loc: Optional[float] = None, scale: Optional[float] = None) -> float:
"""Returns a value from a standard normal truncated to [a, b] with mean loc and standard deviation scale."""
return _default.scale_random(a, b, loc=loc, scale=scale) | 3c336cd3c345f0366bd721ff2a3a426853804721 | 3,654,449 |
def created_link(dotfile: ResolvedDotfile) -> str:
"""An output line for a newly-created link.
"""
return (
co.BOLD
+ co.BRGREEN
+ OK
+ " "
+ ln(dotfile.installed.disp, dotfile.link_dest)
+ co.RESET
) | 9195db9c3ea8f7aa6281017ef62967ef5b07f4f3 | 3,654,450 |
def instruction2_task(scr):
""" Description of task 1 """
scr.draw_text(text = "Great Work!! "+
"\n\nNow comes your TASK 3: **Consider an image**."+
"\n\nIf you press the spacebar now, an image will "+
"appear at the bottom of the screen. You can use the information from the"+
" image to make an... | 554191b520e1229ffc076bbed1c57f265e0c0964 | 3,654,451 |
import os
def tail(f, lines=10, _buffer=4098):
"""Tail a file and get X lines from the end"""
# place holder for the lines found
lines_found = []
# block counter will be multiplied by buffer
# to get the block size from the end
block_counter = -1
# loop until we find X lines
while le... | 20ccac940eff04a6ec57d98d32330ebfbb97037d | 3,654,452 |
def loggedin_and_owner_required(func):
"""
Decorator that applies to functions expecting the "owner" name as
a second argument.
It will check that the visitor is also considered as the owner of
the resource it is accessing.
Note: automatically calls login_required and check_and_set_owner decorators.
"""... | 171695cc6b6dad2240fbe63ba8ab3193255fee7f | 3,654,453 |
def recursive_subs(e: sp.Basic,
replacements: list[tuple[sp.Symbol, sp.Basic]]) -> sp.Basic:
"""
Substitute the expressions in ``replacements`` recursively.
This might not be necessary in all cases, Sympy's builtin
``subs()`` method should also do this recursively.
.. note::
... | 013a203d214eb7c683efdefc2bc0b60781260576 | 3,654,454 |
def create_lag_i(df,time_col,colnames,lag):
""" the table should be index by i,year
"""
# prepare names
if lag>0:
s = "_l" + str(lag)
else:
s = "_f" + str(-lag)
values = [n + s for n in colnames]
rename = dict(zip(colnames, values))
# create lags
dlag = df.reset_ind... | be6d4b390ae66cd83320b2c341ba3c76cfad2bdb | 3,654,455 |
def crop_image(image_array, point, size):
"""
Cropping the image into the assigned size
image_array: numpy array of image
size: desirable cropped size
return -> cropped image array
"""
img_height, img_width = point # assigned location in crop
# for color image
if len(image_array.s... | 8ee684719e3e4fea755466e810c645c1ccf7d7f5 | 3,654,456 |
def deg_to_rad(deg):
"""Convert degrees to radians."""
return deg * pi / 180.0 | e07bfcb4a541bddedeb8e9a03d6033b48d65c856 | 3,654,457 |
def find_plane_normal(points):
"""
d - number of dimensions
n - number of points
:param points: `d x n` array of points
:return: normal vector of the best-fit plane through the points
"""
mean = np.mean(points, axis=1)
zero_centre = (points.T - mean.T).T
U, s, VT = np.linalg.svd(zer... | 3edd4a848b50cffe9a78c6f75999c79934fd5003 | 3,654,458 |
def binary_search(data, target, low, high):
"""Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
"""
if low > high:
return False # interval is empty; no match
else:
... | 4395434aea4862e7fc0cab83867f32955b8fb2a2 | 3,654,459 |
import time
def ReadUnifiedTreeandHaloCatalog(fname, desiredfields=[], icombinedfile=1,iverbose=1):
"""
Read Unified Tree and halo catalog from HDF file with base filename fname.
Parameters
----------
Returns
-------
"""
if (icombinedfile):
hdffile=h5py.File(fname,'r')
... | 7efc107d5b6eb8a9747d09108f0e89c0b25bb253 | 3,654,460 |
import re
def lines_in_pull(pull):
"""Return a line count for the pull request.
To consider both added and deleted, we add them together, but discount the
deleted count, on the theory that adding a line is harder than deleting a
line (*waves hands very broadly*).
"""
ignore = r"(/vendor/)|(c... | 24aabd83c24c3f337f07b50c894f5503eadfc252 | 3,654,461 |
import tempfile
import os
import shutil
import errno
def plot_panels(volume, panels, figsize=(16, 9), save_name=None):
"""Plot on the same figure a number of views, as defined by a list of panel
Parameters
----------
volume : cortex.Volume
The data to plot.
panels : list of dict
... | bbd3b612ea3e10f47b94e0cb4588493052568d16 | 3,654,462 |
def get_active_milestones(session, project):
"""Returns the list of all the active milestones for a given project."""
query = (
session.query(model.Issue.milestone)
.filter(model.Issue.project_id == project.id)
.filter(model.Issue.status == "Open")
.filter(model.Issue.milestone.... | 8a4c23ada7b18796ea76c770033320f29c0e8d5d | 3,654,463 |
def set_camera_parameters(cfg):
"""
Set camera parameters.
All values come from the dict generated from the JSON file.
:param cfg: JSON instance.
:type cam: dict
:return: None
:rtype: None
"""
# set camera resolution [width x height]
camera = PiCamera()
camera.resolutio... | 3bd7b0b410d7a19f486a8e3fc80d50af4caa1734 | 3,654,464 |
def get_srl_result_for_instance(srl_dict, instance):
"""Get SRL output for an instance."""
sent_id = instance.sent_id
tokens_gold = instance.tokens
srl_output = srl_dict[sent_id]
srl_output["words"] = [word for word in srl_output["words"] if word != "\\"]
tokens_srl = srl_output['words']
if tokens_srl != tokens... | 4437e68817469966d70759bf038b68c6b5983745 | 3,654,465 |
import sys
def ensure_tty(file=sys.stdout):
""" Ensure a file object is a tty. It must have an `isatty` method that
returns True.
TypeError is raised if the method doesn't exist, or returns False.
"""
isatty = getattr(file, 'isatty', None)
if isatty is None:
raise TypeError(
... | 52981903549b5241c22073df94b39db3eb4e3271 | 3,654,466 |
from typing import List
def chop_cells(text: str, max_size: int, position: int = 0) -> List[str]:
"""Break text in to equal (cell) length strings."""
_get_character_cell_size = get_character_cell_size
characters = [
(character, _get_character_cell_size(character)) for character in text
][::-1]... | d8d0bd558b48a43775aed3cb5e15a3889fdc653d | 3,654,467 |
def read_input_field_lonlat(
input_file,
fld_name,
level,
conf_in,
*,
conv_fact=None,
crop=0,
):
"""Read from file and pre-process a field.
Returns the field as a Field2D object.
Arguments:
- input_file: Input netCDF file.
- fld_name: Name of the input field used in t... | 2ad31cee8ea26abcb7982fc4f5a9518dd11872c4 | 3,654,468 |
def multiply_scenarios(sep, *args):
"""
Create the cross product of two lists of scenarios
"""
result = None
for scenes in args:
if result == None:
result = scenes
else:
total = []
for scena in result:
for scenb in scenes:
... | ef44d9cfcd01304be2d56215caea676dfc26d01b | 3,654,469 |
def export_output():
"""
Returns a function that will return the contents of the first file in a zip file which is
not named '_metadata.csv'
"""
def fn(export: FlexibleDataExport):
out = BytesIO()
export.file_format = FileFormat.ZIP_CSV
export.write_data(out)
with Zi... | dd94d996e72d01c287d8a1b57979d47b89e6a207 | 3,654,470 |
def compute_total_probability_vector(mix_coeff_matrix, kernel_probability_matrix):
"""
Computes the total, weighted probability vector using the mixture coefficient matrix and the kernel probability matrix.
"""
# Start writing code here. The computation for the total probability vector can be
# writ... | 9c9d97dd8d7c83be02bb91a9924994c36700cbd8 | 3,654,471 |
def mnist_noniid(dataset, num_users):
"""
Sample non-I.I.D client data from MNIST dataset
:param dataset:
:param num_users:
:return:
"""
num_shards, num_imgs = 200, 300
idx_shard = [i for i in range(num_shards)]
dict_users = {i: np.array([], dtype='int64') for i in range(num_users)}
... | 8194cf27698d9e721f739ed405f56c8fddbe581a | 3,654,472 |
def first_order_model(nt, rates):
"""
Returns the first-order model asymptotic solution for a network nt.
Takes a list of interaction weigths (in the same order as the list of nodes) as the "rates" argument
"""
if type(nt) == list:
nt = az.transform(nt)
M = network_matrix(nt, rates=r... | 8348e68568d3fb9f5236a1e7852f2b1cb8c2860d | 3,654,473 |
import requests
def save_to_disk(url, save_path):
"""
Saves to disk non-destructively (xb option will not overwrite)
"""
print('Downloading: %s' % url)
r = requests.get(url)
if r.status_code == 404:
print('URL broken, unable to download: %s' % url)
return False
else:
... | c9917a637026d999765364d3c276150681554129 | 3,654,474 |
import argparse
def arguments():
"""Parse arguments.
Returns
-------
argparse.Namespace
Returns Argparse Namespace.
"""
parser = argparse.ArgumentParser(prog='pyslackdesc',
description="pyslackdesc - simple, \
... | 4165c2e97ffa6705941c2dd9aeb006cfc567846c | 3,654,475 |
def render_settings_window(s_called, s_int, ntfc_called, ntfc_state, s_state):
"""
Render the settings window
"""
win = Settings(s_called, s_int, ntfc_called, ntfc_state, s_state)
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
return win.settings_called, win.interva... | 30f5a64b822d408b4f9ca4d83047753fa55eaa58 | 3,654,476 |
import json
def server(server_id):
"""
Returns a list of sourcemod servers
"""
data = {}
db_server = ServerModel.select().join(IPModel)
db_server = db_server.where(ServerModel.id == server_id).get()
server_address = (db_server.ip.address, db_server.port)
info = {}
try:
... | a52fd4bbaefefff5e667dd1dc1b06f68b7643810 | 3,654,477 |
def atom_hsoc(case, soc):
"""
Return atomic spin-orbit coupling matrix :math:`\\vec{l}\cdot\\vec{s}` in complex spherical harmonics basis.
Parameters
----------
case : str
String label indicating atomic shell,
- 'p': for :math:`p` -shell.
- 't2g': for :math:`t_{2g}` -... | d1c87105831952746e7b089480058b38c382bcd5 | 3,654,478 |
def wcs_to_celestial_frame(wcs):
"""
For a given WCS, return the coordinate frame that matches the celestial
component of the WCS.
Parameters
----------
wcs : :class:`~astropy.wcs.WCS` instance
The WCS to find the frame for
Returns
-------
frame : :class:`~astropy.coordinat... | 74f798f0f19566acf9f2115edf47ee2cf262ca0b | 3,654,479 |
def conv2d(x, f=64, k=3, d=1, act=None, pad='SAME', name='conv2d'):
"""
:param x: input
:param f: filters, default 64
:param k: kernel size, default 3
:param d: strides, default 2
:param act: activation function, default None
:param pad: padding (valid or same), default same
:param name:... | 86e2b6b9ac21074da460ee2785ef6fca317e0417 | 3,654,480 |
def _is_uniform_distributed_cf(cf):
""" Check if the provided center frequencies are uniformly distributed.
"""
return np.any(np.diff(np.diff(cf))!=0) | c8cee1832ff4664839a0adc1263f3ece94673ad7 | 3,654,481 |
def build_person(first_name, last_name):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
return person | c8da8a5c4d4b7403804eff55e38106bb5921cf06 | 3,654,482 |
def radon(image, theta=None):
"""
Calculates the radon transform of an image given specified
projection angles.
Parameters
----------
image : array_like, dtype=float
Input image.
theta : array_like, dtype=float, optional (default np.arange(180))
Projection angles (in degrees... | 9395e742353def0db9fa26e955d80c31a0c84d55 | 3,654,483 |
def build_idrac_table_schemas(metric_definitions: list):
"""build_table_schemas Build iDRAC Table Schemas
Build table schemas based on the idrac telemetry metric definitions
Args:
metric_definitions (list): idrac telemetry metric definitions
Returns:
dict: iDRAC table schemas
... | 5f7b6b5807f009d56b1f2aabeb86d0ddfcbdf44f | 3,654,484 |
from typing import Tuple
def _increasing_randomly_negate_to_arg(
level: int, params: Tuple[float, float]
) -> Tuple[float]:
"""
Convert level to transform magnitude. This assumes transform magnitude increases
(or decreases with 50% chance) linearly with level.
Args:
level (int): Level val... | a1e9cc220753132cfeb1426967d2cd648bc78fa8 | 3,654,485 |
import json
import hashlib
def hashify(params, max_length=8):
"""
Create a short hashed string of the given parameters.
:param params:
A dictionary of key, value pairs for parameters.
:param max_length: [optional]
The maximum length of the hashed string.
"""
param_str = j... | e4a97a28fc2d0564da3e6b22f32735b4a2534c3e | 3,654,486 |
import os
import io
import re
def version(package, encoding='utf-8'):
"""Obtain the packge version from a python file e.g. pkg/__init__.py
See <https://packaging.python.org/en/latest/single_source_version.html>.
"""
path = os.path.join(os.path.dirname(__file__), package, '__init__.py')
with io.op... | 6066b042a698d0ee2b816573a144c4dc5ac47a45 | 3,654,487 |
def unique_entries(results):
"""Prune non-unqiue search results."""
seen = set()
clean_results = []
for i in results:
if i['code'] not in seen:
clean_results.append(i)
seen.add(i['code'])
return clean_results | c0c55ebd5aa76f3a7f44134a972019c3d26c1c48 | 3,654,488 |
def get_q_confidence() -> int:
"""Get's the user's confidence for the card"""
response = input("How confident do you feel about being able to answer this question (from 1-10)? ")
if response.isnumeric() & 0 < response <= 10:
return int(response)
else:
print("Incorrect score value, please... | e61ceb5676703a795a24f99ee7849a362186ec84 | 3,654,489 |
def generate_offices_table(offices, by_office, by_polling_center,
election_day, day_after_election_day):
""" Pre-compute key data needed for generating election day
office reports.
"""
offices_by_key = {str(office['code']): office for office in offices}
rows = []
for... | 85111ed67e8f6b8dce71af2844ee865699f3fe01 | 3,654,490 |
import time
import random
import select
def bang(nick, chan, message, db, conn, notice):
"""when there is a duck on the loose use this command to shoot it."""
global game_status, scripters
if chan in opt_out:
return
network = conn.name
score = ""
out = ""
miss = ["You just shot you... | 78e537caa4c2579226bfbb870a1e37cacd58279e | 3,654,491 |
def pfunc_role_coverage(args):
"""Another intermediate function for parallelization; as for
pfunc_doctor_banding."""
rota = args[0]
role = args[1]
return rota.get_role_coverage(role) | 043ce250b428d443de90c7aa5fa8e8dcc2869303 | 3,654,492 |
def parse(s: str) -> Tree:
"""
Parse PENMAN-notation string *s* into its tree structure.
Args:
s: a string containing a single PENMAN-serialized graph
Returns:
The tree structure described by *s*.
Example:
>>> import penman
>>> penman.parse('(b / bark-01 :ARG0 (d / d... | 2a309be1e2a4d8c63130120f9497464811cc6e91 | 3,654,493 |
def subtract(v: Vector, w: Vector) -> Vector:
"""Subtracts corresponding elements"""
assert len(v) == len(w), "vectors must be the same length"
return [v_i - w_i for v_i, w_i in zip(v, w)] | 6e81286b28a178981d970630104ac23bfc606e67 | 3,654,494 |
import os
def get_QUTFish(image_path, train_ratio=0.8):
"""
get train and test dataset of QUTFish:
https://wiki.qut.edu.au/display/cyphy/Fish+Dataset
step1: download the dataset
step2: set the root to QUT_fish_data/
:param image_path: the QUT_fish_data/
:param the percentage used for trai... | 728d23d47a5e81745ac707a2318e51b7d0ad42ed | 3,654,495 |
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrab... | 610ed561edf246cef2bfd9f6cc5e38904bb939ec | 3,654,496 |
def get_commit():
""" Try to return the intended commit / release to deal with. Otherwise
raise an acceptable error.
1) it was specified on the command line
2) use the current branch in the target repo
"""
commit = getattr(env, 'commit', None) or rev_parse('HEAD')
if commit is N... | 90af53491335a7c616dc7a070394ec7408b7be52 | 3,654,497 |
def deg2hms(x):
"""Transform degrees to *hours:minutes:seconds* strings.
Parameters
----------
x : float
The degree value c [0, 360) to be written as a sexagesimal string.
Returns
-------
out : str
The input angle written as a sexagesimal string, in the
form, hours:... | 6572020a71d3abaac42c8826c6248c648535c3a9 | 3,654,498 |
def normalise_whitespace(row):
"""Return table row with normalised white space.
This involves stripping leading and trailing whitespace, as well as
consolidating white space to single spaces.
"""
pairs = (
(k, _normalise_cell(v))
for k, v in row.items())
return {
k: v fo... | 10a580ef43c1cc47efc709fff05abd98bb332bcf | 3,654,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.