content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def rst2rst_folder(rststring, folder, document_name="index", **options):
"""
Converts a :epkg:`RST` string into simplified :epkg:`RST`.
@param rststring :epkg:`rst` string
@param folder the builder needs to write the resuts in a
folder defined by... | 5,306,300 |
def test_password_confirmation(client):
""" Unit Test for Password Confirmation"""
response = client.get("/register")
test_password = 'Dummy_Pass_123'
if User.email is not None:
if User.password == test_password:
assert 'Congratulations, you are now a registered user!' in response.da... | 5,306,301 |
def _parse_dictzip_field(subfield):
"""Returns a dict with:
chlen ... length of each uncompressed chunk,
zlengths ... lengths of compressed chunks.
The dictzip subfield consists of:
+---+---+---+---+---+---+==============================================+
| VER=1 | CHLEN | CHCNT | CHCNT ... | 5,306,302 |
def BPmatch_slow_asym(c1, c2, G1, G2, dmax):
"""
New version which makes the differences between ascending
and descending links
- c1 and c2 are arrays of shape (n1,d) and (n2,d) that represent
features or coordinates,
where n1 and n2 are the number of things to be put in correpondence
and d ... | 5,306,303 |
def post_sample_ar_complete_multipart_upload_url(request, pk):
"""Reply with a sample group manifest."""
arf = authorize_sample_ar_upload_url(request, pk)
upload_id, parts = request.data['upload_id'], request.data['parts']
blob = arf.get_presigned_completion_url(upload_id, parts)
return Response(blo... | 5,306,304 |
def get_movies_by_director(data=movies_csv):
"""Extracts all the movies from csv and stores them in a dictionary
where keys are directors, and values is a list of movies (named tuples)"""
directors = defaultdict(list)
with open(data, encoding='utf-8') as f:
for line in csv.DictReader(f):
... | 5,306,305 |
def distance(F, shape_params=None, use_chamfer=False):
"""
Arguments:
----------
F: Tensor of size BxNxM, with the values of the inside-outside function
for the N points w.r.t. the M primitives
shape_params: Tensor with size BxMx3, containing the shape along each
... | 5,306,306 |
def extract_latest(obsv_data):
""" take the 'obsv' data dict and extract entries matching latest predictions.
We know the 'obsv' contains entries of observations and forecasts. Each entry
has the name of the dam as the last item three from the end of the line.
We want one observation of the latest level... | 5,306,307 |
def match(word, guess_n):
"""
This function is built for matching user's guessing with the answer.
Every single alpha will be scrutinized.
If correct, alpha will be shown to users and replace '-'.
If not, guessing chances will depreciate.
(it will print illegal if user type in alpha from diction... | 5,306,308 |
def get_cybex_dataframe(
db, start_date_utc, ticket_severity, group, tickets_closed_past_days
):
"""Stolen from https://github.com/jsf9k/ncats-webd/blob/develop/ncats_webd/cybex_queries.py."""
now = datetime.datetime.now(datetime.timezone.utc)
tomorrow = now + datetime.timedelta(days=1)
days_to_grap... | 5,306,309 |
def run(queue_name):
"""Spawn a worker on the named queue."""
start_worker_process(queue_name) | 5,306,310 |
def html(i):
"""
Input: {
(skip_cid_predix) - if 'yes', skip "?cid=" prefix when creating URLs
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
... | 5,306,311 |
def attach_route_table(**_):
"""Attaches a Route Table (source) to the Subnet (target)"""
rtbl = RouteTable(_ctx=ctx.source)
rtbl_name = utils.get_resource_name(ctx.source)
# Attach
utils.task_resource_update(
Subnet(_ctx=ctx.target, api_version=ctx.source.node.properties.get(
'a... | 5,306,312 |
def history(name):
"""
History view for a wiki page.
"""
if isfile(
join(settings.CONFIG["wiki_root"], name + "." + settings.CONFIG["suffix"])
):
fname = join(
settings.CONFIG["wiki_root"], name + "." + settings.CONFIG["suffix"]
)
rel_fname = relpath(fnam... | 5,306,313 |
def decompose_frame(frame:pd.DataFrame):
"""
Runs a full decomposure against a given DataFrame
:param: frame - a pandas dataframe
:return: a pandas Series that is the smallest unique label set
"""
_frame = frame.drop_duplicates()
_frame_size = len(_frame)
_weight_series = generate_weight... | 5,306,314 |
def page_not_found_view(request, exception=None):
""" A view to render custom 404 not found page """
if exception:
messages.error(request, f"error encountered: {exception}")
return render(request, 'errors/404.html') | 5,306,315 |
def mock_handlers() -> AsyncMock:
"""Get an asynchronous mock in the shape of CommandHandlers."""
# TODO(mc, 2021-01-04): Replace with mock_cmd_handlers
return CommandHandlers(
equipment=AsyncMock(spec=EquipmentHandler),
movement=AsyncMock(spec=MovementHandler),
pipetting=AsyncMock(s... | 5,306,316 |
def analyze_user(information_extractor, sql, args):
""" Analyzes a given user with semantic/syntactic similarities"""
df = parse_raw(sql, args.input)
count = df.count()
print("number of posts: {0}".format(count))
rdd = df.rdd.repartition(args.partitions)
rdd = rdd.map(lambda x: premap_post(x, ar... | 5,306,317 |
def logout(request):
""" Logs out the user from the system"""
permission_obj = PermissionValidation(request)
permission_obj.logout(request)
data = {
'success': True
}
return Response(data, status=status.HTTP_200_OK, content_type='application/json') | 5,306,318 |
def filter_check_route_map_set_items(value):
"""
Function to check route-map set options in a template
:param value:
:return:
"""
error = f'{value} !!!! possible error check template for possible set items!!!!'
if not value: # pylint: disable=no-else-return
J2_FILTER_LOGGER.info('fi... | 5,306,319 |
def _GetErrorDetailsSummary(error_info):
"""Returns a string summarizing `error_info`.
Attempts to interpret error_info as an error JSON returned by the Apigee
management API. If successful, the returned string will be an error message
from that data structure - either its top-level error message, or a list of... | 5,306,320 |
def state_to_trip(trip_state, kp_state):
"""The function state_to_trip was added to have a uniform way of using the state between kinpy
and TriP in the tests
Args:
state (dict): dictionary with the state name of each joint as it occurs in TriP as the key
and a float as t... | 5,306,321 |
def get_recent_mask_dir(input_dir=None):
"""Grab the most recent sub-directory of masks in MASK_DIR.
Parameters
----------
input_dir : :class:`str`, optional, defaults to ``None``
If passed and not ``None``, then this is returned as the output.
Returns
-------
:class:`str`
... | 5,306,322 |
def format_duration_hhmm(d):
"""
Utility function to format durations in the widget as hh:mm
"""
if d is None:
return ''
elif isinstance(d, str):
return d
hours = d.days * 24 + d.seconds // 3600
minutes = int(round((d.seconds % 3600) / 60))
return '{}:{:02}'.format(hours... | 5,306,323 |
def get_feed_list(opml_obj: OPML) -> List[str]:
"""Walk an OPML document to extract the list of feed it contains."""
rv = list()
def collect(obj):
for outline in obj.outlines:
if outline.type == 'rss' and outline.xml_url:
rv.append(outline.xml_url)
if outlin... | 5,306,324 |
def change_password(
session: Session,
new_password: str,
current_password: Optional[str] = None,
current_password_hash: Optional[str] = None,
username: Optional[str] = None,
email: Optional[str] = None,
user_id: Optional[uuid.UUID] = None,
) -> User:
"""
Change a user's password.
... | 5,306,325 |
def get_args():
"""
read parser and return args (as args namespace)
"""
parser = argparse.ArgumentParser(description='Modify/Update existing configuration file to v0.5')
parser.add_argument('-f', nargs=1, type=str, help='File to modify', required=True)
parser.add_argument('-d', '--debug', ac... | 5,306,326 |
def pt_index(*args):
"""Access stored Pressure Transducer data from the sensor limits and collected data to index and build an integer numpy array for sensor values that have exceeded the set bounds.
Parameters
----------
pt_limits : int numpy array
Values for pressure transducer limits.
pt... | 5,306,327 |
def transcribe(audio,
data,
score=None,
res=0.001,
sr=SR,
return_mini_specs=False):
"""
Takes an audio mono file and the non-aligned score mat format as in asmd.
Align them and perform NMF with default templates.
Returns new scor... | 5,306,328 |
def save_article(article: Dict[str, any]) -> None:
"""글을 CSV 형태로 저장한다"""
cols = [
'article_id', 'start', 'end', 'answered', 'votes', 'category', 'title',
'content'
]
# 파일이 없으면 새로 만들고 칼럼 이름 저장
if not os.path.isfile(CSV_FILE_WHOLE):
with open(CSV_FILE_WHOLE, 'w', newline='') a... | 5,306,329 |
def generate_housing_dataset(
num_rows=None, noise=None, distribution="poisson"
) -> Tuple[pd.DataFrame, np.ndarray, np.ndarray]:
"""Generate the openml house_sales housing dataset."""
df = _read_housing_data(num_rows, noise, distribution)
y, exposure = compute_y_exposure(df, distribution)
return ... | 5,306,330 |
def quaternion_to_yaw(quat: Quaternion, in_image_frame: bool = True) -> float:
"""Convert quaternion angle representation to yaw."""
if in_image_frame:
v = np.dot(quat.rotation_matrix, np.array([1, 0, 0]))
yaw = -np.arctan2(v[2], v[0])
else:
v = np.dot(quat.rotation_matrix, np.array(... | 5,306,331 |
def try_int(obj):
"""return int(obj), or original obj if failed"""
try:
return int(obj)
except ValueError: # invalid literal for int()
return obj | 5,306,332 |
def s3_datetime(name="date", **attr):
"""
Return a standard Datetime field
Additional options to normal S3ResuableField:
default = "now" (in addition to usual meanings)
represent = "date" (in addition to usual meanings)
widget = "date" (in addition to usual meani... | 5,306,333 |
def check_for_wkhtmltohtml():
"""
Checks to see if the wkhtmltohtml binary is installed. Raises error if not.
"""
locator = 'where' if sys.platform == 'win32' else 'which'
wkhtmltopdf = (subprocess.Popen([locator, 'wkhtmltopdf'],
stdout=subprocess.PIPE)
... | 5,306,334 |
def test_exac_filter_1(test_scheme, setup_filter, get_empty_maf_record):
"""
Test exac filter when all freqs are None
"""
cutoff = 0.0004
filterer = setup_filter(cutoff)
maf_record = get_empty_maf_record
for key in subpops:
maf_record[key] = get_builder(key, test_scheme, value=None)
... | 5,306,335 |
def save_word_list(words):
"""
save word list
"""
count = 0
with open("wordlist.ts", "w") as file:
file.write("export const WORDS = [\n")
for word in words:
file.write(f"'{word[0]}', // {word[1]}\n")
count += 1
file.write("]")
print(f'words saved... | 5,306,336 |
def gb_predict(X, model):
"""Apply a gradient boosting model using a standard function. It is a wrapper function."""
y = model.predict(X)
return y | 5,306,337 |
def read(stream):
"""Read ILDA data from a stream until we hit the
end-of-stream marker. Yields a sequence of Table objects.
"""
while True:
t = Table()
t.read_stream(stream)
if not t.length:
# End-of-stream
break
yield t | 5,306,338 |
def get_fft_features(npy_file='', m=84, keypoint=7):
"""
Parameters
----------
npy_file
m:
without trimmming: m = 84
with trimming: m = 51
keypoint
coordinate
Returns
-------
"""
raw_data = np.load(npy_file)
res = []
for coordinate in range(3):
data = raw_data[:, keypoint, coordinate]
data =... | 5,306,339 |
def _anonymous_model_data(ops_data):
"""Returns a dict representing an anonymous model.
ops_data must be a dict representing the model operations. It will
be used unmodified for the model `operations` attribute.
"""
return {"model": "", "operations": ops_data} | 5,306,340 |
def load_eazypy_templates(eazytemplatefilename,
format='ascii.commented_header',
verbose=True,
**kwargs):
"""Read in the galaxy SED templates (basis functions for the
eazypy SED fitting / simulation) and store as the 'eazytemplatedata... | 5,306,341 |
def encoding_string(string):
"""
Encoding URL per RFC 3986.
"""
return(quote(string,safe='')) | 5,306,342 |
def load(family_name):
"""
Loads a given blockchain package as `dposlib.core` module.
"""
if hasattr(sys.modules[__package__], "core"):
try:
sys.modules[__package__].core.stop()
except Exception as e:
sys.stdout.write("%r\n" % e)
del sys.modules[__package__].core
# initialize blockchain f... | 5,306,343 |
def collect_files_from_dir(directory, prefix="", suffix="", recursive=True):
"""
Collects the files in the given directory that matches the given prefix
and suffix.
"""
files = []
_collect_files_from_dir(directory, prefix, suffix, recursive, files)
return files | 5,306,344 |
def encode_to_dict(encoded_str):
""" 将encode后的数据拆成dict
>>> encode_to_dict('name=foo')
{'name': foo'}
>>> encode_to_dict('name=foo&val=bar')
{'name': 'foo', 'val': 'var'}
"""
pair_list = encoded_str.split('&')
d = {}
for pair in pair_list:
if pair:
key = pair.spli... | 5,306,345 |
def array_to_dataframe(x: np.ndarray) -> pd.DataFrame:
"""Convert Numpy array to Pandas DataFrame with default column names."""
return pd.DataFrame(x, columns=[f'x{i}' for i in range(x.shape[1])]) | 5,306,346 |
def replace_items(infile, old_word, new_word):
"""Replace old_word with new_world in file infile."""
if not os.path.isfile(infile):
print("Error on replace_word, not a regular file: " + infile)
sys.exit(1)
f1 = open(infile, 'r').read()
f2 = open(infile, 'w')
m = f1.replace(old_word,... | 5,306,347 |
def check_matrix(matrix, gold, pred):
"""Check matrix dimension."""
if matrix.size == 1:
tmp = matrix[0][0]
matrix = np.zeros((2, 2))
if (pred[1] == 0):
if gold[1] == 0: #true negative
matrix[0][0] = tmp
else: #falsi negativi
matrix[1][0] = tmp
else:
if gold[1] ==... | 5,306,348 |
def create_inference_pipeline(sm_role,
workflow_execution_role,
inference_pipeline_name,
return_yaml=True,
dump_yaml_file='templates/sagemaker_inference_pipeline.yaml'):
"""
Return YAML definition... | 5,306,349 |
def send_job(fn, data, args, step):
"""decide if send jobs with ipython or run locally"""
res = []
logger.my_logger.debug("doing %s" % step)
if step not in resources:
raise ValueError("step not in resources %s" % step)
else:
args.memory_per_job = resources[step][0]
args.cores... | 5,306,350 |
def list_keys(ctx, serials, readers):
"""
List connected YubiKeys.
"""
if readers:
for reader in list_readers():
click.echo(reader.name)
ctx.exit()
# List all attached devices
pids = set()
for dev, dev_info in list_all_devices():
if serials:
... | 5,306,351 |
def plot_sv_comparison(*, dates, noisy_sv, denoised_sv, model, obs, model_name,
fig_size=(8, 6), font_size=12, label_size=16,
plot_legend=False, plot_average=False,
window_length=12, min_samples=3, save_fig=False,
write_path=Non... | 5,306,352 |
def taxonomy_levels_below(taxa_level):
"""
E.g. 'Order' --> ['Family', 'Genus']
"""
p_levels = ['Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus']
position_of_taxa_level = p_levels.index(taxa_level)
return p_levels[position_of_taxa_level + 1:] | 5,306,353 |
def build_dict_from_role_object(plotly_dict: dict, is_dict: bool = True) -> dict:
"""
a recursive function that takes in a plotly api dict and transforms it to json schema format
"""
# blacklist if for keys that we are not going to put into our wizard
blacklist = [
"stream",
"transfo... | 5,306,354 |
def higher_order_shelving_holters(Gd, N, wc=1, normalize=True):
"""Higher-order shelving filter design by Martin Holters."""
g = 10**(Gd / 20)
alpha = np.stack([np.pi * (0.5 - (2*m+1)/2/N) for m in range(N)])
p = -np.exp(1j * alpha)
z = g**(1 / N) * p
k = 1
if normalize:
z *= g**(-0.... | 5,306,355 |
def _loglevel_changer(attr, val):
"""Handle a change of conf.logLevel"""
log_scapy.setLevel(val) | 5,306,356 |
def paste():
"""Return a string from the OS clipboard."""
command = ["pbpaste"]
if os.uname().sysname == "Linux":
command = ["xclip", "-selection", "clipboard", "-o"]
return (
subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)
.stdout.read()
.strip()
) | 5,306,357 |
def bin_prd_clsf_info_pos(y_true, y_pred, threshold=0.5, N_MORE=True, epsilon=1e-7):
"""refer to this: https://stats.stackexchange.com/questions/49579/balanced-accuracy-vs-f-1-score
Both F1 and b_acc are metrics for classifier evaluation, that (to some extent) handle class imbalance. Depending
of whic... | 5,306,358 |
def is_public(obj, attr):
"""Return True if input attribute is PUBLIC.
A public attribute has the name without '_' as a prefix.
Parameters
----------
obj : object
Any class instance.
attr : str
Name of the attribute to check.
"""
_check_is_attr_name(attr)
# Exclude... | 5,306,359 |
def custom_ucr_report_filter_values() -> List[Tuple[str, str]]:
"""Custom filter values
Parameters:
None
Returns:
List of Tuple[value_name, python path to value class]
The value class must extend ``ChoiceListFilterValue``
""" | 5,306,360 |
async def type_afk_is_not_true(notafk):
""" This sets your status as not afk automatically when you write something while being afk """
global ISAFK
global COUNT_MSG
global USERS
global AFKREASON
if ISAFK:
ISAFK = False
msg = await notafk.respond("I'm no longer AFK.")
awa... | 5,306,361 |
def roles_to_groups(user, roles=None):
"""
Add users to groups based on roles from single sign-on identity provider
roles:
adjudicator: e.g. Groundwater Data Specialist
Enters applications for new or existing registrants.
read/write access to: Person, Organization, Application, Regi... | 5,306,362 |
def sort(nodes, total_order, dedup=False):
"""Sorts nodes according to order provided.
Args:
nodes: nodes to sort
total_order: list of nodes in correct order
dedup: if True, also discards duplicates in nodes
Returns:
Iterable of nodes in sorted order.
"""
total_order_idx = {}
for i, nod... | 5,306,363 |
def make_script_clip_image_by_shape(region_prefix,image_file,shape_file,command_file,out_folder,out_ext):
"""
region_prefix: huyu,xwd
out_ext: .png, .tif
"""
# of: output format GTiff PNG JPEG
command_str = "gdal_translate -projwin %s %s %s %s -of JPEG %s %s"
driver = ogr.GetDriverByName('ESRI Shapefile')
sh... | 5,306,364 |
def cast_other(f):
"""Generic wrapper to be applied to binary operator type class methods and
whose purpose is to cast the second positional argument to the type self"""
@wraps(f)
def wrapper(self, *args, **kwargs):
cls = self.__class__
other = args[0]
if not isinstance(other, c... | 5,306,365 |
def bet_wit_cv(b_d, w_d):
"""
引数:2つのディクショナリ
返値:double型のクラス間分散,クラス内分散の値のタプル
"""
bc_var = b_d['n'] * w_d['n'] * ((b_d['ave'] - w_d['ave']) ** 2) / ((b_d['n'] + w_d['n']) ** 2)
wc_var = (b_d['n'] * b_d['var'] + w_d['n'] * w_d['var'] ) / (b_d['n'] + w_d['n'])
return bc_var, wc_var | 5,306,366 |
def create_single_file_info(filen, piece_length):
"""
Return dictionary with the following keys:
- pieces: concatenated 20-byte-sha1-hashes
- name: basename of the file
- length: size of the file in bytes
- md5sum: md5sum of the file
@see: BitTorrent Metainfo Specification.
... | 5,306,367 |
def call(cmd, check=True, cwd=None):
"""Execute a command and return output and status code. If 'check' is True,
an exception will be raised if the command exists with an error code. If
'cwd' is set, the command will execute in that directory."""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd... | 5,306,368 |
def suite():
"""Create test suite from TrickWorkflowTestCase unit test class and return"""
return unittest.TestLoader().loadTestsFromTestCase(TrickWorkflowTestCase) | 5,306,369 |
def only_if_element(func):
"""
Decorator which raises if element is None in class State.
Args:
func (callable): The function to be wrapped
Returns:
wrapper (callable): The decorated function
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if self.state.element... | 5,306,370 |
def _get_dataset_sizes(sdtype):
"""Get a list of (fit_size, transform_size) for each dataset generator.
Based on the sdtype of the dataset generator, return the list of
sizes to run performance tests on. Each element in this list is a tuple
of (fit_size, transform_size).
Args:
sdtype (str)... | 5,306,371 |
def HNF_shapes(enum,lattice,show,testmode=False):
"""Plots the shape of each HNF.
Args:
enum (str): The enum.in style input file.
lattice (str): The lattice.in style input file.
show (bool): If true each HNF is plotted in an interactive window.\
testmode (bool, optional): True i... | 5,306,372 |
def get_glide_score(pdb, label_df):
"""
searches for pdb's rmsd in combined rmsd df
:param pdb: (string) {target}_lig{id}
:param label_df: (df) combined rmsd df
:return: (float) rmsd value
"""
return label_df[label_df['target'] == pdb]['glide_score'].iloc[0] | 5,306,373 |
def _test_against_patterns(patterns, entity_id):
"""Test entity against list of patterns, true if any match."""
for pattern in patterns:
if pattern.match(entity_id):
return True
return False | 5,306,374 |
def emulators_get(username=None, label=None, page=None, per_page=None): # noqa: E501
"""List all instances of Emulator
Gets a list of all instances of Emulator (more information in https://w3id.org/okn/o/sdm#Emulator) # noqa: E501
:param username: Name of the user graph to query
:type username: str
... | 5,306,375 |
def get_schema_variables(schema):
"""
This method returns a set of all variables within the schemas.yml. The set is organised by:
(variable_name, locator_method, script, file_name:sheet_name)
If the variable is from an input database, the script is replaced by "-"
Also, if the variable is not from a... | 5,306,376 |
async def async_zmq_receive_data(
reader: zmq.asyncio.Socket,
) -> Optional[Tuple[PeerIdentity, Any]]:
"""Receive data from the reader.
The data is expected to be bytes-encoded JSON representation of a Python object.
Received data is deserialized to a Python object and returned.
:returns: optional... | 5,306,377 |
def read(filename, **kwargs):
"""Load GDF2 data package.
Arguments:
dfn_filename (str)
method (str): how to read the data file. Either assume it is
delimited by whitespace (``'whitespace'``) or use the
field widths specified in the .dfn file (``'fixed-widths'``)
... | 5,306,378 |
def key_id_or_name_as_string_n(index):
"""Pull out the nth (0-based) key id or name from a key which has parents.
If a key is present, return its id or name as a string.
Note that this loses the distinction between integer IDs and strings
which happen to look like integers. Use key_type to distinguish them.
... | 5,306,379 |
def polarToCartesian(polar, radius = 1.0):
"""
Convert a 2D spherical coordinate into a cartesian 3D coordinate.
Polar coordinates are expected to be in radians.
Polar coordinate can be of form (theta, phi), in which case the radius
parameter is used.
Polar coordinate can also be of form (r, the... | 5,306,380 |
def find_root_visual(conn):
"""Find the xcffib.xproto.VISUALTYPE corresponding to the root visual"""
default_screen = conn.setup.roots[conn.pref_screen]
for i in default_screen.allowed_depths:
for v in i.visuals:
if v.visual_id == default_screen.root_visual:
return v | 5,306,381 |
def get_db_connection():
"""Get a connection to the DB. We do this per query to ensure we always
have a live connection."""
conn = mysql.connector.connect(user=DB_UNAME, password=DB_PW,
host=DB_SERVER, database=DB_DATABASE,
autocommit=True)
... | 5,306,382 |
def location_create_mapper(c: ZIAConnector, args):
"""
Creates a new location.
Args:
c: API zia_client that must me logged in beforehand.
args: Parsed api_parser. Namespace object.
Returns:
The requests' response. Generally a JSON object.
"""
with open(args.file) a... | 5,306,383 |
def compute_forward_cost(image, energy):
"""Computes forward cost map (vertical) and paths of the seams.
Starting from the first row, compute the cost of each pixel as the sum of energy along the
lowest energy path from the top.
Make sure to add the forward cost introduced when we remove the pixel of t... | 5,306,384 |
def delete_note(note_id: str) -> tuple[dict, int]:
"""Delete an existing note.
The user can call this operation only for their own notebooks' notes.
This operation requires the following header with an access token:
"Authorization: Bearer access_token"
Request parameters:
- note_id (st... | 5,306,385 |
def test_string_yyyymmdd_with_dots():
"""Test that yyyy.mm.dd pattern is accepted."""
assert CastToDate()(
'2019.09.07',
'yyyy.mm.dd',
).unwrap() == target_after_2000 | 5,306,386 |
def creole_slugify(value):
"""Convert the given string to a slug consistent with heading IDs used
by our creole parser.
>>> creole_slugify("Only 20%!")
"only-20"
"""
if not value:
return value
# Only keep alphanumeric and space characters.
value = re.sub(r"[^a-zA-Z0-9 ]+", "",... | 5,306,387 |
def change_pitch(samples, rate):
"""
Change the pitch of a samples array, returning a new samples array with the pitch changed.
"""
LIMIT = (1 << 15) - 1
index = 0
finished = []
while index < len(samples) - math.ceil(rate):
i = int(index);
frac = index - i;
s1 = samp... | 5,306,388 |
def test_create_batch_change_without_comments_succeeds(shared_zone_test_context):
"""
Test successfully creating a batch change without comments
Test successfully creating a batch using inputName without a trailing dot, and that the
returned inputName is dotted
"""
client = shared_zone_test_cont... | 5,306,389 |
def test_null_imsi_threshold_exceeded(operator_data_importer, logger, db_conn):
"""Test Depot ID not known yet.
Verify that the operator data file is not imported if the number of
data has with blank IMSI is greater than null_imsi_threshold.
"""
# _data_length = 6
# failing_null_check = 2
#... | 5,306,390 |
def crypto_scalarmult_base(n):
"""
Computes and returns the scalar product of a standard group element and an
integer ``n``.
:param n: bytes
:rtype: bytes
"""
q = lib.ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
if lib.crypto_scalarmult_base(q, n) != 0:
raise CryptoError... | 5,306,391 |
def verify_ospf3_interface(device,
expected_interface=None,
expected_interface_type=None,
expected_state=None,
extensive=True,
max_time=60,
check_interval=10,... | 5,306,392 |
def trainCount(
trainData,
questionType,
questionDict,
questionIdict,
objDict,
objIdict,
numAns):
"""
Calculates count(w, a), count(a)
"""
count_wa = np.zeros((len(objIdict), numAns))
c... | 5,306,393 |
def make_true_detections(*, tilename, bands, output_meds_dir, box_size):
"""Make fake "true detection" catalogs as if source extractor had been
run.
Note this function also writes "fake" coadd image data so that
MEDS files can be made.
Parameters
----------
tilename : str
The DES c... | 5,306,394 |
def get_corr_account_full_name(split):
"""
Iterate through the parent splits and return all of the accounts that have a value in the opposite sign of the value
in split.
:param split:
:return:
"""
return_value = []
signed = split.value.is_signed()
for child_split in split.transacti... | 5,306,395 |
def data_block(block_str):
""" find all thermo data
"""
thm_dstr_lst = data_strings(block_str)
thm_dat_lst = tuple(zip(
map(species_name, thm_dstr_lst),
map(temperatures, thm_dstr_lst),
map(low_coefficients, thm_dstr_lst),
map(high_coefficients, thm_dstr_lst)))
return... | 5,306,396 |
def is_match(a,b):
"""Evaluates if a or elements of a are a regex match to the pattern in b."""
if is_array(a):
return all(is_match(a=elem,b=b) for elem in a)
else:
try:
result = bool(re.search(b,a))
except ValueError as e:
print(e)
else:
i... | 5,306,397 |
def remove_class(class_name_gen):
"""
Removes a class on a HTML element
**Important**: this works with the assumption that the element is processed with 'html.parser' or something
similar, that is the 'class' attribute is a list of classes. If processing with the 'html' parser the 'class'
attribute... | 5,306,398 |
def separate_sheaths(
image_in,
dataslices=None,
h5path_lmm='',
h5path_wsmask='',
h5path_mds='',
h5path_mmm='',
MAdilation=[1, 7, 7],
h5path_dist='',
sigmoidweighting=0,
margin=50,
medwidth_file='',
outputpath='',
sa... | 5,306,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.