content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def func1():
"""Generic short description."""
pass | 5,354,400 |
def test_write(size, iterations, exclude_formats, test_compress):
"""
Test writting for one file
Args:
size: size of the file to test (0: small, 1: mediumn, 2: big)
iterations: number of times to run the test
exclude_formats: formats to e... | 5,354,401 |
def get_game_server_group(game_server_group_arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGameServerGroupResult:
"""
The AWS::GameLift::GameServerGroup resource creates an Amazon GameLift (GameLift) GameServerGroup.
:param str game_server_... | 5,354,402 |
def create_wcscorr(descrip=False, numrows=1, padding=0):
""" Return the basic definitions for a WCSCORR table.
The dtype definitions for the string columns are set to the maximum allowed so
that all new elements will have the same max size which will be automatically
truncated to this limit upon updati... | 5,354,403 |
def get_token():
""" Acquire an OAuth token for Koha
returns: OAuth token (string) """
data = {
"client_id": config['client_id'],
"client_secret": config['client_secret'],
"grant_type": "client_credentials",
}
response = requests.post(config['api_root'] + '/oauth/token',
... | 5,354,404 |
def build_step(incr: bool, cfg: RunConfig, repo: Repo, time_dict: dict) -> List[str]:
"""
Build jar for multiple versions of a repo
:param incr: incremental build or not
:param cfg: all configurations read from *.toml
:param repo: a GitPython git.Repo object
:param time_dict: recording running t... | 5,354,405 |
def fetch_hs_races(race_store):
"""
:param race_store: a store of races we currently have
:return: void
"""
parser = GopherStateHSRaceInfoParser()
content = get_gopher_state_content(HS_RACE_INFO_PAGE)
if not content:
print("Warning: skipping fetch for all gopher state highschool eve... | 5,354,406 |
def isfile(value):
"""Validate that the value is an existing file."""
return vol.IsFile('not a file')(value) | 5,354,407 |
def is_in_form(dg: "streamlit.delta_generator.DeltaGenerator") -> bool:
"""True if the DeltaGenerator is inside an st.form block."""
return current_form_id(dg) != "" | 5,354,408 |
def convert_rating() -> None:
""" Creates a file with ratings of type for each user and item from the user-item matrix. """
logger.info('Reading user-item matrix.')
# Load user-item matrix
user_item_matrix = get_user_item_matrix()
user_item_matrix_np = user_item_matrix.to_numpy()
item_set = se... | 5,354,409 |
def fetch(opts):
"""
support fetching from scp sources
With provided fetch options (``RelengFetchOptions``), the fetch stage will
be processed.
Args:
opts: fetch options
Returns:
``True`` if the fetch stage is completed; ``False`` otherwise
"""
assert opts
cache_f... | 5,354,410 |
def install_from_deb(deb_path,additional_options):
"""
Installs package with dpkg command using -i options and some extra options, if needed
Raises an exception on non-zero exit code
Input: apt file path, additional optons
Output: Combined stdout and stderror
"""
return run_shell_command("dp... | 5,354,411 |
def associate_phone_number_with_user(AccountId=None, UserId=None, E164PhoneNumber=None):
"""
Associates a phone number with the specified Amazon Chime user.
See also: AWS API Documentation
Exceptions
:example: response = client.associate_phone_number_with_user(
AccountId='string',
... | 5,354,412 |
def sign_award(award: Award) -> FlexSendMessage:
"""Sign Award Result
Args:
award (Award): Award Object
Returns:
FlexSendMessage: Flex Message
"""
tz = pytz.timezone("Asia/Taipei")
now = datetime.now(tz=tz)
now_text = now.strftime("%Y/%m/%d %H:%M:%S")
with open("line/f... | 5,354,413 |
def create_l5_block(block_id: str) -> l5_block_model.L5BlockModel:
"""
Creates unfinalized L5 block that needs confirmation
"""
l5_block = l5_block_model.L5BlockModel(
dc_id=keys.get_public_id(),
current_ddss=party.get_address_ddss(ADDRESS), # Get DDSS from party, cached hourly
... | 5,354,414 |
def gridgen(xbry: List, ybry: List, beta: List, shape: Tuple,
ul_idx=0, focus=None, proj=None, nnodes=14,
precision=1.0e-12, nppe=3, newton=True, thin=True,
checksimplepoly=True, verbose=False):
"""
External wrapping function to call Gridgen grid builder.
xbry, ybry - nod... | 5,354,415 |
def get_output():
"""Gets the current global output stream"""
global OUTPUT
return OUTPUT | 5,354,416 |
def load_pascal_annotation(index, pascal_root):
"""
This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083).
Thanks Ross!
"""
cl... | 5,354,417 |
def run_pca(
X_train,
y_train,
mean_widget,
std_widget,
x_widget,
labels_map=labels_map,
labels_inv_map=labels_inv_map,
):
"""Runs PCA on the passed data based on the defined parameters and returns a
pandas Dataframe. Consider the PCA is always fitted on the whole dataset X_train
... | 5,354,418 |
def record_nonempty(
entries: MutableMapping,
entry_lines: Sequence[str],
moment: TimeSwitcher
):
"""
insert timestamped sequence into dictionary iff
the sequence has anything in it
"""
if len(entry_lines) < 1:
return
entries[moment.times[-2]] = entry_lines | 5,354,419 |
def cleanup_dir(dir_path=WORKING_DIR):
"""
A function decorator that cleans up file directory before executing.
"""
def rm_content(dir_path):
rm_count = 0
for filename in os.listdir(dir_path):
filepath = os.path.join(dir_path, filename)
if os.path.isfile(filepath... | 5,354,420 |
def test_table():
"""
Tests creating table without parent.
:return: None.
"""
a = BbnNode(Variable(0, 'a', ['on', 'off']), [0.5, 0.5])
table = Table(a)
assert not table.has_parents()
assert_almost_equal(table.probs, np.array([0.5, 1.0]))
assert 'on' == table.get_value(0.4)
asser... | 5,354,421 |
def validate_url(url):
"""
Validates the URL
:param url:
:return:
"""
if validators.url(url):
return url
elif validators.domain(url):
return "http://{}".format(url)
return "" | 5,354,422 |
def test_companies_details_unrelated(user: User, other_company: Company):
""" Company details can be viewed by an unrelated user (non-employee), but only basic information is returned.
"""
client = APIClient()
client.force_authenticate(user)
resp = client.get(client.reverse('company-detail', pk=ot... | 5,354,423 |
def map_class_to_id(classes):
"""
Get a 1-indexed id for each class given as an argument
Note that for MASATI, len(classes) == 1 when only considering boats
Args:
classes (list): A list of classes present in the dataset
Returns:
dict[str, int]
"""
class_ids = list(range(1, l... | 5,354,424 |
def run_directory(tmp_path_factory):
"""
Prepare mock directory structure for run directory of code.
"""
tmp_path = tmp_path_factory.mktemp('output')
for path in OUTPUT_PATHS:
if os.path.dirname(path):
os.makedirs(tmp_path / os.path.dirname(path), exist_ok=True)
with open... | 5,354,425 |
def setup_py_main():
"""Main function for setup script."""
if sys.stdin.isatty() and sys.stdout.isatty() and sys.stderr.isatty():
if os.getpgrp() == os.tcgetpgrp(sys.stdout.fileno()):
if os.geteuid() == 0:
main()
terminate()
else:
p... | 5,354,426 |
def vec2text(vector):
"""
vector to captcha text
:param vector: np array
:return: text
"""
if not isinstance(vector, np.ndarray):
vector = np.asarray(vector)
vector = np.reshape(vector, [CAPTCHA_LENGTH, -1])
text = ''
for item in vector:
text += CAPTCHA_LIST[np.argmax... | 5,354,427 |
def get_data_nasdaq_fall(specified_value):
"""
:param specified_value: the number of datapoints to fetch from the backend
:param collection: specify which collection to be fetched
:return: list of dictionaries
"""
data_points = NasdaqAsc.objects.order_by('difference_close')
data_points = d... | 5,354,428 |
def download(ctx):
"""Download code of the current project."""
user, project_name = get_project_or_local(ctx.obj.get('project'))
try:
PolyaxonClient().project.download_repo(user, project_name)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.prin... | 5,354,429 |
def check_qe_completed(folder,prefix,output_file,calc_type='pw'):
"""
Check if qe calculation has correctly completed.
- folder: where the calculation has been run.
- prefix: qe prefix
- output_file: name of output file
- calc_type: either 'pw' or 'ph' or 'gkkp'
"""
status = T... | 5,354,430 |
def require_openssl(required_version):
"""
This function checks that the required version of OpenSSL is present, and skips the test if not.
Use it as a test function decorator:
@require_openssl("2.3.4")
def test_something():
...
:param required_version: minimal required ver... | 5,354,431 |
def login_required(f):
"""页面要求登录装饰器"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not g.signin:
nu = get_redirect_url()
if nu and (
nu.startswith("/") or nu.startswith(request.url_root)
):
return redirect(url_for('front.l... | 5,354,432 |
def get_agent_type(opt):
"""
Returns the type of model agent, specified by --model and
--model_file.
"""
model_file = opt['model_file']
optfile = model_file + '.opt'
if isfile(optfile):
new_opt = _load_opt_file(optfile)
if 'batchindex' in new_opt:
del new_opt['bat... | 5,354,433 |
def update_col(col, collation=None, mssql_from=True, mssql_to=True):
"""Updates the default value, type and collation of the specified column."""
# - Update the default value
update_col_default(col, mssql_from=mssql_from, mssql_to=mssql_to)
# - Update the type
update_col_type(col, mssql_from=mssql_from, mssql_to=m... | 5,354,434 |
def create_markup_map(name: str, df: pd.core.frame.DataFrame):
"""Place a markup for each point with a valid
housing price evaluation and position
"""
map_ = folium.Map(
location=france_location,
zoom_start=3,
control_scale=True,
tiles="openstreetmap",
)
mcg = fol... | 5,354,435 |
def write_sequential_results_to_csv(results, opts):
"""
:param results: SequentialResults
:param opts:
:return:
"""
prefix = opts.get_alad_metrics_name_prefix()
num_seen_file = os.path.join(opts.resultsdir, "%s-num_seen.csv" % (prefix,))
baseline_file = os.path.join(opts.resultsdir, "%s... | 5,354,436 |
def is_sparse_or_ragged_tensor_value(tensor: Any) -> bool:
"""Returns true if sparse or ragged tensor."""
return (isinstance(tensor, types.SparseTensorValue) or
isinstance(tensor, types.RaggedTensorValue) or
isinstance(tensor, tf.compat.v1.SparseTensorValue)) | 5,354,437 |
def _is_file_not_empty(file_path):
"""Return True when buildinfo file is not empty"""
# NOTE: we can assume, that when file exists, all
# content have been dowloaded to the directory.
return os.path.getsize(file_path) > 0 | 5,354,438 |
def arcsin(tensor):
"""Returns the element-wise inverse sine of the tensor"""
return TensorBox(tensor).arcsin(wrap_output=False) | 5,354,439 |
def get_one_pokemon(id: hug.types.number):
"""Affichage d'un pokemon de la base de donnees"""
cursor.execute("""SELECT * FROM pokemon WHERE id=%s """, [id])
row = cursor.fetchone()
conn.commit()
conn.close()
return row | 5,354,440 |
def check_file_exists(filename):
"""Try to open the file `filename` and return True if it's valid """
return os.path.exists(filename) | 5,354,441 |
def set_loop_header_loop(context: X12ParserContext, segment_data: Dict) -> None:
"""
Resets the loop context to the Eligibility Loop 2120C/D (Subscriber and Dependent)
The LS segment precedes the Subscriber/Dependent Benefit Related Entity Name
:param context: The X12Parsing context which contains the ... | 5,354,442 |
def shift_fft(input_img, shift_val, method="fft"):
"""Do shift using FFTs
Shift an array like scipy.ndimage.interpolation.shift(input, shift, mode="wrap", order="infinity") but faster
:param input_img: 2d numpy array
:param shift_val: 2-tuple of float
:return: shifted image
"""
if method =... | 5,354,443 |
def get_output_detections_image_file_path(input_file_path, suffix="--detections"):
"""Get the appropriate output image path for a given image input.
Effectively appends "--detections" to the original image file and
places it within the same directory.
Parameters
-----------
input_file_path: s... | 5,354,444 |
def plot_weather(wr_date, full=False, fname=None):
"""Plot a weather radar image.
"""
if isinstance(wr_date, str):
wr_date = datetime.strptime(wr_date, '%Y%m%dT%H%M')
# Load the weather radar image
wr_before, wr_after = workflow.find_closest_weather_radar_files(wr_date)
if wr_before !=... | 5,354,445 |
def split_errorSC(tr, t1, t2, q, Emat, maxdt, ddt, dphi):
"""
Calculate error bars based on a F-test and
a given confidence interval q
Parameters
----------
tr : :class:`~obspy.core.Trace`
Seismogram
t1 : :class:`~obspy.core.utcdatetime.UTCDateTime`
Start time of picking w... | 5,354,446 |
def main():
"""Build the same model using pybinding and kwant and verify that the results are identical"""
width, length = 15, 15
electron_energy = 0.25
barrier_heights = np.linspace(0, 0.5, 100)
with pb.utils.timed("pybinding:"):
pb_transmission = measure_pybinding(width, length, electron_... | 5,354,447 |
def test_add_via_stack():
"""
Unit test definition
"""
spec_file = 'bpg_test_suite/specs/add_via_stack.yaml'
plm = BPG.PhotonicLayoutManager(spec_file)
plm.generate_content()
plm.generate_gds() | 5,354,448 |
def test_ridges_at_region():
"""Test getting ridges that bound regions."""
v = Voronoi(POINTS)
converter = VoronoiConverter(v)
ridges_at_region = converter.get_ridges_at_region()
assert_tuple_equal(ridges_at_region.shape, (len(v.regions), 6))
assert_is_instance(ridges_at_region[0, 0], np.int_)... | 5,354,449 |
def get_image():
"""
Returns an image taken using raspberry pi camera.
This image can be directly used with OpenCV library.
"""
if DEBUG:
print("\tTakes image using camera")
camera = PiCamera()
camera.resolution = (512,512)
raw_img = PiRGBArray(camera)
time.sleep(0.1) # ... | 5,354,450 |
def add(x, y):
"""Creates an SMTLIB addition statement formatted string
Parameters
----------
x, y: float
First and second numerical arguments to include in the expression
"""
return "(+ " + x + " " + y + ")" | 5,354,451 |
def build_put_cat_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Put a cat with name 'Boots' where likesMilk and hisses is false, meows is true.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:keyword json... | 5,354,452 |
def partial(fn: Callable, *args, **kwargs) -> Callable:
"""Takes a function and fewer than normal arguments, and returns a function
That will consume the remaining arguments and call the function"""
def partial_fn(*rem_args, **rem_kwargs):
return fn(*args, *rem_args, **kwargs, **rem_kwargs)
re... | 5,354,453 |
def do_nothing(apps, schema_editor):
"""
Do nothing since this is removing bad data
""" | 5,354,454 |
def parse_lipid(name):
"""
parse_lipid
description:
parses a lipid name into lipid class and fatty acid composition, returning a
dictionary with the information. Handles total fatty acid composition, as well
as individual composition, examples:
PC(38:3) --> class: PC, ... | 5,354,455 |
def query(lon, lat, coordsys='gal', mode='full', limit=500000):
"""
Send a line-of-sight reddening query to the Argonaut web server.
lon, lat: longitude and latitude, in degrees.
coordsys: 'gal' for Galactic, 'equ' for Equatorial (J2000).
mode: 'full', 'lite' or 'sfd'
In 'full' mode, outputs a... | 5,354,456 |
def CreatePreDefinedMapUnits(Map_Units, in_features, field_name=None):
"""
Intersects the Map Units feature class with the in_features feature class.
A field name may be provided from the in_features to include in the output
feature class as a label for the map unit, the field will be updated with
'... | 5,354,457 |
def f(x0,x1,l,mig_spont,mig_ind,eps):
""" function defining the model dx/dt=f(x)"""
return [f0(x0,x1,l,mig_spont,mig_ind,eps),f1(x0,x1,l,mig_spont,mig_ind,eps)] | 5,354,458 |
def transform(source, transforms, params=None, output=None):
"""
Convenience function for applying an XSLT transform. Returns
a result object.
source - XML source document in the form of a string (not Unicode
object), file-like object (stream), file path, URI or
amara.lib.inp... | 5,354,459 |
def lookup_user_github_username(user_github_id: int) -> Optional[str]:
"""
Given a user github ID, looks up the user's github login/username.
:param user_github_id: the github id
:return: the user's github login/username
"""
try:
headers = {
'Authorization': 'Bearer {}'.forma... | 5,354,460 |
def get_plot_values(radar):
"""
Return the values specific to a radar for plotting the radar fields.
"""
return _DEFAULT_PLOT_VALUES[radar].copy() | 5,354,461 |
def time_series_dict_to_list(dictionary, key=lambda x: time.mktime(x.timetuple()), value=identity):
"""
Convert the incoming dictionary of keys to a list of sorted tuples.
:param dictionary: dictionary to retrieve data from
:param key: expression used to retrieve the time_series key from the key
:pa... | 5,354,462 |
def get_data_from_csv(csv_reader):
"""Creates a list of StatEntry objects based on data in CSV data.
Input CSV data must be in the format:
Description,timestamp,num_batches,time mean value,time sd
Args:
csv_reader: csv.reader instance.
Returns:
A tuple of datetime timestamp and list of ... | 5,354,463 |
def init_database(db: str):
"""
Init database.
:param db: Database file path.
:return:
"""
connection = sqlite3.connect(db)
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS user_traffic ('
'id INTEGER PRIMARY KEY AUTOINCREMENT,'
... | 5,354,464 |
def rootUrlJoin(base, extend):
"""
Adds a path element to the path within a ROOT url
"""
if base:
match = re.match("^root://([^/]+)/(.+)", base)
if match:
host = match.group(1)
path = match.group(2)
newpath = os.path.join(path, extend)
newu... | 5,354,465 |
def getChildren(SOUP, ADDRESS_SET, FOLDER_LIST, FOLDER_PTR, DEBUG, LEVEL=0):
"""
Loop interative call to move into soup
Args:
SOUP ie bs.BeautifulSoup( doc ) or a sub-portion there-of
ADDRESS_SET list of address information
FOLDER_LIST list of folders
FOLD... | 5,354,466 |
def at_initial_setup():
"""
Custom hook for users to overload some or all parts of the initial
setup. Called very last in the sequence. It tries to import and
srun a module settings.AT_INITIAL_SETUP_HOOK_MODULE and will fail
silently if this does not exist or fails to load.
"""
modname = set... | 5,354,467 |
def either(a, b):
"""
:param a: Uncertain value (might be None).
:param b: Default value.
:return: Either the uncertain value if it is not None or the default value.
"""
return b if a is None else a | 5,354,468 |
def get_app_label_and_model_name(path):
"""Gets app_label and model_name from the path given.
:param str path: Dotted path to the model (without ".model", as stored
in the Django `ContentType` model.
:return tuple: app_label, model_name
"""
parts = path.split('.')
return (''.join(parts[... | 5,354,469 |
def remove_cache():
"""Util to remove the cache files, which can be located at two different places
depending if pycee is running as a installed package or as a cloned repository"""
installed_module_path = pathlib.Path(__file__).parent.absolute()
package_cache = glob.glob(os.path.join(installed_module_... | 5,354,470 |
def get_item_editor(val):
"""
(val: Any) -> Editor
Returns customized View editor type for given attribute value.
"""
if isinstance(val, list): # later might need tuple with label case
if isinstance(val[0], str):
return CheckListEditor(values=val)
else:
ret... | 5,354,471 |
def index_js_to_enriched_function_blocks(index_js: str) -> List[EnrichedFunctionBlock]:
"""
Main function of the file. Converts raw index.js file into the output dataclass.
"""
trimmed_index_js = trim_index_js(index_js)
index_json = json.loads(trimmed_index_js)
rtn_blocks = []
for package_n... | 5,354,472 |
def menu(dictionary : Dictionary):
""" Wrapper for using the dictionary. """
option = None
menu_options = {'read_file': 'Read File',
'add_word': 'Add Word',
'find_word': 'Find Word',
'delete_word': 'Delete Word',
'exit': 'Exit'}... | 5,354,473 |
def compute_single_results(base_path: str, file_name: str, selection_metric: str, selection_scheme: Union[None, str],
selection_mode: str, selection_domain: str, result_scheme: str, result_mode: str, result_metric: str):
"""
Parameters
----------
base_path
file_name
s... | 5,354,474 |
def run():
""" Step through each row and every 3rd column to find collisions """
trees = 0
x = 0
width = len(rows[0])
for line in rows[1:]:
x += 3
if x >= width:
x -= width
if line[x] == "#":
trees += 1
return trees | 5,354,475 |
def div_col(*items, size=None, style=None, id=None, classes=None) -> HTML:
"""Generate a new div with a col class
Parameters
----------
items: argument list
DOM children of this div
"""
children = ''.join(items)
attr = []
if style is not None:
attr.append(f'style="{styl... | 5,354,476 |
def test_variable_init_with_no_terms() -> None:
"""Test fuzzy variable creation"""
universe_range: tuple[int, int] = (0, 1)
terms: dict = {}
fuzzyvar: FuzzyVariable = FuzzyVariable(universe_range=universe_range, terms=terms)
assert fuzzyvar.universe_range == universe_range
assert fuzzyvar.term... | 5,354,477 |
def predict(image: bytes) -> ndarray:
"""
Call the model returning the image with the faces blured
:param image: the image to blur the faces from
:return: the image with the faces blured
"""
import face_recognition
sigma = 50
image = face_recognition.load_image_file(image)
l... | 5,354,478 |
def get_basic_details(args, item):
"""
:param args: {
"item_code": "",
"warehouse": None,
"customer": "",
"conversion_rate": 1.0,
"selling_price_list": None,
"price_list_currency": None,
"price_list_uom_dependant": None,
"plc_conversion_rate": 1.0,
"doctype": "",
"name": "",
"supplier... | 5,354,479 |
def vec_len(x):
""" Length of the 2D vector"""
length = math.sqrt(x[0]**2 + x[1]**2)
return length | 5,354,480 |
def part1_count_increases(measurements):
"""Count increases of a measure with the next."""
windows = zip(measurements[1:], measurements[:-1])
increases = filter(lambda w: w[0] > w[1], windows)
return len(list(increases)) | 5,354,481 |
def remove_empties(seq):
""" Remove items of length 0
>>> remove_empties([1, 2, ('empty', np.nan), 4, 5])
[1, 2, 4, 5]
>>> remove_empties([('empty', np.nan)])
[nan]
>>> remove_empties([])
[]
"""
if not seq:
return seq
seq2 = [x for x in seq
if not (isins... | 5,354,482 |
def breadth_first_graph_search(problem):
"""Grafo paieškos į plotį algoritmas"""
global frontier, node, explored, counter
if counter == -1:
node = Node(problem.initial)
display_current(node)
if problem.goal_test(node.state):
return node
frontier = deque(... | 5,354,483 |
def test_copy_files_no_source_dir():
"""
Test that copy_files throws FileNotFoundError when source_dir does not
exist.
"""
with pytest.raises(FileNotFoundError):
abcutils.copy_files("dirthatdoesnotexist", "destination") | 5,354,484 |
def to_smiles(rdm):
""" SMILES string from an rdkit molecule object
"""
smi = _rd_chem.MolToSmiles(rdm)
return smi | 5,354,485 |
def merge_bins(adata, bin_size):
"""Merge bins."""
orig_bins = collections.defaultdict(list)
for coor in adata.var_names:
chrom, start, end = coor.split(':')[0], int(
coor.split(':')[1].split('-')[0]), int(
coor.split(':')[1].split('-')[1])
orig_bins[chrom].append((start, end))
loggi... | 5,354,486 |
def main():
"""
Perform cost modeling for PV systems using SAM and PVRPM
"""
pass | 5,354,487 |
def show_all_fruits():
"""Show all fruits in the database."""
fruits = fruits_collection.find({})
for fruit in fruits:
print(fruit)
context = {
'list_of_fruits': fruits_collection.find({})
}
return render_template('show_fruits.html', **context) | 5,354,488 |
def load_fields(path: str = f'{DEFAULT_FIELD_PATH}{FIELD_FILENAME}') -> dict:
"""Load Fields.
PARAMETERS
----------
:param: path: string path to the fields file.
Returns
-------
A dictionary of fields, with the following format:
{
"field_name": {
... | 5,354,489 |
def test_recall_at_k():
"""Test Metric.recall_at_k
"""
scores = np.array([[4., 3., 2., 1., 0.]])
gt = np.array([[1., 1., 0., 0., 1.]])
gt_2 = np.array([[0, 0, 1., 1., 1.]])
assert Metrics.recall_at_k(scores, gt, 2) == np.array([1.]), "recall@2 should be 1."
assert Metrics.recall_at_k(scores... | 5,354,490 |
def set_max_concurrency(
uses: int, bucket: t.Type[buckets.Bucket]
) -> t.Callable[[commands.base.CommandLike], commands.base.CommandLike]:
"""
Second order decorator that defines the max concurrency limit for a command.
Args:
uses (:obj:`int`): The maximum number of uses of the command that ca... | 5,354,491 |
def patch_jars(cluster, localSolrDir, n=None, jars='core solrj', vers='4.7.1'):
"""
Replaces Solr JAR files on remote servers with new ones built locally.
This command helps you patch a running system with a quick fix w/o having
to rebuild the AMI.
"""
localSolrDir = os.path.expanduser(localSolr... | 5,354,492 |
def three_to_one_protocol_bob(q1, q2, q3, bob, socket):
"""
Implements Bob's side of the 3->1 distillation protocol.
This function should perform the gates and measurements for 3->1 using
qubits q1 and q2, then send the measurement outcome to Alice and determine
if the distillation was successful.
... | 5,354,493 |
def test_run(cli_runner: CliRunner, servo_cli: Typer) -> None:
"""Run the servo""" | 5,354,494 |
def test_tensorboard() -> None:
"""Test if tensorboard returns a decorator."""
# Prepare
with TemporaryDirectory() as tmpdir:
my_decorator = tensorboard(tmpdir)
# Assert
assert callable(my_decorator) | 5,354,495 |
def read_code_blocks_from_md(md_path):
"""
Read ```python annotated code blocks from a markdown file.
Args:
md_path (str): Path to the markdown fle
Returns:
py_blocks ([str]): The blocks of python code.
"""
with open(md_path, "r") as f:
full_md = f.read()
md_py_sp... | 5,354,496 |
def CBOW(vocab_size, emb_size):
"""
CBOW: Function to define the CBOW model
parameters:
vocab_size: the vocabulary size
emb_size: dimension of the embedding vector
return:
List of theano variables [context, target], represents the model input,
Theano function represen... | 5,354,497 |
def elina_tcons0_array_add_dimensions_with(tcons_array, dimchange):
"""
Add dimensions to an ElinaTcons0Array by following the semantics of an ElinaDimchange.
Parameters
----------
tcons_array : ElinaTcons0ArrayPtr
Pointer to the ElinaTcons0Array to which we want to add dimensions.
dimc... | 5,354,498 |
def subject(request, clas_slug, subject_slug, page=1):
"""
Список гдз сборников для предмета
"""
gdz_clas = get_object_or_404(GdzClas, slug=clas_slug)
gdz_subject = get_object_or_404(GdzSubject, slug=subject_slug, gdz_clas=gdz_clas)
book_list = GdzBook.published.filter(gdz_clas=gdz_clas,
... | 5,354,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.