content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gather_parent_cnvs(vcf, fa, mo):
"""
Create BEDTools corresponding to parent CNVs for converage-based inheritance
"""
cnv_format = '{0}\t{1}\t{2}\t{3}\t{4}\n'
fa_cnvs = ''
mo_cnvs = ''
for record in vcf:
# Do not include variants from sex chromosomes
if record.chrom i... | 6,600 |
def test_get_light_information(light_control):
"""Test get light information API."""
light_control._request.return_value = response_getLightInformation
light_control.get_light_information()
light_control._request.assert_called_with(
"post",
"/axis-cgi/lightcontrol.cgi",
json={
... | 6,601 |
def create_images():
""" Create new images
Internal Parameters:
image (FileStorage): Image
Returns:
success (boolean)
image (list)
"""
# vars
image_file = request.files.get('image')
validate_image_data({"image": image_file})
image_url_set =... | 6,602 |
def docx2python(
docx_filename: Union[str, Path],
image_folder: Optional[str] = None,
html: bool = False,
paragraph_styles: bool = False,
extract_image: bool = None,
) -> DocxContent:
"""
Unzip a docx file and extract contents.
:param docx_filename: path to a docx file
:param image_... | 6,603 |
def test_check_datasets_raises_with_unsorted_interactions():
"""Passed datasets that have sublattice interactions not in sorted order should raise."""
with pytest.raises(DatasetError):
check_dataset(dataset_single_unsorted_interaction) | 6,604 |
def parcel_analysis(con_imgs, parcel_img,
msk_img=None, vcon_imgs=None,
design_matrix=None, cvect=None,
fwhm=8, smooth_method='default',
res_path=None):
"""
Helper function for Bayesian parcel-based analysis.
Given a sequence o... | 6,605 |
def memoize(fn):
"""Simple memoization decorator for functions and methods,
assumes that all arguments to the function can be hashed and
compared.
"""
memoized_values = {}
@wraps(fn)
def wrapped_fn(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
try:
... | 6,606 |
def insert_record(bitdotio, record, qualified_table):
"""Inserts a single sensor measurement record.
Parameters
----------
bitdotio : _Bit object
bit.io connection client.
record : list
The record as a list of str representations.
qualified_table: str
The schema qual... | 6,607 |
def remove(tag: str, not_exist_ok: bool = True) -> None:
"""
Remove the map with the given ``tag``.
Parameters
----------
tag
The ``tag`` to search for and remove.
not_exist_ok
If ``False``, raise :class:`htmap.exceptions.MapIdNotFound` if the ``tag`` doesn't exist.
"""
... | 6,608 |
def validate(
args: Namespace,
model: BaseModel
) -> pd.DataFrame:
"""Perform the validation.
Parameters
----------
args : Namespace
Arguments to configure the model and the validation.
model : BaseModel
The model to be used for validation.
Returns
-------
pd.Da... | 6,609 |
def test_directory_origin_multi_char_delimited(sdc_builder, sdc_executor):
"""
Test Directory Origin with multi-character delimited format. This will generate a sample file with the custom
multi-char delimiter then read it with the test pipeline.
The pipeline looks like:
directory >> trash
... | 6,610 |
def stats(last_day=None, timeframe=None, dates_sources=None):
"""See :class:`bgpranking.api.get_stats`"""
query = {'method': 'stats'}
query.update({'last_day': last_day, 'timeframe': timeframe,
'dates_sources': dates_sources})
return __prepare_request(query) | 6,611 |
def restore_purchases() -> None:
"""restore_purchases() -> None
(internal)
"""
return None | 6,612 |
def show_corner_plot(chain, burnin=0.5, save=False, **kwargs):
"""
Display or save a figure showing the corner plot (pdfs + correlation plots)
Parameters
----------
chain: numpy.array
The Markov chain. The shape of chain must be nwalkers x length x dim.
If a part of the chain i... | 6,613 |
def sim_mat(fc7_feats):
"""
Given a matrix of features, generate the similarity matrix S and sparsify it.
:param fc7_feats: the fc7 features
:return: matrix_S - the sparsified matrix S
"""
print("Something")
t = time.time()
pdist_ = spatial.distance.pdist(fc7_feats)
print('Created di... | 6,614 |
def text_split(in_text, insert_points, char_set):
""" Returns: Input Text Split into Text and Nonce Strings. """
nonce_key = []
encrypted_nonce = ""
in_list = list(in_text)
for pos in range(3967):
if insert_points[pos] >= len(in_list) - 1: point = len(in_list) - 2
else: point = inser... | 6,615 |
def set_global_manager(manager):
"""Set the global ResourceManager."""
global RESOURCE_MANAGER
RESOURCE_MANAGER = manager | 6,616 |
def f_approximation(g_matrix, coeficients_array):
"""
Retorna um vetor para o valor aproximado de f, dados os coeficientes ak.
"""
decimal.getcontext().prec = PRECSION
decimal.getcontext().rounding = ROUNDING_MODE
num_of_xs = len(g_matrix[0])
num_of_coeficients = len(g_matrix)
f_appro... | 6,617 |
def _module_exists(module_name):
"""
Checks if a module exists.
:param str module_name: module to check existance of
:returns: **True** if module exists and **False** otherwise
"""
try:
__import__(module_name)
return True
except ImportError:
return False | 6,618 |
def users(request):
"""Show a list of users and their puzzles."""
context = {'user_list': []}
for user in User.objects.all().order_by('username'):
objs = Puzzle.objects.filter(user=user, pub_date__lte=timezone.now()).order_by('-number')
if objs:
puzzle_list = []
for p... | 6,619 |
def write_file(data_feed, file_path):
"""Write data to a file."""
if data_feed == None:
return
with open(file_path, "w") as open_file:
keys = data_feed[0].keys()
header = ",".join(keys)
open_file.write("{}\n".format(header))
for data in data_feed:
dat... | 6,620 |
def switchClock(onoff, alarmSymbol):
"""
changes the mode of the clock display, from time to text
:param onoff (bool): True=Time mode False=Text Display
:param alarmSymbol (bool): indicates whether the alarm is set when in clock mode (alarm symbol is drawn)
:param scrollOverride (bool): indicates wh... | 6,621 |
def featurize(mode, output_filename=None):
"""
Catch all method to featurize either train or test dataset and save to CSV
Params:
mode: (str) TRAIN or TEST
output_filename: (str) Optional- name of the csv to save the data
"""
MODE = mode
if not os.path.exists('train/') or not os... | 6,622 |
def my_removefile(filename,my_sys_ldebug=0,fatal=0):
"""
Verwijdert een file.
Argumenten: pad naar file en evt een fatal-optie
"""
#Controleer of opgegeven pad een bestaande file is.
if os.path.isfile(filename):
try:
if (my_sys_ldebug):
print("MY_REMOVEFILE: D... | 6,623 |
def MIPS_SPIRE_gen(phot_priors,sed_prior_model,chains=4,seed=5363,iter=1000,max_treedepth=10,adapt_delta=0.8):
"""
Fit the three SPIRE bands
:param priors: list of xidplus.prior class objects. Order (MIPS,PACS100,PACS160,SPIRE250,SPIRE350,SPIRE500)
:param sed_prior: xidplus.sed.sed_prior class
:pa... | 6,624 |
def check_cstr(solver, indiv):
"""Check the number of constraints violations of the individual
Parameters
----------
solver : Solver
Global optimization problem solver
indiv : individual
Individual of the population
Returns
-------
... | 6,625 |
def _FixFsSelectionBit(key, expected):
"""Write a repair script to fix a bad fsSelection bit.
Args:
key: The name of an fsSelection flag, eg 'ITALIC' or 'BOLD'.
expected: Expected value, true/false, of the flag.
Returns:
A python script to fix the problem.
"""
if not _ShouldFix('fsSelection'):
... | 6,626 |
def checkThread(self):
"""
Скинуть название исключения в потоке, ежели такое произойдет
:rtype: none
"""
for x in as_completed(self.futures):
if x.exception() is not None:
logging.error(x.exception())
print(f"ошибОЧКА разраба: {x.exception()}")
self.futures.r... | 6,627 |
def dilation_dist(path_dilation, n_dilate=None):
"""
Compute surface of distances with dilation
:param path_dilation: binary array with zeros everywhere except for paths
:param dilate: How often to do dilation --> defines radious of corridor
:returns: 2dim array of same shape as path_dilation, with ... | 6,628 |
def no_lfs_size_limit(client):
"""Configure environment track all files in LFS independent of size."""
client.set_value("renku", "lfs_threshold", "0b")
client.repo.git.add(".renku/renku.ini")
client.repo.index.commit("update renku.ini")
yield client | 6,629 |
def append(filename, string):
"""open file for appending, dump string, close file"""
op = open(filename, "a")
op.write(string)
op.close() | 6,630 |
def plot_rgb_phases(absolute, phase):
"""
Calculates a visualization of an inverse Fourier transform, where the absolute value is plotted as brightness
and the phase is plotted as color.
:param absolute: 2D numpy array containing the absolute value
:param phase: 2D numpy array containing phase info... | 6,631 |
def init(file: str, template: str, verbose = False, dry_run = False) -> None:
"""Copies template to file"""
if exists(file):
inp = input(
"File '{}' aldready exists, overwrite with new LaTeX file (y/n) ? ".format(file)
)
if not inp or inp.lower()[0] != "y":
exit(0)
command = 'cp "{}" "{}"'.format(templat... | 6,632 |
def layer_view_attachment_warning():
"""Unlimited attachments are warnings"""
content = {
'id': str(uuid.uuid4()),
'_type': 'CatXL',
'attachment': {
'currency': 'USD',
'value': float_info.max,
}
}
return convert_to_analyzere_object(content, LayerVi... | 6,633 |
async def test_multi_group_move(
mock_can_messenger: AsyncMock, move_group_multiple: MoveGroups
) -> None:
"""It should start next group once the prior has completed."""
subject = MoveScheduler(move_groups=move_group_multiple)
mock_sender = MockSendMoveCompleter(move_group_multiple, subject)
mock_ca... | 6,634 |
def restart(bot: DeltaBot, message: Message, replies: Replies) -> None:
"""Restart the game in the game group it is sent."""
with session_scope() as session:
game = session.query(Game).filter_by(chat_id=message.chat.id).first()
if game is None:
replies.add("❌ This is not a game group... | 6,635 |
def create_resfinder_sqlite3_db(dbfile, mappings):
"""
Create and fill an sqlite3 DB with ResFinder mappings.
Expects mappings to be a list of tuples:
(header, symbol, family, class, extra)
"""
logging.info("Creating sqlite3 db: %s ...", dbfile)
if os.path.isfile(dbfile):
logging... | 6,636 |
def normal_shock_pressure_ratio(M, gamma):
"""Gives the normal shock static pressure ratio as a function of upstream Mach number."""
return 1.0+2.0*gamma/(gamma+1.0)*(M**2.0-1.0) | 6,637 |
def create_small_test_fixture(output_dir: str = '/tmp') -> None:
"""
This is how I created the transformer_model.tar.gz.
After running this, go to the specified output dir and run
tar -czvf transformer_model.tar.gz model/
In case you need to regenerate the fixture for some reason.
"""
... | 6,638 |
def _lorentz_berthelot(
epsilon_1: float, epsilon_2: float, sigma_1: float, sigma_2: float
) -> Tuple[float, float]:
"""Apply Lorentz-Berthelot mixing rules to a pair of LJ parameters."""
return numpy.sqrt(epsilon_1 * epsilon_2), 0.5 * (sigma_1 + sigma_2) | 6,639 |
def test_searchChunked_chunksize(client):
"""Same as test_searchChunked_simple, but setting a chunksize now.
"""
# chunksize is an internal tuning parameter in searchChunked()
# that should not have any visible impact on the result. So we
# may test the same assumptions as above. We choose the chu... | 6,640 |
def test_utc_to_local():
"""Check if passed utc datestamp becomes local one."""
import pytz
from tokendito import helpers
from tzlocal import get_localzone
utc = datetime.now(pytz.utc)
local_time = utc.replace(tzinfo=pytz.utc).astimezone(tz=get_localzone())
local_time = local_time.strftime(... | 6,641 |
def test_iterate_input_serializer(aiida_profile, generate_iterator):
"""Test of the classmethod `_iterate_input_serializer` of `BaseIterator`."""
import pytest
with pytest.raises(ValueError):
generate_iterator._iterate_input_serializer({"www": "w"})
it_over = generate_iterator._iterate_input_s... | 6,642 |
def verify_password_str(password, password_db_str):
"""Verify password matches database string."""
split_password_db = password_db_str.split('$')
algorithm = split_password_db[0]
salt = split_password_db[1]
return password_db_str == generate_password_str(algorithm, salt, password) | 6,643 |
def get_ical_file_name(zip_file):
"""Gets the name of the ical file within the zip file."""
ical_file_names = zip_file.namelist()
if len(ical_file_names) != 1:
raise Exception(
"ZIP archive had %i files; expected 1."
% len(ical_file_names)
)
return ical_file_names... | 6,644 |
def unquoted_str(draw):
"""Generate strings compatible with our definition of an unquoted string."""
start = draw(st.text(alphabet=(ascii_letters + "_"), min_size=1))
body = draw(st.text(alphabet=(ascii_letters + digits + "_")))
return start + body | 6,645 |
def _reduce_attribute(states: List[State],
key: str,
default: Optional[Any] = None,
reduce: Callable[..., Any] = _mean) -> Any:
"""Find the first attribute matching key from states.
If none are found, return default.
"""
attrs = list(_fin... | 6,646 |
def sync_garmin(fit_file):
"""Sync generated fit file to Garmin Connect"""
garmin = GarminConnect()
session = garmin.login(ARGS.garmin_username, ARGS.garmin_password)
return garmin.upload_file(fit_file.getvalue(), session) | 6,647 |
def get_paths(graph: Graph, filter: Callable) -> List:
""" Collect all the paths consist of valid vertices.
Return one path every time because the vertex index may be modified.
"""
result = []
if filter == None:
return result
visited = set()
vs = graph.topological_sorting()
... | 6,648 |
def create_app(app_name=PKG_NAME):
"""Initialize the core application."""
app = Flask(app_name)
CORS(app)
with app.app_context():
# Register Restx Api
api.init_app(app)
return app | 6,649 |
def smtlib_to_sympy_constraint(
smtlib_input: str,
interpreted_constants: Dict[str, Callable] = default_interpreted_constants,
interpreted_unary_functions: Dict[str,
Callable] = default_interpreted_unary_functions):
"""Convert SMTLIB(v2) constraints into sympy constra... | 6,650 |
async def revert(app, change_id: str) -> dict:
"""
Revert a history change given by the passed ``change_id``.
:param app: the application object
:param change_id: a unique id for the change
:return: the updated OTU
"""
db = app["db"]
change = await db.history.find_one({"_id": change_i... | 6,651 |
def days_away(date):
"""Takes in the string form of a date and returns the number of days until date."""
mod_date = string_to_date(date)
return abs((current_date() - mod_date).days) | 6,652 |
def node_constraints_transmission(model):
"""
Constrains e_cap symmetrically for transmission nodes.
"""
m = model.m
# Constraint rules
def c_trans_rule(m, y, x):
y_remote, x_remote = transmission.get_remotes(y, x)
if y_remote in m.y_trans:
return m.e_cap[y, x] == m... | 6,653 |
def plot_mtf(faxis, MTF, labels=None):
"""Plot the MTF. Return the figure reference."""
fig_lineplot = plt.figure()
plt.rc('axes', prop_cycle=PLOT_STYLES)
for i in range(0, MTF.shape[0]):
plt.plot(faxis, MTF[i, :])
plt.xlabel('spatial frequency [cycles/length]')
plt.ylabel('Radial MTF'... | 6,654 |
def make_distributor_init(distributor_init, dll_filename):
"""Create a _distributor_init.py file for the vcomp140.dll.
This file is imported first when importing the
sklearn package so as to pre-load the vendored
vcomp140.dll.
"""
with open(distributor_init, "wt") as f:
f.write(textwrap... | 6,655 |
def forward_ref_structure_hook(context, converter, data, forward_ref):
"""Applied to ForwardRef model and enum annotations
- Map reserved words in json keys to approriate (safe) names in model.
- handle ForwardRef types until github.com/Tinche/cattrs/pull/42/ is fixed
Note: this is the reason we nee... | 6,656 |
def test_slicestim_3d():
"""Test slicing a 3D stimulus into overlapping segments."""
np.random.seed(0)
stim_size = (100, 5, 5)
stim = np.random.randn(*stim_size)
history = 10
sliced_stim = stimulustools.slicestim(stim, history)
assert sliced_stim.ndim == stim.ndim + 1
assert sliced_... | 6,657 |
def cross(x: VariableLike, y: VariableLike) -> VariableLike:
"""Element-wise cross product.
Parameters
----------
x:
Left hand side operand.
y:
Right hand side operand.
Raises
------
scipp.DTypeError
If the dtype of the input is not vector3.
Returns
---... | 6,658 |
def p_dividerchar_spec(p):
"""
dividerchar_spec : DIVIDERCHAR CHAR_PAIRS_QUOTED SEMICOLON
"""
p[0] = DEF.declarations.dividerchar(p[2]) | 6,659 |
def delete(service, name, parent_id=None,
appProperties=defaults.GDRIVE_USE_APPPROPERTIES):
""" Delete a file/folder on Google Drive
Parameters
----------
service : googleapiclient.discovery.Resource
Google API resource for GDrive v3
name : str
Name of file/folder
par... | 6,660 |
def _is_LoginForm_in_this_frame(driver, frame):
""" 判断指定的 frame 中是否有 登录表单 """
driver.switch_to.frame(frame) # 切换进这个 frame
if _is_LoginForm_in_this_page(driver):
return True
else:
driver.switch_to.parent_frame() # 如果没有找到就切换回去
return False | 6,661 |
def parse_range_header(specifier, len_content):
"""Parses a range header into a list of pairs (start, stop)"""
if not specifier or '=' not in specifier:
return []
ranges = []
unit, byte_set = specifier.split('=', 1)
unit = unit.strip().lower()
if unit != "bytes":
return []
... | 6,662 |
def acf(x, lags=None):
""" Computes the empirical autocorralation function.
:param x: array (n,), sequence of data points
:param lags: int, maximum lag to compute the ACF for. If None, this is set to n-1. Default is None.
:return gamma: array (lags,), values of the ACF at lags 0 to lags
"""
... | 6,663 |
def copyInfotainmentServerFiles(tarName, targetId=None):
"""
Stuff the server binary into a tar file
"""
# grab the pre-built binary
osImage = getSetting('osImage', targetId=targetId)
infotainmentBinDir = getBinDir('infotainment-server', targetId=targetId)
cpFilesToBuildDir(infotainmentBinDi... | 6,664 |
def _login(client, user, users):
"""Login user and return url."""
login_user_via_session(client, user=User.query.get(user.id))
return user | 6,665 |
def search(request):
"""renders search page"""
queryset_list = Listing.objects.order_by('-list_date')
if 'keywords' in request.GET:
keywords = request.GET['keywords']
# Checking if its none
if keywords:
queryset_list = queryset_list.filter(
description__... | 6,666 |
def generate_cutout(butler, skymap, ra, dec, band='N708', data_type='deepCoadd',
half_size=10.0 * u.arcsec, psf=True, verbose=False):
"""Generate a single cutout image.
"""
if not isinstance(half_size, u.Quantity):
# Assume that this is in pixel
half_size_pix = int(half_s... | 6,667 |
def main():
""" Main Program """
pygame.init()
# Set the height and width of the screen
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pingwiny z Rovaniemi")
# Create the player
player = Player()
# Create all the levels... | 6,668 |
def get_arraytypes ():
"""pygame.sndarray.get_arraytypes (): return tuple
Gets the array system types currently supported.
Checks, which array system types are available and returns them as a
tuple of strings. The values of the tuple can be used directly in
the use_arraytype () method.
If no ... | 6,669 |
def is_request_authentic(request, secret_token: bytes = conf.WEBHOOK_SECRET_TOKEN):
"""
Examine the given request object to determine if it was sent by an authorized source.
:param request: Request object to examine for authenticity
:type request: :class:`~chalice.app.Request`
:param secret_token: ... | 6,670 |
def verify_convenience_header(folder):
"""
Performs the actual checking of convenience header for specific folder.
Checks that
1) The header even exists
2) That all includes in the header are sorted
3) That there are no duplicated includes
4) That all includes that should be in the header ar... | 6,671 |
def circular_mask_string(centre_ra_dec_posns, aperture_radius="1arcmin"):
"""Get a mask string representing circular apertures about (x,y) tuples"""
mask = ''
if centre_ra_dec_posns is None:
return mask
for coords in centre_ra_dec_posns:
mask += 'circle [ [ {x} , {y}] , {r} ]\n'.format(
... | 6,672 |
def dataset_hdf5(dataset, tmp_path):
"""Make an HDF5 dataset and write it to disk."""
path = str(tmp_path / 'test.h5')
dataset.write_hdf5(path, object_id_itemsize=10)
return path | 6,673 |
def _usage():
"""Print command line usage."""
txt = "[INFO] Usage: %s ldtfile tsfile finalfile" %(sys.argv[0])
txt += " anomaly_gt_prefix climo_gt_prefix LSM yyyymmddhh"
print(txt)
print("[INFO] where:")
print("[INFO] ldtfile: LDT parameter file with full lat/lon data")
print("[INFO] ts... | 6,674 |
def test_exists_calculate_index(
mocked_buckets_hash_map,
): # pylint: disable=redefined-outer-name
"""
GIVEN hash map with mocked _calculate_index and key
WHEN exists is called with the key
THEN _calculate_index is called with the key.
"""
mocked_buckets_hash_map._calculate_index.return_va... | 6,675 |
def _make_indexable(iterable):
"""Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, d... | 6,676 |
def get_all_readers():
"""Get all the readers from the module."""
readers = []
for _, name in getmembers(sys.modules[__name__]):
if isinstance(name, abc.ABCMeta) and name.__name__ != 'Reader':
readers.append(name)
return readers | 6,677 |
def fib_for(n):
"""
Compute Fibonnaci sequence using a for loop
Parameters
----------
n : integer
the nth Fibonnaci number in the sequence
Returns
-------
the nth Fibonnaci number in the sequence
"""
res = [0, 1]
for i in range(n-1):
res.append(res[i] + res... | 6,678 |
def command_factory(command):
"""A factory which returns functions for direct daemon communication.
This factory will create a function which sends a payload to the daemon
and returns the unpickled object which is returned by the daemon.
Args:
command (string): The type of payload this should ... | 6,679 |
def load_prepare_saif_data(threshold=0.25):
"""
Loads and prepares saif's data.
Parameters
----------
threshold : float
Only data with intensities equal to or
above this threshold will be kept (range 0-1).
Returns
-------
DataFrame : pd.DataFrame
Concatenated t... | 6,680 |
def nonmax_suppression(harris_resp, halfwidth=2):
"""
Takes a Harris response from an image, performs nonmax suppression, and outputs the x,y values
of the corners in the image.
:param harris_resp: Harris response for an image which is an array of the same shape as the original image.
:param half... | 6,681 |
def create_credit_request(course_key, provider_id, username):
"""
Initiate a request for credit from a credit provider.
This will return the parameters that the user's browser will need to POST
to the credit provider. It does NOT calculate the signature.
Only users who are eligible for credit (ha... | 6,682 |
def is_valid_project_root(project_root: pathlib.Path) -> bool:
"""Check if the project root is a valid trestle project root."""
if project_root is None or project_root == '' or len(project_root.parts) <= 0:
return False
trestle_dir = pathlib.Path.joinpath(project_root, const.TRESTLE_CONFIG_DIR)
... | 6,683 |
def make_2D_predictions_into_one_hot_4D(prediction_2D, dim):
"""
This method gets 2D prediction of shape (#batch, #kpts)
and then returns 4D one_hot maps of shape
(#batch, #kpts, #dim, #dim)
"""
# getting one_hot maps of predicted locations
# one_hot_maps is of shape (#batch, #kpts, #dim * ... | 6,684 |
def aszarr(path, verbose, remap, flip, host, output):
"""
Convert arbitrary dataset into Zarr dataset format.
If OUTPUT is not specified, it will default to 'SOURCE.zarr'
\f
Args:
path (str): path to the original dataset
verbose (str, optional): how verbose should the logg... | 6,685 |
def checkwritable(val, depth=0):
"""Check whether a value is valid for writing to the database.
If it is, returns nothing. If not, raises TypeError.
This should embody the same logic as BSON.encode(val, check_keys=True).
Why not just use that? Because the BSON class displays this weird
runtime ... | 6,686 |
def delete_user_model(creds: PostgresCredentials, uid: str, model_id: UUID):
"""DB function used to delete user model
from database
Args:
creds (PostgresCredentials): [description]
uid (str): [description]
model_id (UUID): [description]
Returns:
[type]: [description]
... | 6,687 |
def display_code_marginal_densities(codes, num_hist_bins, log_prob=False,
ignore_vals=[], lines=True, overlaid=False, plot_title=""):
"""
Estimates the marginal density of coefficients of a code over some dataset
Parameters
----------
codes : ndarray(float32, size=(D, s))
The codes for a dataset of... | 6,688 |
def distance(a, b):
"""
"""
dimensions = len(a)
_sum = 0
for dimension in range(dimensions):
difference_sq = (a[dimension] - b[dimension]) ** 2
_sum += difference_sq
return sqrt(_sum) | 6,689 |
def is_block(modules):
"""Check if is ResNet building block."""
if isinstance(modules, (BasicBlock, Bottleneck)):
return True
return False | 6,690 |
def playlist_500_fixture():
"""Load payload for playlist 500 and return it."""
return load_fixture("plex/playlist_500.xml") | 6,691 |
def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
for cell in nb.cells:
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
return nb | 6,692 |
async def on_ready():
"""starts AVAX ticker"""
print("joeBot have logged in as {0.user}".format(discord_bot))
TaskManager((AvaxTicker(),)).start() | 6,693 |
def set_current_directory(path):
"""Open a context with specified current directory."""
curdir = os.path.abspath(os.path.curdir)
os.chdir(os.path.abspath(path))
try:
yield
finally:
os.chdir(curdir) | 6,694 |
def get_neighbors_general(status: CachingDataStructure, key: tuple) -> list:
"""
Returns a list of tuples of all coordinates that are direct neighbors,
meaning the index is valid and they are not KNOWN
"""
coords = []
for key in get_direct_neighbour_coords_general(key):
if status.valid_i... | 6,695 |
def transit_params(time):
"""
Dummy transit parameters for time series simulations
Parameters
----------
time: sequence
The time axis of the transit observation
Returns
-------
batman.transitmodel.TransitModel
The transit model
"""
params = batman.TransitParams(... | 6,696 |
def actions(__INPUT):
"""
Regresamos una lista de los posibles movimientos de la matriz
"""
MOVIMIENTOS = []
m = eval(__INPUT)
i = 0
while 0 not in m[i]:
i += 1
# Espacio en blanco (#0)
j = m[i].index(0);
if i > 0:
#ACCION MOVER ARRIBA
m[i][j], m[i-1][j] = m[i-... | 6,697 |
def get_massif_geom(massif: str) -> WKBElement:
"""process to get the massifs geometries:
* go on the meteofrance bra website
* then get the html "area" element
* then convert it to fake GeoJSON (wrong coordinates)
* then open it in qgis.
* Select *all* the geom of the layer.
* rotate -90°... | 6,698 |
def _to_arrow(x):
"""Move data to arrow format"""
if isinstance(x, cudf.DataFrame):
return x.to_arrow()
else:
return pa.Table.from_pandas(x, preserve_index=False) | 6,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.