content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_nth_line(file_name: str, line_no: int) -> str:
"""Return the given line of an input file.
:param line_no: Which line of the input file to return? Starts at 1!
:raises ValueError: line_no is too large for a small file or < 1.
"""
if line_no < 1:
raise ValueError(""""line_no" starts ... | bab9579a05f994d40e0b9ac32d8d9293936b4f86 | 646,755 |
def D50():
"""Return D50 illuminant as an (X,Y,Z) triple."""
# See [ICC 2001] A.1
return (0.9642, 1.0000, 0.8249) | de74610304ae00667d3f406f2c85096ab26b3802 | 646,756 |
def __tuples(a):
"""map an array or list of lists to a tuple of tuples"""
return tuple(map(tuple, a)) | 092c5b760e22f8b568668e27433a9733fbe6d85e | 646,757 |
def scale_filters(filters, multiplier, base):
"""Scale `filters` by `factor`and round to the nearest multiple of `base`.
Args:
filters: Positive integer. The original filter size.
multiplier: Positive float. The factor by which to scale the filters.
base: Positive integer. The number of filters will be... | 6b5b63ab78e6b592526cca85c6b9134acb850086 | 646,759 |
def map_values(function, dictionary):
"""
Transform each value using the given function. Return a new dict with transformed values.
:param function: keys map function
:param dictionary: dictionary to mapping
:return: dict with changed values
"""
return {key: function(value) for key, value ... | 7073f63e98f3b5e2a44bf76d74a40d08293f1a1d | 646,760 |
import subprocess
def _transform_json(obj):
"""
default function for json.dump
:param obj: Object, to be serialized
:return: Any.
"""
if isinstance(obj, subprocess.Popen):
return obj.pid | bd6e759973cc67478fc36b1764ac1e0741c0a024 | 646,761 |
from typing import Counter
def counter():
"""Return a new counter object."""
return Counter() | 4ec042b5b25b421916ef47c90685eeb8c2260bc4 | 646,763 |
import math
def interpolate(low, high, n, method):
"""
Interpolates between two numeric values.
The *n* parameter specifies the number of values to interpoluate.
Specifically the number of classes that will result from the interpolated
values.
The *method* parameter specifies the interpolation method.... | 9405c308abd59d54dff77abef49094fc53f16879 | 646,764 |
import os
def touch(file, mtime=None):
"""ensure a file exists, and set its modification time
returns the modification time of the file
"""
dirname = os.path.dirname(file)
if not os.path.exists(dirname):
os.makedirs(dirname)
open(file, 'a').close()
# set explicit mtime
if mtim... | 4f3c17e82e7f1c12fe6da6c68eb6b5478f93ccf2 | 646,766 |
def nearest_neighbor_interpolation(points):
"""
Input: list of points (x, y).
Returns a function f(x) which returns y value of nearest neighbor for given
x. At the midpoints (when distances to 2 closest points are the same) value
of point with lower x value is returned.
"""
points.sort(key=l... | 992e385d91a722989aef6c8f962863ddc46d6d25 | 646,768 |
from numpy import mean
def mean_crossover(couple: list) -> list:
""" Creates a list of mean values from two parent lists"""
mean_weights = [mean([a, b]) for a, b in zip(*couple)]
return mean_weights | 2beb82d10b526c39fb8cfb7bd2b4fc1e8932530f | 646,769 |
def cache_get_langs(sql):
"""Get the list of languages from tooltip database."""
return [row[0] for row in sql.execute(
"SELECT DISTINCT lang FROM vars").fetchall()] | 160e61c15c5141ac9a590a0993361ab6548796b5 | 646,770 |
import re
def remove_ignored_lines(lines):
"""
Removes ignored lines in ``lines``
Args:
lines (``list`` of ``str``): cell source as a list of strings
Returns:
``list`` of ``str``: stripped version of lines without ignored lines
"""
ignore_suffix = "# IGNORE"
stripped ... | 7fcad4f8c6cd28a5cd968e45f9e5cad154cb878a | 646,771 |
def trigger_reactions(polymer: str) -> str:
"""
Triggers the polymer reactions and returns the polymer with all the
reactions applied.
The algorithm works by iterating through the polymer and comparing the
current unit against the next unit. If the next unit is the same as
the current one but d... | 28eb37247b75243f662f0d3e2959a37bd6cdd3c9 | 646,772 |
def YamlFloatDigitRepresenter(dumper, data):
"""The representer for FloatDigit type."""
return dumper.represent_scalar(u"tag:yaml.org,2002:float", repr(data)) | e3b96cfeab57ddaa2d70c0cf445d560e0ca73a64 | 646,773 |
def is_inside_triangles(p, x1, y1, x2, y2, x3, y3):
"""
Returns a binary vector with True if point p is
inside a triangle.
x1,y1,x2,y2,x3,y3 are vectors with the 3 coordiantes of the triangles.
"""
alpha = ((y2 - y3)*(p[0] - x3) + (x3 - x2)*(p[1] - y3)) \
/ ((y2 - y3)*(x1 - x3) + (x3 - ... | b2023874b5a76ab97ccb188faa6d7b707f075ad5 | 646,774 |
def vector_multiply(vector, value):
"""
Args:
vector (list): 3 value list
value (float): value to multiply the vector by
Return:
list: 3 value list
"""
result = [vector[0] * value, vector[1] * value, vector[2] * value]
return result | 112d9ef2e14c29fa372810f99a65eac9f0dea47f | 646,777 |
def set_predict(kwargs):
"""Set attr argument and proba"""
out = dict()
proba = kwargs.pop('proba', False)
if proba:
out['proba'] = proba
out['attr'] = 'predict_proba' if proba else 'predict'
return out | 1c4c6f61c91500ffc2ede94686e85aa17f3426fc | 646,778 |
def pep8_module_name(name):
"""Convert a module name to a PEP8 compliant module name.
* lowercase
* whitespace -> underscore
* dash -> underscore
"""
if name[0].isnumeric():
name = '_'+name
valid_module_name = name.lower().replace('-', '_').replace(' ', '_')
... | ae9399663626321b040c52a598b2cd37e4421753 | 646,779 |
def with_session(request, app, cookie_name, generator):
"""MW для контроля cookies."""
if cookie_name not in request.cookies:
request.cookies[cookie_name] = generator()
value = request.cookies[cookie_name]
res = request.get_response(app)
res.set_cookie(cookie_name, value)
return res | 279a3ba0d9174886691932485544fb8ada65ca16 | 646,780 |
def put_list_to(path_to_file: str, lines: list):
"""
Write a list to a file in lines.
:param str path_to_file: /path/to/file
:param list lines: source list
:return: str
"""
with open(path_to_file, 'w') as fp:
content = list()
for line in lines:
content.append('{}... | 74d57c76e8303467441d6035d85b62e677a4db55 | 646,782 |
def get_geotag(post_content):
"""Gets latitude and longitude from post's HTML content."""
post_map = post_content.find("div", {"id": "map"})
geotag = {"lat": "", "lon": ""}
if post_map is not None:
geotag["lat"] = post_map.attrs["data-latitude"]
geotag["lon"] = post_map.attrs["data-longi... | a61c3742e6a0cdc23ef28fa8ec03631a20e1e352 | 646,783 |
def get_retrospective_location(location, velocity, time):
"""Calculate the original location and velocity based on the one at time t"""
return [l - v * time for l, v in zip(location, velocity)] | 87858a797b334e8e9af9fff52dcef873aae35197 | 646,784 |
def get_hosted_zone_id(session, hosted_zone):
"""Look up Hosted Zone ID by DNS Name
Args:
session (Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
hosted_zone (string) : DNS Name of the Hosted Zone to loo... | 98f0a54d9a440b44c2c266adc8f698090bde50de | 646,785 |
def assert_variable_type(variable, expected_type, raise_exception=True):
"""Return True if a variable is of a certain type or types.
Otherwise raise a ValueError exception.
Positional arguments:
variable -- the variable to be checked
expected_type -- the expected type or types of the variable
r... | 9610b5013aeb15a692a8b8f5c12a556f766a86fc | 646,786 |
import struct
def bytes_to_fp32(data):
"""小端字节序"""
byte = bytes([data[0]])
byte += bytes([data[1]])
byte += bytes([data[2]])
byte += bytes([data[3]])
ret = struct.unpack("<f", byte)
return ret[0] | fe28746dbd7ab3a2873f413864156e1d6621e0d6 | 646,787 |
def extract_string(data, offset=0):
""" Extract string """
str_end = offset
while data[str_end] != 0:
str_end += 1
return data[offset:str_end].decode('ascii') | fdf040903c7004b3ed8c032d5f91a0c78dfd0fce | 646,789 |
import json
def logformat(result):
"""
Format the dict/list as a json object
"""
rstr = json.dumps(result, indent=2)
if rstr[0] == '{':
rstr = rstr[1:-2]
return rstr | 186de312a9d6c90b660ae7733c67feb87bf6b94f | 646,790 |
import sqlite3
def get_all_assembled_contigs(cxn, bit_score=0, length=0):
"""Get all assembled contigs."""
sql = """
SELECT iteration, contig_id, seq, description, bit_score, len,
query_from, query_to, query_strand,
hit_from, hit_to, hit_strand
FROM aux.assemble... | 0780d6087dd40dd30d258716c108f647491811ed | 646,791 |
def combine_frames(frames, is_negative_class=False):
"""
Input: Pandas dataframe
Output: Pandas dataframe
Description: Concatenate all the dataframes together. When the input frames are for patients
without RRT events use is_negative_class=False, otherwise use is_negative... | d44e97c400f0b3da644ee187e56bdec637d1fd7a | 646,792 |
def original_production_volume(dataset, default=None):
"""Get original (i.e. before activity link subtractions) production volume of reference product exchange.
Returns ``default`` (default value is ``None``) if no or multiple
reference products, or if reference product doesn't have a production
volume... | 9ea2c18d7fe19ab2d5dce04caf6afe1eb9b5a7bd | 646,793 |
def _validate_list_of_or_raise(a_list, t):
"""Validates a List of items of a specific type"""
if not isinstance(a_list, (list, tuple)):
raise TypeError("Expected list, got {t}".format(t=type(a_list)))
for item in a_list:
if not isinstance(item, t):
raise TypeError("Expected type... | 2dd6181d0cde21309789a9361f4838910e015aee | 646,795 |
def convert_from_CAL_to_k(data):
"""
Transforms from CAL to k using k = (1 - CAL)
"""
return 1 - data | ea3a3a7a73a13662e07417206cb5725fc6b02575 | 646,796 |
def help_command():
"""Returns available commands with their help messages"""
return (
"Available commands:\n"
"/help - Show this message\n"
"/weather - Weather in `Zagazig, Egypt` now\n"
"/translate - Translate message from english to arabic\n"
"/calculate - Calculate a ... | dc64eeb3fe4768cc36e4ade27c39908f61343744 | 646,797 |
def word_count(text):
"""
Count number word in text
Args:
text (str): string text
Returns:
(int): number of word in text
"""
if isinstance(text, str):
tokens = text.split(" ")
else:
tokens = []
return len(tokens) | fa35beb4187eab1245f16e355193e66256d6f460 | 646,798 |
def cast_str_to_int_float_bool_or_str(str_, fmt='{:.3f}'):
"""
Convert string into the following data types (return the first successful): int, float, bool, or str.
:param str_: str;
:param fmt: str; formatter for float
:return: int, float, bool, or str;
"""
value = str(str_).strip()
f... | 50edf0028c5d6194947c426275437d4dc75c9a3b | 646,799 |
import argparse
def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--model_name',
type=str,
required=True,
default="deepfm",
help='Model Name.')
... | c4fe0338df8fbd6a63dacb904285cc00f27a5955 | 646,800 |
def exists(env):
""" Check if `gtags` module has been loaded in the environment """
return env['GTAGS'] if 'GTAGS' in env else None | 8feb1b08e24cd77c8f954c113f9fa6241496318d | 646,801 |
def filter_matching_fields(fields, other_fields):
"""return fields which are same as in other_fields list, ignoring the case"""
other_fields_lowercase = set([f.lower() for f in other_fields])
return [f for f in fields if f.lower() in other_fields_lowercase] | f8b0909e4872c0bc6b1212b8bd658debb38da922 | 646,802 |
def get_file_attachment(res_client, incident_id, artifact_id=None, task_id=None, attachment_id=None):
"""
call the Resilient REST API to get the attachment or artifact data
:param res_client: required for communication back to resilient
:param incident_id: required
:param artifact_id: optional
:... | 8dcf887f2773addbbf8a29791157f9be833ab9e9 | 646,803 |
def cal_local_high_low_point_score(high_low_points):
"""
:param high_low_points:
:return:
"""
score = 0
if len(high_low_points) <= 1:
return score
for i in range(1, len(high_low_points)):
score_i = 0
for j in range(0, i):
if high_low_points[i] >= high_low... | 9f6d2a7239d8bd76a4ddd670d29a0636c8d5f802 | 646,804 |
import textwrap
def literal(text: str) -> str:
"""
Quick way of 'quoting' the text
https://orgmode.org/manual/Literal-Examples.html
"""
return textwrap.indent(text, ': ', lambda line: True) | af821c624581cd9dd55b27d4a8937c7cd57c679a | 646,805 |
from typing import Union
from typing import Iterable
import numpy
def mag_decimation_subsample(
signal: Union[Iterable, numpy.ndarray],
decimation_factor: int = 10,
return_indices: bool = False,
truncate_last_indivisible: bool = True,
) -> numpy.ndarray:
"""
truncate_last_undivisible is false... | 20abb42a418896cc8b3e9f28b3dc1b4112778df9 | 646,806 |
def read_qudi_parameters(filename: str, folder: str = "") -> dict:
""" Extract parameters from a qudi dat file. """
if not filename.endswith(".dat"):
filename += ".dat"
params = {}
with open(folder + filename) as dat_file:
for line in dat_file:
if line == '#=====\n':
... | d4c08a0e9b7e5cc122581c5076047cb03a055106 | 646,807 |
def concatenate_dirs(dir1, dir2):
"""
Appends dir2 to dir1. It is possible that either/both dir1 or/and dir2 is/are None
"""
result_dir = dir1 if dir1 is not None and len(dir1) > 0 else ''
if dir2 is not None and len(dir2) > 0:
if len(result_dir) == 0:
result_dir = dir2
e... | 576f2f0df6d7f54c659a1a315920e748d784f4be | 646,808 |
def is_decomposed(P):
"""
Check if a polynomial (array) is on component form.
Args:
P (Poly):
Input data.
Returns:
(bool):
True if all polynomials in ``P`` are on component form.
Examples:
>>> x,y = cp.variable(2)
>>> print(cp.is_decomposed(... | f2e148ca3229a80770eb40a07ad811dec23416a3 | 646,809 |
def intersection_lists(lst1, lst2):
""" Return the intersection between two lists """
return list(set(lst1) & set(lst2)) | 9ab488c7658ff8a09b9210d6c778391030533bd0 | 646,810 |
from typing import List
def find_mine_pythonic_alt(field: List) -> List[int]:
"""Finds mine location (pythonic alternative).
Examples:
>>> assert find_mine([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == [1, 1]
"""
return next(
[field.index(sub_field), sub_field.index(1)]
for sub_field ... | 7ec65ae9698dd901cd07f3a2cf12a8fb9c27d65b | 646,811 |
def get_small_joker_value(deck):
"""(list of int) -> int
Precondition: the input deck is a valid deck.
Return the value of the small joker (value of the second highest card) for
the given deck of cards.
>>> deck = [ 18, 21, 24, 27, 2, 5, 8, 11, 14, 17, 20, 23, 26, 1, 4, 7, 10, \
13, 16, 19, 2... | ee25744adcd1f4b96f4fce8dafe24d93e0d8bb74 | 646,812 |
import copy
def _make_expansion_variables(media_block, content_version):
"""
Creates a dictionary of expansion variables for media items.
:param self:
:param media_block:
:param content_version:
:return:
"""
vars = copy.copy(media_block)
# strip black listed keys
black_list = ... | cbb4c6d6329b9d38a1168620311451da49a1e2be | 646,813 |
def specieset(structure):
""" Returns ordered set of species.
Especially usefull with VASP since we are sure what the list of species
is always ordered the same way.
"""
tmp = [a.type for a in structure]
species = sorted(set(tmp), key=tmp.index)
return species | 23d38b5e1052a6010e48794c2f2978b9fd753311 | 646,814 |
async def get_db_name(pool):
"""Gets the name of the current database."""
return await pool.fetchval("SELECT current_database()") | d81f486de7b2e0a45101b7d8badf6b3b855591ae | 646,815 |
def extract_prime_power(a, p):
"""
Return s, t such that a = p**s * t, t % p = 0
"""
s = 0
if p > 2:
while a and a % p == 0:
s += 1
a //= p
elif p == 2:
while a and a & 1 == 0:
s += 1
a >>= 1
else:
raise ValueError("Nu... | 39e39b7911ad71d6c15600cc52e61e5e819b05e4 | 646,816 |
def get_assignment_pool(possible_asn, assigned):
"""
Get an assignment pool, i.e. a set of distributions and shifts to assign independently from the rest
Inputs: - possible_asn List of possible assignments for each distribution
- assigned List of already assigned distribut... | 9f5b2804915c882cc92b2b8f143de3847726b121 | 646,817 |
def get_K(jfdb):
"""
Infer K from jellyfish db.
"""
j = jfdb.rsplit('_', 1)[0].rsplit('-', 1)[-1]
assert j[0] == 'K'
return int(j[1:]) | 82b649e09a57108e22006dc7baaef01b40570166 | 646,820 |
def load_file_list(filename):
"""
Load a text file containing a list of filenames (or other strings) as a
Python list.
To obtain a list of DataFile objects, the result can easily be converted
as in the example:
>>> raw_biases = DataFileList(load_file_list('list_of_biases.txt'))
If the lis... | bbb49943b9d5ea6869be35d343ce0f7452d1f6d5 | 646,821 |
def create_choice(klass, choices, subsets, kwargs):
"""Create an instance of a ``Choices`` object.
Parameters
----------
klass : type
The class to use to recreate the object.
choices : list(tuple)
A list of choices as expected by the ``__init__`` method of ``klass``.
subsets : l... | 948d6e1ba8082c82ff6a7e7dea643b4a39ee6a60 | 646,822 |
def addSpentMinutes(dataFrame):
"""
Create a new column with the amount of spent minutes on Netflix, by adding the current row's runtime's value to the column
Parameters:
dataFrame1: string
The name of the dataFrame in which the user wants to calculate the spent minutes
Returns:
... | f23fe19b8c4f491d61c3e35f54ca956ff0b65f0b | 646,823 |
import torch
def try_gpu(x):
"""Try to put a Variable/Tensor/Module on GPU."""
if torch.cuda.is_available():
return x.cuda()
return x | 2db7675874cfa50f4472fcaab4708d218d028fe3 | 646,824 |
def methods(attrdict):
"""Return all public methods and __init__ for some class."""
return {
name: method
for name, method in attrdict.items()
if callable(method)
and (not name.startswith("_") or name == "__init__")
} | 81d77e191475431124fa4fe1b1ccc74ef7f016d3 | 646,825 |
import time
def chop_midnight( tsecs ):
"""
Returns the epoch time at midnight for the given day.
"""
tup = time.localtime( tsecs )
tup = ( tup[0], tup[1], tup[2], 0, 0, 0, tup[6], tup[7], tup[8] )
return int( time.mktime( tup ) + 0.5 ) | 267b6c576288f0bffc831104e208582a783eef8f | 646,826 |
def _fig_nset(tree, rectangle, sqloc, node, nlyst):
"""
Set node value in rectangle
"""
if node < 0:
return nlyst
nlyst.append([sqloc[0] + tree[node]['point'][1],
sqloc[1] + tree[node]['point'][0]])
return _fig_nset(tree, rectangle, sqloc, tree[node]['prev_gen'], nlyst) | 557921add00859e60d78c00f1c4b3e44fa9b005e | 646,827 |
def docstring_interpolate(name, values):
"""Interpolate a variable into a function's docstring.
Use to prevent duplication of documentation in `create` and `update` methods."""
def _decorator(func):
args = {name: values}
if func.__doc__:
func.__doc__ = func.__doc__.format(**args)... | 7b0c6682466b43870d53dfafe1bd550317e8754b | 646,828 |
def difference_with(f, xs, ys):
"""Finds the set (i.e. no duplicates) of all elements in the first list not
contained in the second list. Duplication is determined according to the
value returned by applying the supplied predicate to two list elements"""
out = []
for x in xs:
if x in out:
... | 13304fc3b0a7335c5c30b7c16d35bec1e37ae7bd | 646,829 |
import math
def roundup(x, n=10):
"""Round up x to multiple of n."""
return int(math.ceil(x / n)) * n | 6cd0fcddf7488a3aecd13a255dabaa3a775c125e | 646,830 |
def site(coord, size, xperiodic):
"""
numbering the square lattice sites
Parameters
--------------
site : (x, y)
(x, y) coordinate of the site
size : (int, int) -> (nx, ny)
linear size of the square lattice
xperiodic : boolean
indicates PBC along x
"""
nx, ny... | f0344d7663c45054968ab44a793b7c651dbb608a | 646,831 |
import itertools
def mixedCase(*args):
"""
Generates a completely random number
Guaranteed to be random 100% **WORKING 2020** FREE HD 4k
"""
total = []
for string in args:
a = map(''.join, itertools.product(*((c.upper(), c.lower()) for c in string)))
for x in list(a): total.app... | 091100f0be9f697d04cc4764a8a5222b71488b78 | 646,833 |
def rpn_function(code):
"""wrapper command generator, used to inject RPN functions into the namespace"""
def wrapper(stack):
stack.interpret(code)
return wrapper | eda147d902589c8051d79443de0d0bd7080d5ac8 | 646,834 |
def max_attribute_index(items, attr):
""" Find the index of the field with the maximum length in a list of Items.
Arguments
---------
items : list
The list of Item instances.
attr : str
Attribute to look at.
"""
if attr == 'definition':
attributes = [len(' '.join(i... | 696964c5d72cf2eceae881c4cb8377979cf23bec | 646,835 |
def error_regression_plot(data):
"""Plot the data from the regression fit."""
x = data["regression_x"]
y = data["regression_y"]
fit = (x * (data["model_a"] ** 2)) + ((data["model_a"] * data["model_b"]) ** 2)
return {
"regression_fit": {
"data": [
{
... | 54ed6cab31f5e6e1a321963cda33d4533a7bde08 | 646,836 |
def is_illegal_sequence(seq: str) -> bool:
"""True if seq is one of the forbidden sequences."""
return seq in ['ab', 'cd', 'pq', 'xy'] | fadc2e314553a1c2af0c02b9482c19f3e3cef11a | 646,837 |
import re
def cc_string(identifier: str) -> str:
""" From https://stackoverflow.com/questions/29916065/how-to-do-camelcase-split-in-python """
matches = re.finditer(
".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier
)
return " ".join([m.group(0) for m in matches]) | bbda5ef8900251066737360160a131fd89ac5730 | 646,839 |
def check_for_radicals(mol_list):
"""Check if list of molecules contains a radical.
"""
to_remove = []
for name in mol_list:
if 'radical' in name:
# new_name = name.replace('radical', '').lstrip().rstrip()
# if new_name in mol_list:
print('removing', name, '... | 3d422040aab4de27b8a49706ed25db3677542201 | 646,840 |
import requests
import logging
def get_news_from_steamNetAPI(game_id):
"""
This is the function that gets the latest news of a game from the Steam API.
Params:
game_id - Integer
Returns:
List - Contains 3 dictionaries with the 'actual' news.
"""
try:
game_news_api... | e9f13957d076a17cfd767ef4d383fd55be0c9c57 | 646,841 |
import re
def is_discord_username(username):
"""re makes me feel smart"""
if re.match(r'.+#\d{4}', username):
return True
return False | 0ed34eb8c0de953c0098071003723268737b087c | 646,842 |
def compute_overlap(bound1, bound2):
"""
Get the bound of the overlapping section between two bounds
:param bound1: bound where overlap is to be checked
:param bound2: bound where overlap is to be checked
:return: bound tuple of overlap between ``bound1`` and ``bound2``
if there is no overl... | 9e6853aa13f4395bb2a151c0f24a5aec766ab78f | 646,843 |
def str2int(s):
"""Convert an octet string to an integer. Octet string assumed to represent a positive integer."""
r = 0
for c in s:
r = (r << 8) | ord(c)
return r | f6646c18e7df0e96983bdeb2633cf9b533fa70e2 | 646,844 |
def clean_add_umlaut(line):
"""Returns the line cleaned of incorrect umlauting
Param:
line (unicode)
Returns:
Corrected line
"""
cleaned_line = line
umlaut_dict = {
'a"': 'ä',
'i"': 'ï',
'o"': 'ö',
'u"': 'ü',
'e"': 'ë',
'A"': 'Ä',... | 7c43180566f1b8c3b4c858726f9d73b0e625b05c | 646,845 |
def increment_deck(deck_size, cards, increment):
"""Increment operation."""
return [(card * increment) % deck_size for card in cards] | 715443b32a5ec2dfad7ed2ee55a3ed831082835e | 646,847 |
import numpy
def get_7z_from_bfp_z123(z123):
"""Implements Eq. (7.7) from: https://arxiv.org/pdf/1909.10969.pdf"""
z1, z2, z3 = z123
return numpy.array([-z2, -z3, z1, z1, z1, -z3, -z3]) | 349d191b6bb9d7bd6cf648a20f156e1eac0c1d95 | 646,848 |
def get_lr(optimizer):
"""Gets learning rate given an optimizer
Args:
optimizer ([type]): [description]
"""
for param_group in optimizer.param_groups:
return param_group['lr'] | cfdb44f03836bd28513fce8a98a9ce5f86288549 | 646,850 |
def footer():
"""feets"""
footer_list = '^^^(this) ^^^(bot) ^^^(uses) ^^^(the) [^^^(scripture.api.bible)](https://scripture.api.bible/) ' \
'^^^(web) ^^^(services) ^^^(from) [^^^(American) ^^^(Bible) ^^^(Society)]' \
'(https://www.americanbible.org/) ^^^(|) [^^^source ^^^code... | b909e74cb2a42e3d21d2aab3bbfefa0323a2e3e8 | 646,851 |
def make_mfe_cmd(primers,
database,
output,
mfe_exec,
ppc,
min_tm,
oligo_conc,
mv_conc,
dv_conc):
"""
Make the MFEprimer command to test the primers' coverage and/or specifici... | 94b05f8f34eb4e851c626c343e488c69f29d9fb2 | 646,852 |
import numpy
def gaussian(x, sx, y=None, sy=None):
"""Returns an array of numpy arrays (a matrix) containing values between
1 and 0 in a 2D Gaussian distribution
arguments
x -- width in pixels
sx -- width standard deviation
keyword argments
y -- height in pixels (default = x)
sy -- height standard devi... | daa905d4b1d690b8a0ed95552bad8a0d9aa8dee9 | 646,854 |
import subprocess
import os
def discover_darshan_pkgconfig():
"""
Discovers an existing darshan-util installation and returns the appropriate
path to a shared object for use with Python's CFFI.
:return: Path to a darshan-util installation.
"""
args = ['pkg-config', '--path', 'darshan-util']... | 80a114afe768de3844266a5c5333e9d02d429539 | 646,856 |
def calculate_check_digit(number):
"""
Given a number without the check-digit, calculate
the check digit and return it.
See: https://www.gs1.org/services/how-calculate-check-digit-manually
"""
# Step 2: Multiply alternate position by 3 and 1
# and get the sum
step_2 = sum(
[int(... | 7c219600ae96672344d14cbce997ce1c0a1f7ff7 | 646,858 |
import unicodedata
import re
def preprocess_sentence(w):
""" preprocess_sentence """
w = ''.join(c for c in unicodedata.normalize('NFD', w.lower().strip())
if unicodedata.category(c) != 'Mn')
w = re.sub(r"([?.!,?])", r" \1 ", w)
w = re.sub(r'[" "]+', " ", w)
w = re.sub(r"[^a-zA-Z?.!,?]+", ... | 3a981384196d206a5d08d5e5928b24a8e9791c7b | 646,859 |
import torch
def build_attn_mask(source_mask: torch.Tensor, s: int, head_num:int):
"""
:param source_mask: B, t
:param s: source size
:param head_num: multi head attention's head num
:return: atten_mask: (B * head_num, s, t)
attn_mask 的 第 i 个位置表示 source 和 target 是否要进行attention操作,对于没有定义的source... | e83d5f0406cec1e2e454aa9cb9c34ed8044b8246 | 646,860 |
import os
def read_file(file_path):
""" Gets the provided file and reads its content as bytes,
after that, it stores everything in the variable payload_list,
which it returns. """
payload_list = list()
if os.path.isfile(file_path):
print("Loading File in: " + file_path)
with ope... | 4d05fb014daa1b04fa60546e109052d4789fe0df | 646,861 |
def b64max(char_length):
""" Maximum number of raw bits that can be stored in a b64 of length x """
# Four byte increments only, discard extra length
return (char_length // 4) * (3 * 8) | fc5adc579bf8a250b161723a7e31fc7a71c06aee | 646,862 |
def get_age_df(df, age_list):
"""Gets a DataFrame and filters it for the purpose of putting specific
ages on the Concordia plots. Note the DataFrame must have a column named
'age'.
Parameters
----------
df : DataFrame
A dataframe with a column 'age'.
age_list : list
A list o... | 4c007f23fed55d808b2c6bb426b7f66f788a8d68 | 646,863 |
def test_frozen_parameters_not_changed(trainer):
"""Perform a training step and verifies that no parameters in frozen
layers changed."""
print("No parameters changed in frozen layers", end="")
passed, msg = True, ""
trainer.fit(epochs=1, max_steps=1, max_eval_steps=0)
for name, new_param i... | 80d87131afb568f0262d1651a49d2556c80d087a | 646,864 |
import math
def score_clusters(intervalMap, lengths, rd, baf, m):
"""
This function will score the given cluster assignments in the intervalMap based on the average
distance to the cluster center.
"""
cluster_scores=[float('inf') for x in range(m)]
for key in intervalMap.keys():
if key == -1:
#cluster_sc... | 1c046d7ec19c442a76be88c37635d34fb3cf83dd | 646,865 |
def build_frequency(dataset, vocab):
""" create list of frequencies for each unique word in class"""
freq = [0.0] * len(vocab)
for message in dataset:
words = message.split()
for word in words:
if word in vocab:
freq[vocab.index(word)] += 1.0
# divide every el... | f55e0646f3953d8a8cc46a8d63d69c598d12fd33 | 646,866 |
def rm_duplicates(lis):
""" Takes a list, removes duplicates and returns it sorted. """
a_set = set(lis)
return sorted(a_set) | c3571f5002a0c02cfe404b7613d1db5e685e56bc | 646,867 |
import time
def sleepMacbeth(tuple):
""" He does - """
time.sleep(1);
return True | e4df86588d5d7516f523da9589a2309b018306f5 | 646,868 |
def researched_before(technology, timestamp, player):
"""Check if a technology was researched before a given time."""
for item in player['research']:
if item['technology'] == technology and item['timestamp'] < timestamp:
return True
return False | dc13485aa0be40fa2cb2c25fe0926e8e97f32c9d | 646,869 |
def challenge_request(name):
"""Create ACME "challengeRequest message.
:param str name: Domain name
:returns: ACME "challengeRequest" message.
:rtype: dict
"""
return {
"type": "challengeRequest",
"identifier": name,
} | b9f781b5abafe57f9b979af46d4132f865196ac4 | 646,871 |
import statistics
def r_squared(pred, res):
"""
Calculating the R² score of this model.
Value returned is between 0.0 and 1.0, the higher the better.
:param pred: List<Int>
:param res: List<Int>
:return: Float
"""
ss_t = 0
ss_r = 0
for i in range(len(pred)):
ss_t += (... | 2390cefd6c562b396bbc53204c823e001c07354d | 646,872 |
def average(lst):
"""Averages a list, tuple, or set of numeric values"""
return sum(lst) / len(lst) | 4c29af810ebd80de38cf8fad2622e1d2c701f5e4 | 646,873 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.