content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _count_partial_errors(client: GoogleAdsClient,
conversion_upload_response) -> int:
"""Counts the partial errors in the GAds response.
Args:
client: A GoogleAdsClient instance
conversion_upload_response: Google Upload Conversion service response.
Returns:
An intege... | aaa0ab8c3668765539a05374afb06bc3e661af23 | 3,656,400 |
def cumulative_similarity(atoms, representations,
threshold=0.98):
"""
"""
u_representations = [representations[0]]
s_idxs = [0]
for i, representation in enumerate(representations[1:]):
i += 1
similar = merge_asymmetric_similarity(atoms,
[representation],
... | 6f2c065233a6b7b7931bfdfcfe08a032287d6ffc | 3,656,401 |
def get_project_by_id(project_id):
"""
Retrieve a project by its Id. Returns None if no project is found.
"""
try:
return Project.objects.get(pk=project_id)
except Project.DoesNotExist:
return None | e7ae842d7b9daa5bde08a00f6dd9ac84246d4e13 | 3,656,402 |
from typing import Dict
from typing import Tuple
import os
def create_colorbar(
labels: pd.DataFrame,
tree: CassiopeiaTree,
colormap: Dict[str, Tuple[int, int, int]],
dataset_name: str,
output_directory: str = ".tmp/",
create_legend: bool = False,
) -> str:
"""Creates a colorbar file for t... | a0907476c4f5b027106b347a4500808805179112 | 3,656,403 |
def one_c(rand_gen):
"""
KS Test
:param rand_gen:
:return:
"""
# Now need to do the ks test
# This calculates the value for KS at given points
def ks_test(z):
if z == 0:
return 1
elif z < 1.18: # Numerically optimal cutoff
block = ((np.exp((-1. *... | 9a2b420f3620bc198bc880c01d90cc743ac5c2ec | 3,656,404 |
from typing import List
def divide_into_sentences(
text: str, num_of_senteces: int, is_reversed: bool = False, offset: int = 0
) -> str:
"""
This function divides the text into sentences and returns either the first X sentences or the last X sentences.
"""
tokens_sent = nltk.sent_tokenize(text)
... | e57e772942953c890b12e91c888688295dcf89ae | 3,656,405 |
def intersection(bbox1: BoundingBox,
bbox2: BoundingBox) -> BoundingBox:
"""
Calculate the intersection of two bounding boxes.
"""
assert bbox1.x_min <= bbox1.x_max
assert bbox1.y_min <= bbox1.y_max
assert bbox2.x_min <= bbox2.x_max
assert bbox2.y_min <= bbox2.y_max
... | 71ce5b562f5f6fbfe6dba51db43240a98b0d7d49 | 3,656,406 |
from typing import Optional
from typing import Iterable
import logging
def maybe_load_checkpoint(train_loop_rngs: jnp.ndarray,
save_checkpoint_path: str,
init_optimizer: flax.optim.Optimizer,
init_params: Params,
i... | 8b21fe6ac806a3d153d8dde11045a26432f52be0 | 3,656,407 |
def test_if_tech_defined(enduse_fueltypes_techs):
"""Test if a technology has been configured,
i.e. a fuel share has been assgined to one of the
fueltpyes in `fuel_shares`.
Arguments
---------
enduse_fueltypes_techs : dict
Configured technologies and fuel shares of an enduse
Return... | a727b375dc1bc7e76fe63090d8e278013fa2c6bb | 3,656,408 |
from mindboggle.guts.segment import segment_regions
def segment_rings(region, seeds, neighbor_lists, step=1, background_value=-1,
verbose=False):
"""
Iteratively segment a region of surface mesh as concentric segments.
Parameters
----------
region : list of integers
indi... | 3b2c5c1a68ecef7f036a332b966a3aa8610157af | 3,656,409 |
def classification_result(y, y_pred):
"""
:param y:
:param y_pred:
:return:
"""
assert len(y) == len(y_pred)
correct = []
wrong = []
for i in range(len(y)):
if y[i] == y_pred[i]:
correct.append(i)
else:
wrong.append(i)
return correct, wro... | bdab32eeded40691a721fe8e1463819605c5639c | 3,656,410 |
def flatgrad(loss, var_list, clip_norm=None):
"""Calculate the gradient and flatten it.
Parameters
----------
loss : float
the loss value
var_list : list of tf.Tensor
the variables
clip_norm : float
clip the gradients (disabled if None)
Returns
-------
list ... | cd359f78c882bbd57876e4011818422799727ce7 | 3,656,411 |
async def get_image_from_message(
ctx,
url=None,
*,
return_type="image_RGBA",
search_last_messages=True,
accept_emojis=True,
accept_templates=True,
):
"""Get an image from a discord Context or check on images among the 100
last messages sent in the channel. Return bytes or PIL.Image ... | fd135153dd6db0fb7e6e1990560da0aa69af6ac7 | 3,656,412 |
import tqdm
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: ... | 847de26005a291d9505a6c66221eec19e7924e54 | 3,656,413 |
from typing import Optional
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.... | ad5d517b5c05f0b2bbe300f6fd430d9780ebbc34 | 3,656,414 |
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... | 3764f412bdbae771fe75fec7b8623906fddf01b1 | 3,656,415 |
import requests
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'] + '... | 02b362a27d8c9101ca24f6a853513f99d167f4c9 | 3,656,416 |
from typing import List
import time
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
... | 348f32e8ab5881c3563cd442390e4af203a2b15d | 3,656,417 |
def isfile(value):
"""Validate that the value is an existing file."""
return vol.IsFile('not a file')(value) | 2513516dbe0bdb765cbff78780f6386c5809a8d7 | 3,656,418 |
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) != "" | e0f60c4b320d325db2cc27ece9395cae20b92fda | 3,656,419 |
import sys
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 opt... | e94e684d50965a8617f4a03899503784f5840b5f | 3,656,420 |
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... | 8d452b96e1a3cb8c6b134747fe351158625fed27 | 3,656,421 |
import pytz
from datetime import datetime
import json
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 =... | e44f42d8563d641ef9136f4121841c430e95288b | 3,656,422 |
import math
import time
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 par... | c4508e4aff53315a0fa84924f8a3fc66d99e0c8f | 3,656,423 |
from typing import List
from typing import Tuple
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... | e1e3eea43aff3301f317b1103e820bfb79169fbd | 3,656,424 |
def get_output():
"""Gets the current global output stream"""
global OUTPUT
return OUTPUT | 63480fb1dc071f3f3df878204fd2af6994cc9ea0 | 3,656,425 |
import scipy
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!
... | 62495a50995f9fb0cec30d63b627f1b66022561b | 3,656,426 |
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
... | de84adbc9a7779c05557941d1c4714e7a3eaf8c7 | 3,656,427 |
import os
import shutil
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)
... | 34a03406e1c47aa27597d98cce3d3e9c8506d68e | 3,656,428 |
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 "" | cd1ea3a834e1e67c4f438a28dcfa08e1dbd041c6 | 3,656,429 |
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... | 7c2b47249f61f446327c0a798c1a129c62fde6b3 | 3,656,430 |
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... | c819407caca85e4ced798b6c4058918708af0095 | 3,656,431 |
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... | 20d811f7276c410cb8aefb71cfd8ef23bea66977 | 3,656,432 |
import os
import subprocess
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 'gkk... | 778375406379996d86d0e033da8531566f8fa7dd | 3,656,433 |
import re
import subprocess
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... | 7750c2f4de2eda82e8d6765405648677e48e8ac7 | 3,656,434 |
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... | b9e7db40ebb50a71d4d56064fce8ec8e30fb6fbe | 3,656,435 |
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... | 59e53f961c29c9cf993bb176d4d993b80848bbcd | 3,656,436 |
from typing import Any
import types
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)... | 8c82ffd04dfae89f19f34770b67724ffb9c66fc1 | 3,656,437 |
import os
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 | 08ef68719eaf57adbb946412dc259ea3d42117d1 | 3,656,438 |
def arcsin(tensor):
"""Returns the element-wise inverse sine of the tensor"""
return TensorBox(tensor).arcsin(wrap_output=False) | c49f520610e0a59c8a29f25ff0f02c81b2226b14 | 3,656,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 | b36b2a5b50c1f0edfc39f3a74341bed583c36e13 | 3,656,440 |
import os
def check_file_exists(filename):
"""Try to open the file `filename` and return True if it's valid """
return os.path.exists(filename) | 93edc12c8d87863b560637f0bff73f0545f38270 | 3,656,441 |
import numpy
import scipy
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 i... | 2729d187d222ef83635abea5bc29a633abce9e61 | 3,656,442 |
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... | b8d060dff6800750c418c70c61bd4d8e0b7bb416 | 3,656,443 |
from scipy import stats
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`
... | 41c56204884bafc32effe5f96557b703da589e05 | 3,656,444 |
from re import DEBUG
import time
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 = PiRGBA... | 25f0e90378e70d443107ccfa519b0c36fd224e47 | 3,656,445 |
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 + ")" | 5145573a4616cc92be72301eae0a5dfffecf9234 | 3,656,446 |
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... | 5191eac67e6cdeedfa32ca32fad1cdd96e7a2870 | 3,656,447 |
from typing import Callable
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, *... | 80f0df16915593fa0c5212e7560626db78147da6 | 3,656,448 |
import re
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) -->... | 31a26cf57edfd08c6025c07982b7d6805704088e | 3,656,449 |
import chunk
import requests
import json
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', 'li... | 1975d69b1c01d0cbb824b813d994941a63728750 | 3,656,450 |
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)] | f6c6a9bdfd9eac7db40306388035bb2127301753 | 3,656,451 |
from amara.lib import inputsource
from amara.xpath.util import parameterize
from amara.xslt.result import streamresult, stringresult
from amara.xslt.processor import processor
def transform(source, transforms, params=None, output=None):
"""
Convenience function for applying an XSLT transform. Returns
a r... | 4a9bbb7a27a9daff977ccefc151a0c480b27f71b | 3,656,452 |
from typing import Optional
import requests
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 = {
... | 2943ff8760ff02006efcd33ecb59508fc2262520 | 3,656,453 |
def get_plot_values(radar):
"""
Return the values specific to a radar for plotting the radar fields.
"""
return _DEFAULT_PLOT_VALUES[radar].copy() | 579cf303a7be1201e71831a13f156b72766bad7f | 3,656,454 |
import time
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 t... | f5234ec0d5296c17f6758b2815b65ac33009944d | 3,656,455 |
from datetime import datetime
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 ... | 31473648b91b605d8537da720f316a22f8584f2a | 3,656,456 |
import re
import os
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, ex... | 613db9d8ae230bfba064e16cf4fe1712b061be91 | 3,656,457 |
import re
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
... | 34cef9312b9ee3f44bd40f4067cbbff170da875b | 3,656,458 |
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 | 3fd2f99fa0851dae6d1b5f11b09182dbd29bb8c1 | 3,656,459 |
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[... | 998e8d81f59491a51f3ae463c76c8627ed63b435 | 3,656,460 |
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... | 46dd3011bcd34ee7ecf5a311d45e8fa7a6d8603e | 3,656,461 |
from typing import List
import json
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)
... | 46776f7a277da4f111fb8b2d797c91777d84c2a7 | 3,656,462 |
from typing import Union
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
----------
ba... | b176f7d2a3ae3c19c67794c47969a3bf4d5d203b | 3,656,463 |
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 | f8c3f05ad411990bf16c6161f8ebcb544d5930df | 3,656,464 |
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... | 9200c23481756fa8d82813d1e95edc7328e63497 | 3,656,465 |
import face_recognition
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
"""
sigma = 50
image = face_recognition.load_image_file(image)
loc... | 87cfffa2a63c3e90baf023f2d37effa753c9ab89 | 3,656,466 |
from frappe.defaults import get_user_default_as_list
from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
import json
def get_basic_details(args, item):
"""
:param args: {
"item_code": "",
"warehouse": None,
"customer": "",
"conversion_rate": 1.0,
"selling_price_li... | f79438ebdcb7de48f48ca92e80f160a396d6ea6a | 3,656,467 |
import math
def vec_len(x):
""" Length of the 2D vector"""
length = math.sqrt(x[0]**2 + x[1]**2)
return length | a357d31df808720eb2c4dfc12f4d6194ef904f67 | 3,656,468 |
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)) | 59311b940ff7fe72cd6fe9cd4d0705918e796e69 | 3,656,469 |
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... | 500cbbd942682bfde1b9c1babe9a2190413b07fd | 3,656,470 |
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([node]) ... | 332d5d300615f30f1125c5fafed882f1941b8f39 | 3,656,471 |
def to_smiles(rdm):
""" SMILES string from an rdkit molecule object
"""
smi = _rd_chem.MolToSmiles(rdm)
return smi | bd0c79b8b0066bd0cf2f49d99c0ec80543f50c9b | 3,656,472 |
import collections
import logging
import scipy
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])
... | dc1f939e5bcd1604b525d616ee94868e6baae8c6 | 3,656,473 |
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) | 6329c6f6f1a7a30f6e35ea83aecd7fd71e81fe24 | 3,656,474 |
import json
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":... | b6bc8916fa3a9d8a53f7cda5e13acf32a9b57860 | 3,656,475 |
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... | b0677bc71f68d9ae674b424795bb29e93915726b | 3,656,476 |
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.
... | 0eab81d5d860c4314be4411b0dca429fc58cdb28 | 3,656,477 |
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... | ca920f74e9326cf5f3635fbb6ebe125b6d97a349 | 3,656,478 |
from re import T
import math
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,
... | 82275f52528715fc783247b649cc5b56e51e1ce2 | 3,656,479 |
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,
... | 1b7a3bd6314de87ec059313cd020a8249586619f | 3,656,480 |
def root_mean_square_ffinalise(out, sub_samples=None):
"""Divide the weighted sum by the sum of weights and take the square
root.
Also mask out any values derived from a too-small sample size.
:Parameters:
out: 3-`tuple` of `numpy.ndarray`
An output from `root_mean_square_fpartial... | 82562ef562b2e7dfaeefee9de42224568900f5a1 | 3,656,481 |
import hashlib
def md5sum_fileobj(f, start = 0, end = None):
"""Accepts a file object and returns the md5sum."""
m = hashlib.md5()
for block in file_reader(f, start, end):
assert block != "", "Got an empty read"
m.update(block)
return m.hexdigest() | db1046c2466d408b0de9e402af31930b72ce9d76 | 3,656,482 |
import math
def get_localization_scores(predicted_start: int, predicted_end: int, true_start: int, true_end: int):
"""
exp(-abs(t_pred_start-t_start)/(t_end-t_start))
exp(-abs(t_pred_end-t_end)/(t_end-t_start))
:param predicted_start:
:param predicted_end:
:param true_start:
:param true_en... | dfcef55e0594507b48aa83027c5b55a2a6530717 | 3,656,483 |
def json_compatible_key(key: str) -> str:
"""As defined in :pep:`566#json-compatible-metadata`"""
return key.lower().replace("-", "_") | b914ba17b3da5df84d72497048565a118fc4fb05 | 3,656,484 |
import logging
import json
def get_transitions(jira_host, username, password, issue_id):
"""
Returns transitions of the issue.
jira_host -- JIRA host to contact
username -- JIRA username with administrative permissions.
password -- password of the username.
issue_id -- id of the issue which t... | ec1546b6595e4482f245507e98dfd830673c9920 | 3,656,485 |
def _scale_func(k):
"""
Return a lambda function that scales its input by k
Parameters
----------
k : float
The scaling factor of the returned lambda function
Returns
-------
Lambda function
"""
return lambda y_values_input: k * y_values_input | 65fd06bfb1a278b106eecc4974bc9317b1dea67f | 3,656,486 |
import numpy
import multiprocessing
import math
def focal_agents(dest, weight, source, fail=False):
"""
dest: point property set (determines property return type)
weight: field property (weight/mask)
source: point property (values to gather from)
"""
# hack rename...
source_point = de... | 20acc643f725b0935e67041061fe8d7ebe9b44d3 | 3,656,487 |
import torch
from typing import Optional
from typing import Union
from typing import List
def erosion_dependent(input_tensor: torch.Tensor,
structuring_element: torch.Tensor,
origin: Optional[Union[tuple, List[int]]] = None,
border_value: Union[int, fl... | 7646d56ceab9a7ec27182c485954f748cf4afd75 | 3,656,488 |
def bin_barcodes(barcodes, binsize=1000):
"""Binning barcodes into chunks
Parameters
----------
barcodes : iterable
Iterable of barcodes
binsize : int
Size of bin for grouping barcodes
Returns
-------
yields list of barcode (1 bin)
"""
binsize = int(float(bin... | 3cc063f68a89a325a53def31bfe779d3aa8e62c6 | 3,656,489 |
def flash_regions(device, region_map):
"""divide the named memory into sized memory regions"""
regions = []
for x in region_map:
if len(x) == 2:
# no meta information: set it all to None
(name, region_sizes) = x
meta = (None,) * len(region_sizes)
elif len(x) == 3:
# provided meta i... | 43f444c1bdfee8441a8e6bf6c72dbc06dccb56df | 3,656,490 |
from typing import Collection
import json
def _load_explorer_data(multiprocess=False):
"""
Load in all available corpora and make their initial tables
This is run when the app starts up
"""
corpora = dict()
tables = dict()
for corpus in Corpus.objects.all():
if corpus.disabled:
... | f302b2529402b4ed75fa554ef915d7c117bca149 | 3,656,491 |
def compute_CD_projected_psth(units, time_period=None):
"""
Routine for Coding Direction computation on all the units in the specified unit_keys
Coding Direction is calculated in the specified time_period
:param: unit_keys - list of unit_keys
:return: coding direction unit-vector,
contr... | 44025b200855cb685efa052e106b4b5a1ed47b6e | 3,656,492 |
import struct
def _tvos_extension_impl(ctx):
"""Implementation of the `tvos_extension` Skylark rule."""
binary_artifact = binary_support.get_binary_provider(
ctx.attr.deps, apple_common.AppleExecutableBinary).binary
deps_objc_provider = binary_support.get_binary_provider(
ctx.attr.deps, apple_common... | e1bbd3711e7b449fdb23ebb6bbb755c4dbbe14c9 | 3,656,493 |
import copy
def simplify_graph(G):
"""remove the scores, so the cycle_exits() function can work"""
graph = copy.deepcopy(G)
simplified = dict((k, graph[k][0]) for k in graph)
# add dummy edges,so the cycle_exists() function works
for source in simplified.keys():
for target in simplified[s... | fc9b052c83ce500d20842367b3b6f011268a5a7d | 3,656,494 |
def Run_INCR(num_vertices, edge_density, algorithm_name, k, init_tree=None):
"""
Initialize and run the MVA algorithm
"""
edges_bound = int(edge_density * (num_vertices * (num_vertices - 1) / 2))
k = max(1, k * edges_bound)
runner = runner_factory(num_vertices, algorithm_name, None, edges_b... | 4b64891d773f8e5f43833984727d514e089937cb | 3,656,495 |
import os
import subprocess
def create_nrrd_from_dicoms(image, patient_id):
"""
Reads a folder that contains multiple DICOM files and
converts the input into a single nrrd file using a command line
app from MITK or MITK Phenotyping.
Input:
* path to one dicom (other are automatical... | f930d9ccfab7c20d8afb80fb0b9a422df8bc77e8 | 3,656,496 |
def _two_point_interp(times, altitudes, horizon=0*u.deg):
"""
Do linear interpolation between two ``altitudes`` at
two ``times`` to determine the time where the altitude
goes through zero.
Parameters
----------
times : `~astropy.time.Time`
Two times for linear interpolation between
... | b7b9bd53464d17c9e8fc51006a938b4c6b9cfac1 | 3,656,497 |
import string
def setup_sample_data(no_of_records):
"""Generate the given number of sample data with 'id', 'name', and 'dt'"""
rows_in_database = [{'id': counter, 'name': get_random_string(string.ascii_lowercase, 20), 'dt': '2017-05-03'}
for counter in range(0, no_of_records)]
retu... | 65659f931a103ea80dce19eabe277bba88653279 | 3,656,498 |
from io import StringIO
import csv
def generate_csv_string(csv_data):
""" Turn 2d string array into a string representing a csv file """
output_buffer = StringIO()
writer = csv.writer(output_buffer)
csv_data = equalize_array(csv_data)
csv_data = utf_8_encode_array(csv_data)
for row in csv_data:
writ... | 70861f363ed3d8445b38f448ffdea9ea1d479239 | 3,656,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.