content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def convert(digits, base1, base2):
"""Convert given digits in base1 to digits in base2.
digits: str -- string representation of number (in base1)
base1: int -- base of given number
base2: int -- base to convert to
return: str -- string representation of number (in base2)"""
# Handle up to base 3... | 5,320,900 |
def _get_cmfs_xy():
"""
xy色度図のプロットのための馬蹄形の外枠のxy値を求める。
Returns
-------
array_like
xy coordinate for chromaticity diagram
"""
# 基本パラメータ設定
# ------------------
cmf = CMFS.get(CMFS_NAME)
d65_white = D65_WHITE
# 馬蹄形のxy値を算出
# --------------------------
cmf_xy = X... | 5,320,901 |
def square_matrix_multiply(A, B):
""" 定義通りの計算 Θ(n^3)
"""
n = len(A)
C = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C | 5,320,902 |
def _filter_irregular_boxes(boxes, min_ratio=0.2, max_ratio=5):
"""Remove all boxes with any side smaller than min_size."""
ws = boxes[:, 2] - boxes[:, 0] + 1
hs = boxes[:, 3] - boxes[:, 1] + 1
rs = ws / hs
keep = np.where((rs <= max_ratio) & (rs >= min_ratio))[0]
return keep | 5,320,903 |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv:
argv = sys.argv
# setup command line parser
parser = E.OptionParser(
version="%prog version: $Id$", usage=globals()["__doc__"])
(options, args) = E.start... | 5,320,904 |
def test_randomize_corrmat_tail_error():
"""Test that we are strict about tail paramete."""
a = rs.randn(3, 30)
stat.randomize_corrmat(a, "hello") | 5,320,905 |
def test_show_environment(server):
"""Server.show_environment() returns dict."""
_vars = server.show_environment()
assert isinstance(_vars, dict) | 5,320,906 |
def login(user, password):
"""
Authenticate against SomethingAwful, both storing that authentication in
the global cookiejar and returning the relevant cookies
:param user: your awful username for somethingawful dot com
:param password: your awful password for somethingawful dot com
:return: th... | 5,320,907 |
def streams(url: str, **params):
"""
Initializes an empty Streamlink session, attempts to find a plugin and extracts streams from the URL if a plugin was found.
:param url: a URL to match against loaded plugins
:param params: Additional keyword arguments passed to :meth:`streamlink.Streamlink.streams`
... | 5,320,908 |
def process(args):
"""Standard JSON object `args` has the form::
{"query": <query>,
"countOnly": False,
"pageSize": 100,
"page": 1}
where `<query>` is AIP formatted query.
"""
query = args['query']
locus = query['locus']
param = '[{{"gene":"{locus}"}}]'.for... | 5,320,909 |
def get_questionnaire_example() -> pd.DataFrame:
"""Return questionnaire example data.
Returns
-------
data : :class:`~pandas.DataFrame`
dataframe with questionnaire example data
"""
return load_questionnaire_data(_get_data("questionnaire_sample.csv")) | 5,320,910 |
def auto_dsk(dsk_row,synth,bounds,conv_limit=0,conv_bounds=[None,None],phase_args=(0.,360.,1.),highcut=0.,order=3):
"""
Returns the maximum likelihood phase shift to deskew the data to match a provided synthetic given a bounds
on a window to match.
Parameters
----------
dsk_row : Pandas.Series... | 5,320,911 |
def tabulate_e2e_vectors(*, tau_n=dna_params['tau_n'], unwrap=None):
"""Return a lookup table of entry->exit vectors with the right magnitude in
nm. Multiply on the left with the entry orientation matrix to obtain the
entry to exit displacement vector.
One vector for each possible level of unwrapping.
... | 5,320,912 |
def load_fooof_task_pe(data_path, side='Contra', param_ind=1, folder='FOOOF'):
"""Loads task data for all subjects, selects and return periodic FOOOF outputs.
data_path : path to where data
side: 'Ipsi' or 'Contra'
"""
# Collect measures together from FOOOF results into matrices
all_alphas = n... | 5,320,913 |
def warning(message):
"""Generic warning message formatter.
Args:
message (string): A message that describes the warning.
Returns:
(str): Formatted warning message.
"""
return bcolors.WARNING + "WARNING: " + bcolors.ENDC + message | 5,320,914 |
def GetResult(cl, opts, result):
"""Waits for jobs and returns whether they have succeeded
Some OpCodes return of list of jobs. This function can be used
after issueing a given OpCode to look at the OpCode's result and, if
it is of type L{ht.TJobIdListOnly}, then it will wait for the jobs
to complete, other... | 5,320,915 |
def decomposition_method(input):
"""
Decomposition of an individual spectrum using input guesses from the parent
SAA
Parameters
----------
input : list
A list which contains the following:
spectral_axis : an array of the spectral axis
specids : a mask over which the spe... | 5,320,916 |
def test_fsp_configuration_not_equal_to_other_objects():
"""
Verify that FSPConfiguration objects are not considered equal to objects
of other types.
"""
config = FSPConfiguration(1, FSPFunctionMode.CORR, 1, 10, 0)
assert config != 1 | 5,320,917 |
def main(model,
quotes=False,
quotes_epochs=5,
limericks=False,
limericks_epochs=20,
):
"""
Perform the training.
:param model: Model that must be trained
:param quotes: Perform pre-training on a keyword-to-sentence translation task on the quotes dataset... | 5,320,918 |
def test_wrong_number_in_action():
"""
В случае, если переданная аргументом функция возвращает недействительное значение, она должна просто отрабатывать без таймаута.
Проверяем, что это так и происходит.
"""
flag = False
@time_limit(lambda: -1)
def function():
nonlocal flag
f... | 5,320,919 |
def oci_init():
"""collectd initialization callback method"""
global _configuration, _data_reporter
logger = None
try:
while not _configuration:
time.sleep(1)
data_processor = DataProcessor(configuration=_configuration)
collectd.register_write(oci_write, data=data_pro... | 5,320,920 |
def create_feature_columns() -> Tuple[list, list, list]:
"""
生成MMOE模型输入特征和label
Returns:
dense_feature_columns (list): 连续特征的feature_columns
category_feature_columns (list): 类别特征的feature_columns(包括序列特征)
label_feature_columns (list): 因变量的feature_columns
"""
dense_... | 5,320,921 |
def cal_features(pm):
"""
only one track in pm, all bars are calculated
Returns:
used_pitch
used_note
pitch_histogram
pitch_interval_hist # not for track 2
pitch_range
onset_interval_hist
duration_hist
"""
result_features = {}
chromagram = np.zeros(12)
duration_h... | 5,320,922 |
def grayscale(img):
"""Applies the Grayscale transform
"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | 5,320,923 |
def sample_user(email='test@joeshak.com', password='testpass'):
""" Create a sample user """
return get_user_model().objects.create_user(email, password) | 5,320,924 |
def GroupConv1D(x, in_channels, out_channels, groups=1, kernel=1, strides=1, name=''):
"""
group Convolution 1D
group=1 means pointwise convolution
----
input:
- x:
input tensor
- in_channels:
input channels
- out_channels:
output channels
... | 5,320,925 |
def xyzlim(vmin, vmax):
"""Set limits or all axis the same"""
xlim(vmin, vmax)
ylim(vmin, vmax)
zlim(vmin, vmax) | 5,320,926 |
def dashboard_token(ctx, managers, **_):
"""
Get a login token for the dashboard at <nms hostname or ip>/kubernetes/
"""
cmd = "kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | awk '/^deployment-controller-token-/{print $1}') | awk '$1==\"token:\"{print $2}'"
subprocess.r... | 5,320,927 |
def get_logger_obj(logger=None):
"""Get a logger object that can be specified by its name, or passed as is.
Defaults to the root logger.
"""
if logger is None or isinstance(logger, py.builtin._basestring):
logger = logging.getLogger(logger)
return logger | 5,320,928 |
def default_recurisive_init(custom_cell):
"""default_recurisive_init"""
for _, cell in custom_cell.cells_and_names():
if isinstance(cell, nn.Conv2d):
cell.weight.default_input = init.initializer(KaimingUniform(a=math.sqrt(5)),
cell.wei... | 5,320,929 |
def opt_validate_predictd ( options ):
"""Validate options from a OptParser object.
Ret: Validated options object.
"""
# gsize
try:
options.gsize = efgsize[options.gsize]
except:
try:
options.gsize = float(options.gsize)
except:
logging.error("Err... | 5,320,930 |
def associate_trajectories(traj_1, traj_2,
max_diff=0.01, offset_2=0.0,
first_name="first trajectory", snd_name="second trajectory"):
"""
Synchronizes two trajectories by matching their timestamps.
:param traj_1: trajectory.PoseTrajectory3D object of first trajectory
:param traj_2: traje... | 5,320,931 |
def calculate_wake_wing_influence_matrix(cpoints, wake, normals):
"""
Calculate influence matrix (steady wake contribution).
Parameters
----------
cpoints : np.ndarray, shape (m, n, 3)
Array containing the (x,y,z) coordinates of all collocation points.
wake : np.ndarray, shape (n, 4, 3)... | 5,320,932 |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
parser = E.OptionParser(
version="%prog version: $Id: fasta2distances.py 2781 2009-09-10 11:33:14Z andreas $")
parser.add_option("--filte... | 5,320,933 |
def get_recent_games(summoner_id):
"""
https://developer.riotgames.com/api/methods#!/1016/3445
Args:
summoner_id (int): the ID of the summoner to find recent games for
Returns:
RecentGames: the summoner's recent games
"""
request = "{version}/game/by-summoner/{summoner_id}/rece... | 5,320,934 |
def test_advinc_subtensor1():
""" Test the second case in the opt local_gpu_advanced_incsubtensor1 """
shared = cuda.shared_constructor
#shared = tensor.shared
xval = numpy.asarray([[1,2,3], [4,5,6], [7,8,9]],
dtype='float32')
yval = numpy.asarray([[10,10,10], [10,10,10]],
... | 5,320,935 |
def create_daily_rate_line_plot(sources, services, y_axis_type='log', y_range=(1, 10**7)):
"""
Returns
-------
plotting.figure
A Bokeh plot that can be shown.
"""
# create plot with a datetime axis type
p = plotting.figure(plot_width=700, plot_height=1200, x_axis_type="datetime",
... | 5,320,936 |
def masked_loss(y_gt, y_pred, loss_fn, **kwargs):
"""Calculate 2d loss by removing mask, normally it's durrations/f0s/energys loss."""
real_len = tf.reduce_sum(tf.cast(tf.math.not_equal(
y_gt, 0), tf.float32), axis=1) # shape [B,]
max_len = tf.shape(y_gt)[1]
max_len = tf.cast(max_len, real_len... | 5,320,937 |
def call_ft(function, *args):
"""Call an FTDI function and check the status. Raise exception on error"""
status = function(*args)
if len(bRaiseExceptionOnError) > 0:
if status != FT_OK:
raise DeviceError(status)
return status | 5,320,938 |
def reshuffle_words_to_fit(word_tuples_to_fit):
"""Within each length-class, reshuffle the words."""
new_word_tuples_to_fit = deepcopy(word_tuples_to_fit)
distinct_lens = set(len(wt.board) for wt in new_word_tuples_to_fit)
for word_len in distinct_lens:
word_inds_with_len = [i for i,wt in enumer... | 5,320,939 |
def make_tree_all_params(species, dbh, height, stem_x, stem_y, stem_z,
lean_direction, lean_severity, crown_ratio, crown_radius_E,
crown_radius_N, crown_radius_W, crown_radius_S,
crown_edge_height_E, crown_edge_height_N, crown_edge_height_W,
crown_edge_height_S, s... | 5,320,940 |
def get_cfg_defaults():
"""Get a yacs CfgNode object with default values"""
# Return a clone so that the defaults will not be altered
# This is for the "local variable" use pattern
return _C.clone() | 5,320,941 |
def outage_check(data, filename='outage.txt'):
"""
Quality assurance check on the weather service :-)
"""
outage_checker = Outage(data)
outage_checker.check_outage()
outage_result = outage_checker.parse_outage()
outfilepath = os.path.join(data['output_dir'], filename)
if outage_result is None:
logg... | 5,320,942 |
def should_ignore(file: str, exclusions: List[str]) -> bool:
"""Check if a file matches a line in the exclusion list."""
for excl in exclusions:
if fnmatch(file, excl):
return True
return False
# for file in Path(".").glob("**/*.py*"):
# if should_ignore(str(file), exclusion... | 5,320,943 |
def fpn_classifier_graph(rois, feature_maps,image_shape, pool_size, num_classes,config):
"""Builds the computation graph of the feature pyramid network classifier
and regressor heads.
selector: 0 for training and 1 for inference
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
... | 5,320,944 |
def fit_unitarity(depths, shifted_purities, weights=None):
"""Construct and fit an RB curve with appropriate guesses
:param depths: The clifford circuit depths (independent variable)
:param shifted_purities: The shifted purities (dependent variable)
:param weights: Optional weightings of each point to ... | 5,320,945 |
def save_del(data, name):
"""Save deep delete from a dict
"""
if isinstance(name, list):
for n in name:
save_del(data, n)
return
parts = name.split('.', 1)
if len(parts) == 1:
n = parts[0]
if isinstance(data, dict) and n in data:
del data[n]
... | 5,320,946 |
def filter_paragraph(p):
"""Simple filter to remove obviously bad paragraphs (bad text extraction).
Note this needs to run very quickly as it is applied to every paragraph
in the corpus, so nothing fancy! This whole method should be linear
expected time in len(p).
Args:
p: string, paragraph
Returns:
True if we ... | 5,320,947 |
def get_matching_tables(tables, path):
"""Get list of matching tables for provided path
Return list is sorted by longest matching path part
:param tables: List of `Table' objects
:param path: Path like string
:return: List of matched by path tables
"""
candidates = []
for table in tabl... | 5,320,948 |
def email_video_link(talk):
"""Send the presenter a link to their video, asking to confirm."""
meeting_recordings = common.zoom_request(
requests.get,
common.ZOOM_API + f"/meetings/{talk['zoom_meeting_id']}/recordings"
)
if not len(meeting_recordings["recording_files"]):
raise Ru... | 5,320,949 |
def load_plugin(mainMenu, pluginName):
""" Given the name of a plugin and a menu object, load it into the menu """
# note the 'plugins' package so the loader can find our plugin
fullPluginName = "empire.server.plugins." + pluginName
module = importlib.import_module(fullPluginName)
pluginObj = module... | 5,320,950 |
def make_import_user_csv_files(uw_accounts,
filepath):
"""
:param uw_accounts: a list of UwAccount objects
Writes all csv files. Returns number of records wrote out.
"""
if not uw_accounts or len(uw_accounts) == 0:
return 0
file_size = get_csv_file_size()
... | 5,320,951 |
def distanceInOval(x, y, a=3, b=2, k=0.2):
"""
:param x: high-dimension embedding of cell A
:param y: high-dimension embedding of cell B
:param a: major axis length
:param b: minor axie length
:param k: Deformation parameter
:return: distance between cell A and B in oval whose function is
... | 5,320,952 |
def file_generator(
wrapped=None,
ids=["file"],
names=[uuid4().hex],
suffixes=[""],
dirs=[SANDBOX],
properties=None,
):
"""Decorator which automates setup and return for file generation functions.
The decorator fulfills 3 tasks:
1. Generating required temporary file names.
... | 5,320,953 |
def optimal_t_from_selection(x, y, ts, J, min_n):
"""
Time complexity:
O(T*N)
Space complexity:
O(N+T) - to store the input
"""
N = len(x)
best_loss = np.inf
best_t = -np.inf
idx = None
for t in ts: # O(T)
# evaluate loss for splitting [:s], [s:]
y_l = y[x <= ... | 5,320,954 |
def _deserialize_qnode(qnode_id, qnode):
"""Returns a QNode from a single deserialized QueryGraph node in a
TRAPI request
"""
constraints = []
try:
ids = qnode.get('ids')
categories = qnode.get('categories')
is_set = qnode.get('is_set')
req_constraints = qnode.get('co... | 5,320,955 |
def insert_seq_file_header(filepath: Union[str, Path],
author: str):
"""
Inserts header information into seq-file
:param filepath: path to the sequence file
:param author: name of the author of the file
"""
# create a temp file
tmp, abs_path = mkstemp()
in_pos... | 5,320,956 |
def combined_f1_rmse(y_true, y_pred):
"""Difference between F1 score and root mean square error (rmse).
The optimal values for F1 score and rmse are 1 and 0 respectively.
Therefore, the combined optimal value is 1.
"""
return f1_score(y_true, y_pred) - rmse(y_true, y_pred) | 5,320,957 |
def get_images_with_annotations(host, public_key, private_key, project_id=None, download=True, annotation_ids=None):
"""
Find and download (if not present) annotation information and images
:param annotation_ids: List of annotations to fetch
:param download: Whether or not to download missing files. Oth... | 5,320,958 |
def read_inap(room_name='K1N0624', start='2018-02-01', end='2018-03-01'):
"""
Function to download Indoor Environmental Quality (IEQ) data monitored by INAP sensors in SL demo-case
using IRI-UL web api. You may need to update the token if the current one is expired (contact IRI-UL).
Args:
room_... | 5,320,959 |
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Flu Near You sensors based on a config entry."""
coordinators = hass.data[DOMAIN][entry.entry_id]
sensors: list[CdcSensor | UserSensor] = [
CdcSensor(coordinators[C... | 5,320,960 |
async def infer_type_make_record(engine, _cls: dtype.TypeType, *elems):
"""Infer the return type of make_record."""
cls = _cls.values[VALUE]
if cls is ANYTHING:
raise MyiaTypeError('Expected a class to inst')
expected = list(cls.attributes.items())
if len(expected) != len(elems):
rai... | 5,320,961 |
def concatenate(trajectories):
"""Return the concatenation of a sequence of trajectories.
Parameters
----------
trajectories : sequence of sequences
A sequence of trajectories.
Returns
-------
sequence
The concatenation of `trajectories`.
"""
if isinstance(trajecto... | 5,320,962 |
def dlonlat_at_grid_center(ctr_lat, ctr_lon, dx=4.0e3, dy=4.0e3,
x_bnd = (-100e3, 100e3), y_bnd = (-100e3, 100e3),
proj_datum = 'WGS84', proj_ellipse = 'WGS84'):
"""
Utility function useful for producing a regular grid of lat/lon data,
where an approximate spacing (dx, dy) and total span of t... | 5,320,963 |
def copy_aligner(self, id_from, id_to):
"""
Copy the kernel weights from one aligner module to another
"""
if min(id_from, id_to) < 0 or max(id_from, id_to) >= self.height:
raise IndexError('Values {} --> {} out of bounds for size {}.'
.format(id_from, id_to, self.height... | 5,320,964 |
def attribute_test_service(request):
"""
Displays a list of all :model:`rr.Attribute` and values
found from environment variables.
**Context**
``object_list``
List of dictionaries containing attribute values and metadata.
``logout_url``
Logout URL.
**Template:**
:temp... | 5,320,965 |
def create_foundation_entity_instance(entity):
"""Create an instance of a Foundation SDK Entity"""
# Get an SDK class and use the configuration generation behaviour to pass in parameters
sdk_instance = SDK(**(request.get_json() or {}))
try:
# Entity names are PascalCase, SDK entity methods are ... | 5,320,966 |
def guided_alignment_cost(
attention_probs, gold_alignment, sequence_length=None, cost_type="ce", weight=1
):
"""Computes the guided alignment cost.
Args:
attention_probs: The attention probabilities, a float ``tf.Tensor`` of shape
:math:`[B, T_t, T_s]`.
gold_alignment: The true alignme... | 5,320,967 |
def _log_object_event(
ctx,
dbOperationsEvent=None,
event_status_id=None,
dbAcmeAccount=None,
dbAcmeAccountKey=None,
dbAcmeDnsServer=None,
dbAcmeOrder=None,
dbCertificateCA=None,
dbCertificateCAChain=None,
dbCertificateRequest=None,
dbCoverageAssuranceEvent=None,
dbDomain... | 5,320,968 |
def main():
"""COGclassifier main function for entrypoint"""
# Get argument values
args = get_args()
query_fasta_file: Path = args.infile
outdir: Path = args.outdir
download_dir: Path = args.download_dir
thread_num: int = args.thread_num
evalue: float = args.evalue
run(query_fasta_f... | 5,320,969 |
def catlogmatch_plot(catalog_mt, dd=0.2, dir_fig='.', figformat='png', fnametag=None):
"""
To plot the pie figure after comparing two catalogs.
Parameters
----------
catalog_mt : dic
a comparison catalog, for detail see 'utils_dataprocess.catalog_match'.
catalog_mt['status'] contain... | 5,320,970 |
def dismiss_message_url(course):
"""
Returns the URL for the dismiss message endpoint.
"""
return reverse(
'openedx.course_experience.dismiss_welcome_message',
kwargs={
'course_id': str(course.id),
}
) | 5,320,971 |
def cllr(lrs, y, weights=(1, 1)):
"""
Calculates a log likelihood ratio cost (C_llr) for a series of likelihood
ratios.
Nico Brümmer and Johan du Preez, Application-independent evaluation of speaker detection, In: Computer Speech and
Language 20(2-3), 2006.
Parameters
----------
lrs : ... | 5,320,972 |
def heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> torch.Tensor:
"""
Extract predicted keypoint locations from heatmaps.
Args:
maps (Tensor): (#ROIs, #keypoints, POOL_H, POOL_W). The predicted heatmap of logits for
each ROI and each keypoint.
rois (Tensor): (#R... | 5,320,973 |
def create_label_case(
target_dir: Path,
case_id: str,
instances: np.ndarray,
mapping: Dict[int, int],
dim: int,
) -> None:
"""
Crete labels for evaluation and analysis purposes
Args:
target_dir: target dir to save labels
case_id: case identifier
instances: i... | 5,320,974 |
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
... | 5,320,975 |
def logs(args):
"""View service logs"""
stacks = StackCache.load()
try:
config = stacks[args.name]
except KeyError:
sys.stderr.write("Unknown stack '{}'. Available stacks are: {}\n".format(args.name, ', '.join(stacks.keys())))
return 1
if not args.stderr or args.stdout:
... | 5,320,976 |
def add_user_input_to_scene(scene, user_input, keep_space_around_bodies=True):
"""Converts user input to objects in the scene.
Args:
scene: scene_if.Scene.
user_input: scene_if.UserInput or a triple (points, rectangulars, balls).
keep_space_around_bodies: bool, if True extra empty space... | 5,320,977 |
def language_add():
"""Return the page to add a language."""
is_user_logged_in = True if 'username' in login_session else False
context = {'is_user_logged_in': is_user_logged_in}
if request.method == 'POST':
if not is_user_logged_in:
flash('You have to log in to add a language.')
... | 5,320,978 |
def pyramid_sum(lower, upper, margin = 0):
"""Returns the sum of the numbers from lower to upper,
and outputs a trace of the arguments and return values
on each call."""
blanks = " " * margin
print(blanks, lower, upper) # Print the arguments
if lower > upper:
print(blanks, 0) # Print th... | 5,320,979 |
def transact():
"""pytest transact fixture for sqlalchemy."""
with Transact() as t:
yield t | 5,320,980 |
def grad_qform_1_ZV(a,f_vals,X_grad,ind,n,alpha):
"""
Gradient for quadratic form in ZV-1 method
"""
Y = f_vals[:,ind] + X_grad @ a
return 2./(n-1) * (X_grad*(Y - np.mean(Y)).reshape((n,1))).sum(axis=0) + 2*alpha*a | 5,320,981 |
def demo_nearest_self_image(image, display: bool = True):
"""
Demo for self-supervised denoising using camera image with synthetic noise
"""
Log.enable_output = True
Log.set_log_max_depth(5)
image = normalise(image.astype(np.float32))
noisy = add_noise(image)
self_image = nearest_self_... | 5,320,982 |
def test_card_draw_form_slider_default_step():
"""
Ensure the expected form widget and associated label are added to the
screen's layout instance.
"""
card = Card(
"title", form=Inputs.SLIDER, text="Form label...", options=(1, 100)
)
card.layout = mock.MagicMock()
card.font_size ... | 5,320,983 |
def send_tweet(self, *args, **kwargs):
"""Stub for filter method that returns one single tweet"""
self.listener.on_data(open('tweet.json', encoding='utf-8').read()) | 5,320,984 |
def calculate_movement_directions(data, stroke_label, direction_label):
"""Calculate the movement direction for each row in the data set based
upon the stroke values. This calculation method has the side effect of
losing the first and the last data rows.
INPUTS:
data: DataFrame.
stroke... | 5,320,985 |
def test_get_polls_from_user():
"""
Test existing functionalities of get_polls_from_user()
6 tests in total.
"""
result = get_polls_from_user('PollzOnTwitta')
# test output type
assert type(result) == list
# test output size (for an existing user)
assert len(result) >= 0
assert... | 5,320,986 |
def get_plot_extent(df, grid_stepsize=None, grid=False) -> tuple:
"""
Gets the plot_extent from the values. Uses range of values and
adds a padding fraction as specified in globals.map_pad
Parameters
----------
grid : bool
whether the values in df is on a equally spaced grid (for use in... | 5,320,987 |
def is_learner(user, program):
"""
Returns true if user is a learner
Args:
user (django.contrib.auth.models.User): A user
program (courses.models.Program): Program object
"""
return (
not Role.objects.filter(user=user, role__in=Role.NON_LEARNERS, program=program).exists()
... | 5,320,988 |
def _merge_global_options(needs_info, global_options):
"""Add all global defined options to needs_info"""
if global_options is None:
return
for key, value in global_options.items():
# If key already exists in needs_info, this global_option got overwritten manually in current need
if... | 5,320,989 |
def calculate_rupture_rates(
nhm_df: pd.DataFrame,
rup_name: str = "rupture_name",
annual_rec_prob_name: str = "annual_rec_prob",
mag_name: str = "mag_name",
) -> pd.DataFrame:
"""Takes in a list of background ruptures and
calculates the rupture rates for the given magnitudes
The rupture ra... | 5,320,990 |
def checkScriptParses(scriptVersion, script):
"""
checkScriptParses returns None when the script parses without error.
Args:
scriptVersion (int): The script version.
script (ByteArray): The script.
Returns:
None or Exception: None on success. Exception is returned, not raised.
... | 5,320,991 |
def normalize_caseless(text):
"""Normalize a string as lowercase unicode KD form.
The normal form KD (NFKD) will apply the compatibility decomposition,
i.e. replace all compatibility characters with their equivalents.
"""
return unicodedata.normalize("NFKD", text.casefold()) | 5,320,992 |
def select_device_mirrored(device, structured):
"""Specialize a nest of regular & mirrored values for one device."""
def _get_mirrored(x):
if isinstance(x, DistributedValues):
if not isinstance(x, Mirrored):
raise TypeError(
"Expected value to be mirrored across replicas: %s in %s." %
... | 5,320,993 |
def default_base_builder(individual: "Individual", frame: Frame, **kwargs) -> Dict[str, Any]:
"""Get base stats of the frame"""
v = dict()
# nodes
nodes = individual.nodes(frame_selector=frame, data=True)
v['nodes'] = list(nodes.keys())
v['macro_counter'] = Counter([d['macro'] for d in nodes.va... | 5,320,994 |
def plot_figure (susc_data, plot_filename):
"""Create a figure of the processed data"""
susc_figure = plt.figure()
susc_plot = plt.scatter (susc_data[:,0],susc_data[:,1])
plt.title ("IODP Expedition 303, Site U1302-03")
plt.xlabel ("Meters Composite Depth")
plt.ylabel ("Magnetic Susceptibility")... | 5,320,995 |
def calculate_maximum_potential_edge_counts(channel_composition, N, max_ble_span):
"""Computes the maximum number of possible occurrences per potential edge type.
Parameters
----------
channel_composition : Dict[str, int]
Channel composition description.
N : int
Number of BLEs in th... | 5,320,996 |
def test_save_data(tmpdir):
"""test save data to csv"""
save_data(tmpdir.join("test.csv"), [["Poprad", "Poprad", "A", "Adam", "Adam"]])
with open(tmpdir.join("test.csv"), mode="r") as file:
lines = file.readlines()
assert len(lines) == 2, "file have wrong number of lines"
assert lines[0] =... | 5,320,997 |
def generic_document_type_formatter(view, context, model, name):
"""Return AdminLog.document field wrapped in URL to its list view."""
_document_model = model.get('document').document_type
url = _document_model.get_admin_list_url()
return Markup('<a href="%s">%s</a>' % (url, _document_model.__name__)) | 5,320,998 |
def string_to_bool(value):
"""
boolean string to boolean converter
"""
if value == "true":
return True
else:
return False | 5,320,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.