content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def calculate_multiple_choice_task_metrics(pred_dict, labels_dict):
"""Calculate accuracy for multiple choice tasks.
Args:
pred_dict: mapping subinstance ids to prediction, where subinstance id is like "0_0", which stands for the 0-th
option for the 0-th instance
labels_dict: mappin... | b4be8a3f66e06978a50cc1fdef6659a94a7fe394 | 682,375 |
import argparse
def str2bool(v):
"""Boolean type for argparse"""
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.') | 1e5212fd367cea364ffe94aa706962143d2097d6 | 682,376 |
def SelectDefaultBrowser(possible_browsers):
"""Return the newest possible browser."""
if not possible_browsers:
return None
return max(possible_browsers, key=lambda b: b.last_modification_time) | 969aa1e14892a35eef4f7bccad2799407a9fd97e | 682,377 |
def mw_to_gwh(megawatt, number_of_hours):
""""Conversion of MW to GWh
Arguments
---------
kwh : float
Kilowatthours
number_of_hours : float
Number of hours
Return
------
gwh : float
Gigawatthours
"""
# Convert MW to MWh
megawatt_hour = megawatt * nu... | 1565d7992c11c35113ddbf4c425aa53aa06ba166 | 682,378 |
def triangle(n: int) -> int:
"""
fastest method
"""
return sum([x for x in range(1, n + 1)]) | 54c3b92f7e16bcc207d3bf2812384f0cfb0e7049 | 682,380 |
from typing import OrderedDict
def get_counts(arrays, cart_prods, cn=2):
"""
function to count every possible combination
of WT and His47Arg copies in a population of K3L arrays
"""
all_combos = OrderedDict()
for combo in cart_prods:
count = sum([1 if combo == ''.join([str(x) for x in ... | a9cb57ac8e4f98105209da9267c8d78183744441 | 682,381 |
def dict_slice(dict_input, start, end) -> dict:
"""
take slice for python dict
:param dict_input: a dict for slicing
:param start: start position for splicing
:param end: end position for slicing
:return: the sliced dict
"""
keys = dict_input.keys()
dict_slice = {}
for k in keys[... | ec4bb4970074b11de21c686afd1ac9bd28460430 | 682,384 |
def getInterfaceRecord(networkRecords, mac):
"""
Get the interface record of xen by it's mac.
Arguments:
interfaces -- Interfaces on xen server.
mac -- Mac of the interface.
Returns:
network object on success else None.
"""
interfaces = [rec for rec in networkRecords if... | af7e31289b902bcc41028183af7185ffcc1000f4 | 682,386 |
import time
from datetime import datetime
def _time_str_to_unix(timestring):
"""
:type timestring: Union[str, int]
:rtype: Union[int, None]
"""
if isinstance(timestring, (int, float)):
return timestring
try:
t = int(time.mktime(datetime.strptime(timestring, '%a, %d %b %Y %H:%M:... | 3dfa5dd585b0a7918e6d82d28ed2bcc807c4f48e | 682,388 |
def extract_barcode(read, plen):
"""
Extract barcode from Seq and Phred quality.
:param read: A SeqIO object.
:type read: object
:param plen: The length of the barcode.
:type plen: num
:returns: A SeqIO object with barcode removed and a barcode string.
"""
barcode = str(read.seq[:pl... | d6087a32c2c49a71338a32e4f69a7cf064b33894 | 682,390 |
import warnings
def _parse_GRD_RPC_vect(str_coeffs):
"""
The GRD RPC is packed in string lists of 20 elements. Unravel them.
"""
coeffs = str_coeffs.split(" ")
if len(coeffs) != 20:
warnings.warn(
"Expected there to be 20 rational polyonomial cubic coefficients in the metadat... | 060316e78ea9a8040928b00432f5a3c901ba76a0 | 682,391 |
def parseIO(iostat):
"""
Parses the iostat in an array if info
:param iostat
:return: array of dict
"""
data = []
for disk, stat in iostat.items():
data.append({
disk: {
"read_count": stat.read_count,
"write_count": stat.write_count,
... | 02c89a4db702c29b4238865aa84c5e42f691ed87 | 682,392 |
def get_blob(blob_name): # noqa: E501
"""Serves a blob
# noqa: E501
:param blob_name: name of a blob to serve
:type blob_name: str
:rtype: str
"""
return 'do some magic!' | 4e822f9400cea4170e415d24e29e9c330815c336 | 682,393 |
import sys
def main(argv=None):
"""Drive the validator."""
argv = argv if argv else sys.argv[1:]
if not argv:
print("ERROR arguments expected.", file=sys.stderr)
return 2 | 5b6a664b7430b32fdcb583dd6e1b311ddb58d1cd | 682,394 |
import os
import json
def check_file_for_train(param_path, file) -> bool:
"""
Check if the training task corresponding to this file has been completed.
Parameters
----------
param_path : ``str``
Where to check training_progress.json.
file : ``str``
File name to check
"""
... | d2e39ca694927d8371725638ccb11e0808e8c243 | 682,395 |
def getGroupInputDataLength(hg):
""" Return the length of a HDF5 group
Parameters
----------
hg : `h5py.Group` or `h5py.File`
The input data group
Returns
-------
length : `int`
The length of the data
Notes
-----
For a multi-D array this return the length of th... | f049faff66573b9dfeec304f33143ca915a692c6 | 682,397 |
def user_editor(context, request, leftcol_width=4, rightcol_width=8):
""" User editor panel.
Usage example (in Chameleon template): ${panel('user_editor')}
"""
return dict(leftcol_width=leftcol_width, rightcol_width=rightcol_width) | 1a94367d8510d89a2ac41a1fc2d96ed6b73aff0e | 682,398 |
from typing import Dict
import re
def get_current_zones(filename: str) -> Dict[str, str]:
"""Get dictionary of current zones and patterns"""
res = {}
try:
for line in open(filename).readlines():
if line.startswith("#"):
continue
if match := re.match(r"^add (... | 5b87653ac19c76e023bf33eb0c81fa2c3b92009c | 682,399 |
def maybe_remove_new_line(code):
"""
Remove new line if code snippet is a
Python code snippet
"""
lines = code.split("\n")
if lines[0] in ["py", "python"]:
# add new line before last line being ```
lines = lines[:-2] + lines[-1:]
return "\n".join(lines) | 7dda971f628c2451ef16283e9c87e3be01fde91d | 682,402 |
def LinearSearch(arr, item):
""" If item is in array, Returns the index of first occurence of the item in the array; Else Returns False.
Searches for an item using 'Linear Search' algorithm.
Time Complexity :-
Best Case : Ω(1)
Worst Case : O(N)
Avg Case : Θ(N/2)
... | 58806bd94500fa20249c2fa8f1f08de66467b3e1 | 682,403 |
import numpy
def NormalisedFft(values, divisions = None, returnPhases = False):
"""
Perform a normalised fast Fourier transform of the supplied values.
More efficient if divisions is a power of 2
"""
if divisions is None:
divisions = len(values)
fft = numpy.fft.rfft(values, n = divisions) / di... | c018036fc3c99919599dfcf71ea5668a5994b84b | 682,404 |
from typing import Union
import os
import sys
def check_if_file_exists(file: str) -> Union[str, None]:
"""Check if a file exists.
If the file does not exist, the execution will halt.
Keyword arguments
-----------------
file : str
the file path
Returns
-------
the ... | 4667e09116be687de1b46853dd621cbe13d74419 | 682,405 |
def std_ver_minor_uninst_valueerr_iativer(request):
"""Return a string that looks like it could be a valid IATIver minor version number, but is not."""
return request.param | 5d902381b22d03a52c2cbee6d13b178beda9c97a | 682,406 |
from typing import Union
import inspect
from pathlib import Path
def get_appropriate_stacktrace() -> list[dict[str, Union[str, int, dict[str, str]]]]:
"""Return information of all frames related to cmyui_pkg and below."""
stack = inspect.stack()[1:]
for idx, frame in enumerate(stack):
if frame.fun... | 92ae8ed2e90899150ba1e2d33f9ff6ea92364c0e | 682,408 |
import base64
def img_to_base64(img_path):
"""
img 转 base64
:param img_path:
:return:
"""
with open(img_path, "rb") as imageFile:
img_str = base64.b64encode(imageFile.read())
return img_str.decode('utf-8') | 6506e625d09775cfec604b15d66ccda9245d033b | 682,409 |
def AbortScript():
"""
Example:
while True:
try:
print 'do something'
sleep(5)
except KeyboardInterrupt:
if AbortScript() == 'y':
break
"""
try:
print('\n\nWARNING: Do you want to abor... | 411650b282cbd8214c875367584c55df0f31f23b | 682,410 |
def sec_url(period):
""" Create url link to SEC Financial Statement Data Set """
url = "".join([
"https://www.sec.gov/files/dera/data/financial-statement-data-sets/",
period,
".zip"
])
# handle weird path exception of SEC
if period == "2020q1":
url = "".join([
... | 8d38a8dca62a7fd23a04130bd37aed1ed9ae34a0 | 682,411 |
def power_provision_rule(mod, prj, tmp):
"""
Power provision is a load, so a negative number is returned here whenever fuel is
being produced.
"""
return -mod.Fuel_Prod_Consume_Power_PowerUnit[prj, tmp] | be46cb494adc3069e27f1e6da593f822a06e6489 | 682,412 |
def get_job_type(x):
""" returns the int value for the nominal value survived
:param x: a value that is either 'yes' or 'no'
:return: returns 1 if x is yes, or 0 if x is no
"""
if x == 'Government':
return 1
elif x == 'Private':
return 2
elif x == 'Self-employed':
re... | e98876932844c472127dd6c45e2d262384422398 | 682,414 |
def kmp_prefix(inp, bound=None):
"""Return the KMP prefix table for a provided string."""
# If no bound was provided, default to length of the input minus 1
if not bound:
bound = len(inp) - 1
table = [0] * (bound+1) # Initialize a table of length bound + 1
ref = 0 # Start referencing at th... | 435588bcabc3ee97523cfbd863b21d71e4feea94 | 682,416 |
def compute_sub(guard_str):
"""
Given a guard, return its sub-guards
"""
parens = []
sub = []
for i in range(len(guard_str)):
if guard_str[i] == '(':
parens.append(i)
if guard_str[i] == ')':
j = parens.pop()
g = guard_str[j:i + 1].strip... | 42e75bd56c0a1cf9a6c8ff8bb92978e423df2314 | 682,417 |
def clean_string(s):
"""
Get a string into a canonical form - no whitespace at either end,
no newlines, no double-spaces.
"""
return s.strip().replace("\n", " ").replace(" ", " ") | d0de7c4d7d398152d23a03f90e86c592e2a4e6ea | 682,418 |
def large_clique_size(G):
"""Find the size of a large clique in a graph.
A *clique* is a subset of nodes in which each pair of nodes is
adjacent. This function is a heuristic for finding the size of a
large clique in the graph.
Parameters
----------
G : NetworkX graph
Returns
----... | 052eb22552e5f6842c98c1bd78ac78fdfac406aa | 682,419 |
import os
def codegen_type(filepath):
"""
param1: string : path of file to generate with either .py or .ipynb extension.
return: string
The function identifies which type of file to generate and return type.
"""
if(filepath=="" or None):
ftype='py'
else:
extension = os.pat... | 1b2e4bd48eb75fed983dc4539c58a68bb239bc63 | 682,420 |
import math
def precision_digits(f, width):
"""Return number of digits after decimal point to print f in width chars.
Examples
--------
>>> precision_digits(-0.12345678, 5)
2
>>> precision_digits(1.23456789, 5)
3
>>> precision_digits(12.3456789, 5)
2
>>> precision_digits(12345... | 473fa791e1d9dc07486250b2b9072c264aa365bc | 682,421 |
def nativeQSnapX(self):
"""
TOWRITE
:rtype: qreal
"""
scene = self.activeScene() # QGraphicsScene*
if scene:
return scene.property("SCENE_QSNAP_POINT").x() # .toPointF().x()
return 0.0 | 25b93f0db1b0ac51100e01b2db4015a61cf01bdc | 682,422 |
def sorted_nodes_by_name(nodes):
"""Sorts a list of Nodes by their name."""
return sorted(nodes, key=lambda node: node.name) | b73aef773b59204af5ee00f1dc95aab8b5d0b3ca | 682,423 |
def __fibonacci_recursivo(terminos: int, secuencia: list) -> list:
"""Calcula recursivamente la secuencia de Fibonacci"""
if not terminos:
return secuencia
if len(secuencia) == 0:
secuencia.append(0)
elif len(secuencia) == 1:
secuencia.append(1)
else:
secuencia.appen... | 50e9fc9bb75e697db51bc96a31b49cf488cff615 | 682,424 |
from sys import settrace
def count_calls(func, *args, **kwargs):
"""Count calls in function func"""
calls = [-1]
def tracer(frame, event, arg):
if event == "call":
calls[0] += 1
return tracer
settrace(tracer)
rv = func(*args, **kwargs)
return calls[0], rv | 3949e4d764b68dc0396c196b36039c9e906e5b92 | 682,425 |
def ai(vp,rho):
"""
Computes de acoustic impedance
Parameters
----------
vp : array
P-velocity.
rho : array
Density.
Returns
-------
ai : array
Acoustic impedance.
"""
ai = vp*rho
return (ai) | 4879c0095d64ad04911b264524e6a95c277c128a | 682,426 |
import argparse
import os
def parse_args():
"""Parse cli arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("image", help="Name of the image to create.")
parser.add_argument("container", help="Name of the container to create.")
parser.add_argument("dockerfile", help="Path to t... | 921c72f6d758f1ad29c8083b471e4ed67ebc8f26 | 682,428 |
def rainbow(n, s = 1, v = 1, start = 1, rval='cols'):
"""Return n rainbow colors
"""
rscript = ''
if not n: return rscript
rscript += '%s <- rainbow(%d,' %(rval, n)
if s != 1:
rscript += 's=%s,' %str(s)
if v != 1:
rscript += 'v=%s,' %str(v)
if start != 1:
rsc... | 65af500904a304b90910ef61dbc2146500700b86 | 682,429 |
def get_bool(bytearray_: bytearray, byte_index: int, bool_index: int) -> bool:
"""Get the boolean value from location in bytearray
Args:
bytearray_: buffer data.
byte_index: byte index to read from.
bool_index: bit index to read from.
Returns:
True if the bit is 1, else 0.
... | 34d7a032b90ffaa7eb85e88bd8a57ec5db54a22b | 682,430 |
def cam_com(exp, wellu, wellv, fieldx, fieldy, dxcoord, dycoord):
"""Add a field to the cam list.
Return a list with parts for the cam command.
"""
# pylint: disable=too-many-arguments
wellx = str(wellu + 1)
welly = str(wellv + 1)
fieldx = str(fieldx + 1)
fieldy = str(fieldy + 1)
r... | 0dc76afcc0f017755fce9a6b4a4409e6ea4c5212 | 682,432 |
from typing import Callable
def evaluate(population: list, evaluation_fn: Callable) -> list:
"""Evaluates the given population using the given evaluation function.
Params:
- population (list<str>): The population of chromosomes to evaluate
- evaluation_fn (Callable): The evaluation function to use
... | a839524618b6871008da4f8c844b2fe123cadffa | 682,433 |
import os
def CreateCommandsList(params):
"""
Create list of commands to execute
@param params: Parameters.
@type params: ScriptData.
@return: List of commands.
@rtype list of strings.
"""
property_name = 'wrap.' + params.app
# If the property name length exceeds ... | 6eec444faefc088d55188aec1aebebf7617d784f | 682,434 |
def parse_cookies(cookies):
"""Parse cookies.
Parse cookies, and return dictionary with cookie name as key and all details as value."""
# import Cookie
parsed_cookies = {}
# print cookies
cookie_string = str(cookies)
cookie_list = cookie_string.split(';')
# cookie_list =... | cd8fd9ae08acbe8a316b5ee0d38f2a845871da0c | 682,435 |
def run_add_metadata(
input_path: str,
output_path: str,
meta: str
) -> str:
"""
Parameters
----------
input_path
output_path
meta
Returns
-------
"""
cmd = 'biom add-metadata \\\n'
cmd += ' -i %s \\\n' % input_path
cmd += ' -o %s \\\n' % outp... | 826c717420254b795d6b929d9757a9c0fe872cb5 | 682,437 |
def correct_node_position(order, positions, new_position_j):
"""
Some order 0, 4, 2, 3, 1
and q ∈ [0, ..., len(order)-1], say 1
q = 1
i = 4
pos_i = 5 - 1 - 4 = 0
j = 0
order[1] = 0, order[0] = 4
pos[0] = 1, pos[4] = 0
return 4, 0, 2, 3, 1
"""
i = order[new_positi... | 028634fc91370bba2aea82024f5412466b18a7e0 | 682,438 |
def convert_bytes(size):
"""
将大小转换成 KB MB GB TB 展示
:param size:
:return:
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
return f"{size} {x}" if x == 'bytes' else f"{size:.2f} {x}"
size /= 1024.0
return size | 7f1473fe3d8fd3efa7a1bb074c1d57ddadc22187 | 682,439 |
import copy
def merge_to_panoptic(detection_dicts, sem_seg_dicts):
"""
Create dataset dicts for panoptic segmentation, by
merging two dicts using "file_name" field to match their entries.
Args:
detection_dicts (list[dict]): lists of dicts for object detection or instance segmentation.
... | e28916b97bf1955f06a6e24208dd6d47422e23c4 | 682,440 |
def distance_hue(h1: float, h2: float) -> float:
"""HUE based distance
distance > 0 -> "clockwise"
distance < 0 -> "counter-clocwise"
"""
dist = h2 - h1
if abs(dist) > .5:
dist = (-1 if dist > 0 else 1) * (1 - abs(dist))
return dist | 4a2155afad5a42549e37b3993ea54e901997dddf | 682,441 |
def numpy_inner_product_dist(q1, q2):
"""Quaternion distance based on innerproduct.
See comparisons at: https://link.springer.com/content/pdf/10.1007%2Fs10851-009-0161-2.pdf"""
return 1.0 - abs(q1[0]*q2[0] + q1[1]*q2[1] + q1[2]*q2[2] + q1[3]*q2[3]) | 7d651f535be4e18355d8ddf22aa8c0c7933f057c | 682,442 |
def encode_string_to_url(str):
""" takes as string (like a name) and replaces the spaces for underscores to make a string for a url
:param str: string
:return: encoded string with underscores for spaces
>>> encode_string_to_url('hello')
'hello'
>>> encode_string_to_url('hello world')
'hello_... | 1683b08f312988713f20f3b25c27b650420a1bdc | 682,443 |
def intersection_pt(L1, L2):
"""Returns intersection point coordinates given two lines.
"""
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx / D
y = Dy / D
return x, y
else:
return False | 1ded12cf1e876b468cea6960f8069a48c76ea9ff | 682,444 |
import torch
def colormask_to_torch_mask(colormask: torch.Tensor) -> torch.Tensor:
"""
:param colormask: [C=1, X, Y, Z]
:return:
"""
uni = torch.unique(colormask)
uni = uni[uni != 0]
num_cells = len(uni)
c, x, y, z = colormask.shape
shape = (num_cells, x, y, z)
mask = torch.... | 1a641593e52133ea9763470b59cfde44e335ee11 | 682,445 |
def has_cli_method(script_path):
"""
Check if a script has a cli() method in order to add it to the main
:param script_path: to a python script inside Cider packages
:return: Boolean
"""
file_obj = open(script_path, 'r').read()
return "cli()" in file_obj | 9afb9a7db73a671dc21c2bc3a23a2b3d6d414ecb | 682,446 |
def lobid_qs(row, q_field='surname', add_fields=[], base_url="https://lobid.org/gnd/search?q="):
""" creates a lobid query string from the passed in fields"""
search_url = base_url+row[q_field]+"&filter=type:Person"
if add_fields:
filters = []
for x in add_fields:
if x:
... | 0a69bea98eb2a67b28fd78206ec6f79b1a14719e | 682,447 |
def jaccard(ground, found):
"""Cardinality of set intersection / cardinality of set union."""
ground = set(ground)
return len(ground.intersection(found))/float(len(ground.union(found))) | 6e3068fd6f2d2d8aec8aede7d7f7c1dd8ad4fcdf | 682,448 |
import os
def get_data(input_path, folder_path='../detection_images'):
"""Parse the data from annotation file
Args:
input_path: annotation file path
folder_path: path to place before filepaths in annotation file
"""
all_imgs = {}
classes_count = {}
file = open(input_path, 'r... | b8bd2d1140fe43310f52293e268bd8f63a42b19d | 682,449 |
def FileNameTuple(FileHeaderTuple, InitialIndexTuple, FinalIndexTuple, Extension = ""):
"""
FileNameTuple : this function returns a tuple of files that should be evaluated
Taken as parameters are tuple of file name headers,
starting indices and ending indices
"""
# Verify that all t... | fc5fbef78a2dcdb2591c7dd5a32a3b904e7851c6 | 682,452 |
from typing import Dict
import logging
def collect_content_packs_to_install(id_set: Dict, integration_ids: set, playbook_names: set, script_names: set) -> set:
"""Iterates all content entities in the ID set and extract the pack names for the modified ones.
Args:
id_set (Dict): Structure which holds a... | d31901a0d44aa676389f8f1fe313066993e988a7 | 682,453 |
import argparse
def IsSuppressed(arg):
"""Returns True if arg is suppressed."""
return arg.help == argparse.SUPPRESS | 97a6ba2387bc2eebae2a11b5c788c1e858369078 | 682,454 |
def maximum_severity(*alarms):
"""
Get the alarm with maximum severity (or first if items have equal severity)
Args:
*alarms (Tuple[AlarmSeverity, AlarmStatus]): alarms to choose from
Returns:
(Optional[Tuple[AlarmSeverity, AlarmStatus]]) alarm with maximum severity; none for no argumen... | d78a221b56e891103e8387d077d8f14dd2d1ce93 | 682,455 |
def extractRoi(frame, pos, dia):
"""
Extracts a region of interest with size dia x dia in the provided frame, at the specied position
Input:
frame: Numpy array containing the frame
pos: 2D position of center of ROI
dia: Integer used as width and height of the ROI
Ou... | 0c66811c9f564477e0075a52deaa5d242ffcba22 | 682,457 |
import secrets
import click
def generate_secret_key(num_bytes, show=True):
"""Generate and print a random string of SIZE bytes."""
rnd = secrets.token_urlsafe(num_bytes)
if show:
click.secho(rnd)
return rnd | 917d7a4e9be93b7c8266f53f07f3f3e1cec43865 | 682,458 |
def read_fasta(fname):
"""
Read a fasta file and return a hash.
:param fname: The file name to read
:return: dict
"""
seqs = {}
seq = ""
seqid = ""
with open(fname, 'r') as f:
for line in f:
line = line.strip()
if line.startswith(">"):
... | b16755d7d515c506af46b9ab7328895573cecb7c | 682,461 |
import os
def file_exists(path):
"""
Return :data:`True` if `path` exists. This is a wrapper function over
:func:`os.path.exists`, since its implementation module varies across
Python versions.
"""
return os.path.exists(path) | 58aa51297a247889d8847cbf93b3681277a727df | 682,462 |
def _lookup_format(var):
"""
Looks up relevant format in fits.
Parameters
----------
var : object
An object to look up in the table
Returns
-------
lookup : str
The str describing the type of ``var``
"""
lookup = {"<type 'int'>": "J", "<type 'float'>": "E",
... | b23ac4ba4fbeb0909e144b7daa7a3eecf5738093 | 682,463 |
import argparse
def get_input_args():
"""
Retrieves and parses the 3 command line arguments provided by the user when
they run the program from a terminal window. This function uses Python's
argparse module to created and defined these 3 command line arguments. If
the user fails to provide some ... | 6e50bcb6407f17e49afe15c017466310d5eccc44 | 682,464 |
def batch2list(batch):
"""Converts a batch of patches into a list of batches.
Args:
restored_model: Restored TensorFlow segmentation model.
batch: np.array of shape
(min(remaining, group_size), patch_size, patch_size, num_channels).
Returns:
List of length batch.shape[0... | 674a25f4f79fad9a340fbb9532ab3a89b24d7c78 | 682,465 |
def get_spiral_coords(w, h):
"""
Determine the sequence of coordinates found by spiraling in on an image of
given size clockwise from the top-left corner to the centre.
"""
x, y = 0, 0
depth = 0
coords = []
while len(coords) < w * h:
# Check for the special case where we are 1 pi... | 21fb38120e74028f883f0f9e72c559e2fd566f15 | 682,466 |
def get_tech_installed(enduses, fuel_switches):
"""Read out all technologies which are specifically switched to
Parameter
---------
fuel_switches : dict
All fuel switches where a share of a fuel of an enduse is switched to a specific technology
Return
------
installed_tech : list
... | 849e2f91a74a0a319e5307848c391f63b584fb98 | 682,467 |
def compute_basin(i, j, grid):
"""
Basin starts from the low point and includes any point up, down, left,
right as long as that point is lower than the point next to it. 9 is
automatically not included.
From each point that is in the basin, we have to recursively compute
the basin to the up, d... | 6de71addf41ba1f5bc37c389aeff12e239cdd37e | 682,468 |
def breakdown2score_sum(working_score, score_breakdown, full=False):
"""Implements the combination scheme 'sum' by always returning
``working_score``.
Args:
working_score (float): Working combined score, which is the
weighted sum of the scores in
... | 6f291246e50ec52592aec1272bbefe8b9769e51b | 682,469 |
import sys
import os
def argv_name():
"""Returns the name of our program by examining argv.
"""
app_name = sys.argv[0][:-3] if sys.argv[0].endswith('.py') else sys.argv[0]
return os.path.split(app_name)[-1] | eadfb862b80a33ac8d2057b4dc3bd8a620bf1f61 | 682,470 |
import re
def handle_optionals(url_list):
"""Builds a set of urls given a list of 'pseudo-urls' with optional parts
returns a set of strings
WARNING: Currently correctly handles only 1 optional part per url
Example:
input: ['home/city(-bristol)?',
'home/city(-bath)?',
'h... | a9694464b5fc3fa56f148a736deca4c13de556c6 | 682,472 |
def get_max_step(sb, w):
"""
Функция-замыкание. Возвращает функцию устанавливающую максимальное значение виджета QSpinBox или QDoubleSpinBox.
Максимальное значение зависит от значения виджета, переданного в эту функцию.
:param sb: виджет от которого зависит максимальное значение
:param w: виджет к... | 61fe444abf9e9892760456720ff360b15899de49 | 682,473 |
from os import walk
import os
def include_dir_files(folder):
"""Find all C++ header files in folder"""
files = []
for (dirpath, _, filenames) in walk(folder):
for fn in filenames:
if os.path.splitext(fn)[1] in {'.h', '.hpp'}:
files.append(os.path.join(dirpath, fn))
... | a1276d82cb050c11b3842086b4ca896eafcfa5e1 | 682,474 |
def npy_cdouble_from_double_complex(var):
"""Cast a Cython double complex to a NumPy cdouble."""
res = "_complexstuff.npy_cdouble_from_double_complex({})".format(var)
return res | ee9a6c3803a2f572e3dfb5a3e7c822136e630d1e | 682,475 |
from pathlib import Path
import os
def get_project_path() -> Path:
"""Get the path to the project's root directory.
Returns
-------
project_path : Path
The path to the root directory of the project.
"""
file_dir = os.path.dirname(os.path.realpath(__file__))
dir_path = Path(file_di... | cb9b142e3c7d97e30983c2d3e5442c02df0c1e23 | 682,477 |
def other_params():
"""Для параметров функции set_other_params."""
class Result:
locale = 'ru_RU'
return Result | 83c0d57dd2a7f0f6203e47a91d41bd2e09140a8a | 682,479 |
def find_highest_degree(graph):
""" Find the highest degree in a graph """
degrees = graph.degree()
max_degree = 0
for node in degrees:
if degrees[node] > max_degree:
max_degree = degrees[node]
return max_degree | 8a311280e8ac61972fa9dcd05dab3ead98456720 | 682,480 |
def _parse_absorption(line, lines):
"""Parse Energy, Re sigma xx, Re sigma zz, absorp xx, absorp zz"""
split_line = line.split()
energy = float(split_line[0])
re_sigma_xx = float(split_line[1])
re_sigma_zz = float(split_line[2])
absorp_xx = float(split_line[3])
absorp_zz = float(split_line... | 9e4d936685334f3f4ed96d4254457039f4e2bed3 | 682,481 |
from typing import List
from typing import Optional
async def get_shipment() -> List[Optional[float]]:
""" Get all shipments """
return [] | b5de22a0070739ad65670957c3cc377313448af1 | 682,482 |
def determine_submethod(args):
"""
Determine the submethod.
"""
submethod = False
if "organism_code" in args:
submethod = "query"
elif "search_query" in args:
submethod = "search"
elif "analysis_domain_file" in args:
submethod = "analysis"
elif "convert_domain_fil... | 09af123e9a46f9f4af0d6db2da1dc80a69664232 | 682,483 |
from typing import Callable
import functools
from typing import Any
import warnings
def deprecated(func: Callable) -> Callable:
"""Decorator that can be used to mark functions as deprecated, emitting a warning
when the function is used.
Arguments:
func:
The function to be decorated.
... | 747df84c3b3b6e8bf8f24fa1e8244fd45d781d6f | 682,484 |
def printtable(table, moe=False):
"""Pretty print information on a Census table (such as produced by `censustable`).
Args:
table (OrderedDict): Table information from censustable.
moe (bool, optional): Display margins of error.
Returns:
None.
Examples::
censusdata.printtable(censusdata.censustable('acs5... | 346935c49c9b6e213914ed7f85cee05d01361c9a | 682,485 |
def _juniper_vrf_default_mapping(vrf_name: str) -> str:
"""
This function will convert Juniper global/default/master routing instance
=> master => default
:param vrf_name:
:return str: "default" if vrf_name = "master" else vrf_name
"""
if vrf_name == "master":
return "default"
... | 30028de90d0bb04824dda33f41ebca8bd2b17dba | 682,486 |
def unclean_wrap_text(text, width, render_font):
"""Wraps text based off of the font to render to, and the max width in pixels"""
wrapped_lines = []
i = 0
line_width = len(text)
while i < line_width:
while render_font.size(text[i:line_width])[0] > width:
line_width -= 1
... | 9df6768d32966d1999cf3083305fa75e4c26120f | 682,487 |
def nz(df, y=0):
""" Replaces NaN values with zeros (or given value) in a series.
Same as the nz() function of Pinescript """
return df.fillna(y) | 5d0b940b88d7c8dfb7109d5e1a2538784231db1c | 682,489 |
def placemark_name(lst):
"""Formats the placemark name to include its state if incomplete."""
if lst[1] == 'Complete':
return lst[0]
else:
return ': '.join(lst) | aeee6bbbf909b82f241c45fd3bbfe149d87c2dc1 | 682,490 |
def default(event, **kwargs):
"""A Hacktoolkit-flavored default event handler for Alexa webhook events
Returns a payload if applicable, or None
"""
intent = kwargs.get('intent')
ssml = """<speak>Sorry, I'm not sure how to process that.</speak>""",
payload = {
'version' : '1.0',
... | b722aba393bafae6c672a1836f12519d83bc9df1 | 682,491 |
def _find_terminator(iterator):
"""The terminator might have some additional newlines before it.
There is at least one application that sends additional newlines
before headers (the python setuptools package).
"""
for line in iterator:
if not line:
break
line = line.strip... | 77bcee7916b09eee1f70ee0de5d41422b3abd6ec | 682,493 |
import itertools
def set_scan_dims(tors_grids):
""" Determine the dimensions of the grid
"""
assert len(tors_grids) in (1, 2, 3, 4), 'Rotor must be 1-4 dimensions'
grid_points = ((i for i in range(len(grid)))
for grid in tors_grids)
grid_vals = ((x for x in grid)
... | 69677fe1104ae686621a3ae6aff4625fa0ec15e9 | 682,494 |
def calc_suffix(_str, n):
"""
Return an n charaters suffix of the argument string of the form
'...suffix'.
"""
if len(_str) <= n:
return _str
return '...' + _str[-(n - 3):] | 67ff72f0ed1f3f1f6a06c10089293c8a61e1cf75 | 682,495 |
import tarfile
import io
import os
import zipfile
def open_compressed(byte_stream, file_format, output_folder):
"""
Extract and save a stream of bytes of a compressed file from memory.
Parameters
----------
byte_stream : bytes
file_format : str
Compatible file formats: tarballs, zip fi... | 8550b6735b8af522aabd34da2b2e25ae8a9a537c | 682,496 |
from typing import List
def datum_is_sum(datum: int, preamble: List[int]) -> bool:
"""Iterate the preamble numbers and determine whether datum is a sum.
Args:
datum (int): a number that should be a sum of any two numbers
in preamble
preamble (List[int]): a list of preceeding n num... | e5024bb0adbada3ba07a949505db8a31c0170958 | 682,497 |
import numpy
def smoothing_window_length(resolution, t):
"""Compute the length of a smooting window of *resolution* time units.
:Arguments:
*resolution*
length in units of the time in which *t* us supplied
*t*
array of time points; if not equidistantly spaced, the
... | 1993d71286feb7f98bad4d5e7bfdaa7dbbaa99bf | 682,498 |
def filter_data(data, var_val_pairs):
"""
We use this to filter the data more easily than using pandas subsetting
Args:
data (df) is a dataframe
var_val pairs (dict) is a dictionary where the keys are variables and the value are values
"""
d = data.copy()
for k, v in var_val_pa... | 66e2dcd66ffa7221795ac598a767648fdfeefcf6 | 682,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.