content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def update_sheet_from_df(sheet: gspread.Spreadsheet, df: pd.DataFrame) -> None:
"""Dump the current dataframe onto the google sheet"""
sheet.update([df.columns.values.tolist()] + df.values.tolist()) | 36,400 |
def extract(fname: Path):
"""Extract the main information from each path entry"""
with fname.open() as f:
sw = json.load(f)
for path, defi in sw["paths"].items():
g = RE_PATH.match(path)
if g is None:
continue
path_match = g.groupdict()
if path_match["wat... | 36,401 |
def greedy_decode(input_sentence, model, next_symbol=next_symbol, tokenize=tokenize, detokenize=detokenize):
"""Greedy decode function.
Args:
input_sentence (string): a sentence or article.
model (trax.layers.combinators.Serial): Transformer model.
Returns:
string: summary of the i... | 36,402 |
def get_browser_errors(driver):
"""
Checks browser for errors, returns a list of errors
:param driver:
:return:
"""
try:
browserlogs = driver.get_log('browser')
except (ValueError, WebDriverException) as e:
# Some browsers does not support getting logs
print(f"Could n... | 36,403 |
def get_user(request, user_id):
"""
Endpoint for profile given a user id.
:param request: session request.
:param user_id: id of user.
:return: 200 - user profile.
401 - login required.
404 - user not found.
"""
try:
get_user = User.objects.get(id=user_id)
... | 36,404 |
def get_file_ext(url):
""" Returns extension of filename of the url or path """
return get_filename(url).split('.')[-1] | 36,405 |
def exists(path):
"""Return True if path exists (value can be ''), False otherwise"""
raise NotImplementedError() | 36,406 |
def weights_save(model, filename, config):
"""Saving the weights of a Keras model instance.
Args:
model (Keras model instance): A Keras model instance.
filename (str): Filename for the weights.
config (Bunch object): The JSON configuration Bunch object.
Returns:
A `.h5` fil... | 36,407 |
def check_records(msg: dict) -> int:
"""
Returns the number of records
sent in the SQS message
"""
records = 0
if msg is not None:
records = len(msg[0])
if records != 1:
raise ValueError("Not expected single record")
return records | 36,408 |
def CalculateVariables(default_variables, params):
"""Calculate additional variables for use in the build (called by gyp)."""
flavor = gyp.common.GetFlavor(params)
if flavor == 'mac':
default_variables.setdefault('OS', 'mac')
default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib')
default_variable... | 36,409 |
def unload_modules(name):
"""Unload all modules where the name begins with the passed name.
"""
for key in list(sys.modules.keys()):
if key.startswith(name):
del sys.modules[key] | 36,410 |
def include(*args, **kwargs):
"""
Used for including Django project settings from multiple files.
Usage::
from split_settings.tools import optional, include
include(
'components/base.py',
'components/database.py',
optional('local_settings.py'),
... | 36,411 |
def incoming(cred):
"""[Opens DB connection with PostgreSQL host='localhost']
Arguments:
cred {[str]} -- [Credentials]
Yields:
[obj] -- [DB connection with PostgreSQL host='localhost']
"""
try:
infile = psycopg2.connect(user='postgres', password=cred[1], host='local... | 36,412 |
def get_processes_from_tags(test):
"""Extract process slugs from tags."""
tags = getattr(test, 'tags', set())
slugs = set()
for tag_name in tags:
if not tag_name.startswith('{}.'.format(TAG_PROCESS)):
continue
slugs.add(tag_name[len(TAG_PROCESS) + 1:])
return slugs | 36,413 |
def get_best_score(version):
"""
Given an existing version, retrieves the alias and score of the best score obtained
:param version: version to be evaluated (str|unicode)
:return: alias, score (str, float)
"""
logger = logging.getLogger(__name__)
logger.info("Request best submission evaluati... | 36,414 |
def eight_ball():
""" Magic eight ball.
:return: A random answer.
:rtype: str
"""
answers = [
'It is certain', 'It is decidedly so', 'Not a fucking chance!', 'without a doubt', 'Yes definitely',
'I suppose so', 'Maybe', ' No fucking way!', 'Sure :D', 'hahahaha no you... | 36,415 |
def head(line, n: int):
"""returns the first `n` lines"""
global counter
counter += 1
if counter > n:
raise cbox.Stop() # can also raise StopIteration()
return line | 36,416 |
def reconstruction(datafile, **kwargs):
"""
Reconstructs the image in datafile according to given parameters. The results: image.npy, support.npy, and
errors.npy are saved in 'saved_dir' defined in kwargs, or if not defined, in the directory of datafile.
Parameters
----------
datafile : str
... | 36,417 |
def onehot(x, numclasses=None):
""" Convert integer encoding for class-labels (starting with 0 !)
to one-hot encoding.
If numclasses (the number of classes) is not provided, it is assumed
to be equal to the largest class index occuring in the labels-array + 1.
The output is an array... | 36,418 |
def draw_graph(image, graph):
"""
Draw the graph on the image by traversing the graph structure.
Args:
| *image* : the image where the graph needs to be drawn
| *graph* : the *.txt file containing the graph information
Returns:
"""
tmp = draw_edges(image, graph)
node_size ... | 36,419 |
def valid_octet (oct):
""" Validates a single IP address octet.
Args:
oct (int): The octet to validate
Returns:
bool: True if the octet is valid, otherwise false
"""
return oct >= 0 and oct <= 255 | 36,420 |
def main():
"""
Execute the program from the command line
"""
main_help = ("Main program for motif finding. Provide a query file and "
"optional motif file(s) with the -m argument")
parser = argparse.ArgumentParser(prog='motiffinder', description=main_help)
parser.add_argument('... | 36,421 |
def load_clean_dictionaries():
"""
is loading the combilex data into two dictionaries
word2phone and phone2word
:return: g2p_dict, p2g_dict
"""
grapheme_dict = {}
phonetic_dict = {}
with open(COMBILEX_PATH, encoding='utf-8') as combilex_file:
for line in combilex_file:
... | 36,422 |
def build_missing_wheels(
packages_and_envts,
build_remotely=False,
with_deps=False,
dest_dir=THIRDPARTY_DIR,
):
"""
Build all wheels in a list of tuple (Package, Environment) and save in
`dest_dir`. Return a list of tuple (Package, Environment), and a list of
built wheel filenames.
... | 36,423 |
def load_reads(path, format='bed', paired=False, shift=100, name=None):
"""Read reads from file.
Parameters
----------
path : str
Path to load the reads.
format : str, optional
File format, default='bed'.
paired : bool, optional
Whether the reads are paired-end or not, d... | 36,424 |
def sketch_blocks(modulepaths, pkg_dirs):
"""Creates a graph of all the modules in `modulepaths` that are related to each other by their
imports. The directories used to resolve an import is `pkg_dirs`
Args:
modulepaths (List[str]): list of modules filepaths to analyze.
pkg_dirs (List[str])... | 36,425 |
def str_to_bool(string):
"""
Parses string into boolean
"""
string = string.lower()
return True if string == "true" or string == "yes" else False | 36,426 |
def rerotateExtremaPoints(minSepPoints_x, minSepPoints_y, maxSepPoints_x, maxSepPoints_y,\
lminSepPoints_x, lminSepPoints_y, lmaxSepPoints_x, lmaxSepPoints_y,\
Phi, Op, yrealAllRealInds):
""" Rotate the extrema points from (the projected ellipse centered at the origin
and x-axis aligned with semi-major ... | 36,427 |
def test_approve_transfer(custom_token: Contract, get_accounts: Callable) -> None:
""" Use the approve() function of the custom token contract """
(A, B) = get_accounts(2)
token = custom_token
call_and_transact(token.functions.mint(50), {"from": A})
initial_balance_A = token.functions.balanceOf(A).... | 36,428 |
def does_name_exist(name):
""" check if a file with that name already exists """
return len(glob.glob('./photos/'+name+'.*')) > 0 | 36,429 |
def cont_hires(npoints, elecs, start_timestamp=0):
"""
Retrieve hires data (sampled at 2 kHz).
Parameters and outputs are the same as the `cont_raw` function.
Args:
npoints: number of datapoints to retrieve
elecs: list of electrodes to sample
start_timestamp: NIP timestamp to s... | 36,430 |
def batch_grid_subsampling_kpconv_gpu(points, batches_len, features=None, labels=None, sampleDl=0.1, max_p=0):
"""
Same as batch_grid_subsampling, but implemented in GPU. This is a hack by using Minkowski
engine's sparse quantization functions
Note: This function is not deterministic and may return subs... | 36,431 |
def eval_wili(result_file: str, config: str) -> None:
"""
CLI function evaluating the classifier on WiLI.
Parameters
----------
result_file : str
Path to a file where the results will be stored
config : str
Path to a configuration file for the classifier
"""
globals()["c... | 36,432 |
def myPrint(fk, gk_norm, orcl, iters, tmk,
alphak=0, iterLS=0, iterSolver=0, rel_res=0):
"""
A print function for every iteration.
"""
if iters%(num_every_print*10) == 0:
prthead1 = ' iters iterSolver iterLS Time f ||g||'
prthead2 = ' alphak P... | 36,433 |
def hot_word_detection(lang='en'):
"""
Hot word (wake word / background listen) detection
What is Hot word detection?
ANSWER: Hot word listens for specific key words chosen to activate the “OK Google” voice interface. ...
Voice interfaces use speech recognition technologies to allow user input throu... | 36,434 |
def parse_ph5_length(length):
"""
Method for parsing length argument.
:param length: length
:type: str, numeric, or None
:returns: length value as a float
:type: float or None
"""
err_msg = "Invalid length value. %s" % (length)
return str_to_pos_float(length, err_msg) | 36,435 |
def _generate(payload: ModelSpec, is_udf: bool = True):
"""Construct a UDF to run pytorch model.
Parameters
----------
payload : ModelSpec
the model specifications object
Returns
-------
A Spark Pandas UDF.
"""
model = payload.model_type
default_device = "gpu" if torch.... | 36,436 |
def test_receipt_revalidate_without_receipt_number():
"""Test revalidation process of an invalid receipt. (Receipt without number)"""
factories.PointOfSalesFactory()
receipt = factories.ReceiptWithVatAndTaxFactory()
receipt.refresh_from_db()
validation = receipt.revalidate()
assert validation ... | 36,437 |
def check_proper_torsion(
torsion: Tuple[int, int, int, int], molecule: "Ligand"
) -> bool:
"""
Check that the given torsion is valid for the molecule graph.
"""
for i in range(3):
try:
_ = molecule.get_bond_between(
atom1_index=torsion[i], atom2_index=torsion[i +... | 36,438 |
def find_all_occurrences_and_indexes(seq):
"""
seq: array-like of pretty_midi Note
Finds all patterns and indexes of those patterns.
"""
list_patterns = list()
list_indexes = list()
res = list()
seq_x = seq
while res!=None:
seq_x, res, indexes = find_occurrences_and_inde... | 36,439 |
def get_drn(blocks,
simplified=False,
model_name=None,
pretrained=False,
root=os.path.join('~', '.chainer', 'models'),
**kwargs):
"""
Create DRN-C or DRN-D model with specific parameters.
Parameters:
----------
blocks : int
Number ... | 36,440 |
def get_uas_volume_admin(volume_id):
"""Get volume info for volume ID
Get volume info for volume_id
:param volume_id:
:type volume_id: str
:rtype: AdminVolume
"""
if not volume_id:
return "Must provide volume_id to get."
return UasManager().get_volume(volume_id=volume_id) | 36,441 |
def draw(canvas):
"""
Draw a ship image several times.
:param canvas: simpleguics2pygame.Canvas or simplegui.Canvas
"""
canvas.draw_line((0, 0), (WIDTH - 1, HEIGHT - 1), 1, 'Blue')
canvas.draw_line((0, HEIGHT - 1), (WIDTH, 0), 1, 'Blue')
img = loader.get_image('double_ship')
# The com... | 36,442 |
def cyclic_learning_rate(global_step,
learning_rate=0.01,
max_lr=0.1,
step_size=50000.,
gamma=0.99994,
max_steps=100000.,
scale_rate=0.9,
mode='t... | 36,443 |
def getElementsOnFirstLevelExceptTag(parent, element):
"""Return all elements below *parent* except for the ones tagged *element*.
:param parent: the parent dom object
:param elemnt: the tag-name of elements **not** to return
"""
elements = []
children = getElements(parent)
for c in childre... | 36,444 |
def run_and_schedule(characters, notifications_job):
"""
Runs a job immediately to avoid having to wait for the delay to end,
and schedules the job to be run continuously.
"""
notifications_job()
schedule.every(notification_caching_timer/len(characters)).minutes.do(notifications_job) | 36,445 |
def show(ctx: Context, output: str, maphandlers: list[str], query: list[str]):
"""Show matching rengu objects"""
out = output_handler(output)
store = storage_handler(ctx.obj["baseuri"])
q = store.query(query, with_data=True)
for x in q:
if output.startswith("list"):
out(x)
... | 36,446 |
def get_first_child_element(node, tag_name):
"""Get the first child element node with a given tag name.
:param node: Parent node.
:type node: xml.dom.Node
:returns: the first child element node with the given tag name.
:rtype: xml.dom.Node
:raises NodeNotFoundError:
if no child node wit... | 36,447 |
def parse_iso(filename='iso.log'):
""" parse the isotropy output file
Args:
filename: the isotropy output file name
Returns:
lname: list of irreps
lpt: list of atom coordinate
lpv: list of distortion vectors, might be multi-dimensional
"""
#read in the isotropy out... | 36,448 |
def revoke_database(cursor: Cursor, user: str, db: str) -> Result:
"""
Remove any permissions for the user to create, manage and delete this database.
"""
db = db.replace("%", "%%")
return Result(_truthy(query(cursor, _format("REVOKE ALL ON {}.* FROM %s@'%%'", db), user))) | 36,449 |
def write_benchmark_csv(file_out, benchmark_result, benchmark, test_config=TestConfig()):
""" Writes benchmark to file as csv """
writer = csv.writer(file_out)
writer.writerow(('Benchmark', benchmark_result.name))
writer.writerow(('Benchmark Group', benchmark_result.group))
writer.writerow(('Failure... | 36,450 |
def write_image(folder, image):
""" Writes image to directory
Args:
param1: path to image folder
param2: image
"""
coil1_img = sitk.GetImageFromArray(image)
castFilter = sitk.CastImageFilter()
castFilter.SetOutputPixelType(sitk.sitkUInt16)
corrupted_img = castF... | 36,451 |
def get_and_parse(p_inqueue, p_outqueue, p_process, p_counters, p_log_queue, p_log_level, p_formatter, **kwargs):
"""
Gets doc from an input queue, applies transformation according to p_process function,
then pushes the so produced new doc into an output queue
p_process must take a "doc" as... | 36,452 |
def get_ex1():
"""Loads array A for example 1 and its TruncatedSVD with top 10 components
Uk, Sk, Vk = argmin || A - Uk*diag(Sk)*Vk||
Over;
Uk, Sk, Vk
Where;
Uk is a Orthonormal Matrix of size (20000, 10)
Sk is a 10 dimensional non-negative vector
Vk is a Orthonormal Matrix of size (1... | 36,453 |
async def to_code(config):
"""Code generation entry point"""
var = await tion_lt.setup_tion_lt(config)
await tion.setup_switch(config, CONF_RECIRCULATION, var.set_recirculation, var) | 36,454 |
def render_variable(context: 'Context', raw: Any):
"""
Render the raw input. Does recursion with dict and list inputs, otherwise renders
string.
:param raw: The value to be rendered.
:return: The rendered value as literal type.
"""
if raw is None:
return None
elif isinstance(raw... | 36,455 |
def resolve_ssh_config(ssh_config_file: str) -> str:
"""
Resolve ssh configuration file from provided string
If provided string is empty (`""`) try to resolve system ssh config files located at
`~/.ssh/config` or `/etc/ssh/ssh_config`.
Args:
ssh_config_file: string representation of ssh co... | 36,456 |
def check_kafka_rest_ready(host, port, service_timeout):
"""Waits for Kafka REST Proxy to be ready.
Args:
host: Hostname where Kafka REST Proxy is hosted.
port: Kafka REST Proxy port.
timeout: Time in secs to wait for the service to be available.
Returns:
False, if the time... | 36,457 |
def is_p2wpkh_output(cscript: CScript) -> bool:
"""Checks if the output script if of the form:
OP_0 <pubkey hash>
:param script: Script to be analyzed.
:type script: CScript
:return: True if the passed in bitcoin CScript is a p2wpkh output script.
:rtype: bool
"""
if len(cscript... | 36,458 |
def check_update_needed(db_table_object, repository_name, pushed_at):
"""
Returns True if there is a need to clone the github repository
"""
logger.info(f"This is the repo name from check_update <<{repository_name}>> and db_table <<{db_table_object}>>")
result = get_single_repository(db_table_object... | 36,459 |
def raise_(error: Type[ErrorImitation], name, text):
"""
Used to raise an ErrorImitation with more flexibility.
"""
error.__raise__(error(name, text)) | 36,460 |
def return_one(result):
"""return one statement"""
return " return " + result | 36,461 |
def inv(a):
"""The inverse rotation"""
return -a | 36,462 |
def wrapCopy(object):
"""Wrap a copy of the object."""
from App import Proxys
return eval( serialize(object), Proxys.__dict__ ) | 36,463 |
def return_edges(paths, config, bidirectional=False):
"""
Makes graph edges from osm paths
:param paths: dictionary {osm_way_id: {osmid: x, nodes:[a,b], osmtags: vals}}
:param config: genet.inputs_handler.osm_reader.Config object
:param bidirectional: bool value if True, reads all paths as both ways... | 36,464 |
def pi_eq_func(ylag,pilag,v,s,slag,alpha,h,b,phi,gamma):
""" equilibrium value for inflation
Args:
ylag (float): lagged output
pilag (float): lagged inflation
v (float): demand disturbance
s (float): supply disturbance
slag (float): lagged supply disturbance
alp... | 36,465 |
def set_mode(vehicle, mode):
"""
Set the vehicle's flight modes. 200ms period state validation.
Args:
vehicle(dronekit.Vehicle): the vehicle to be controlled.
mode(str): flight mode string, supported by the firmware.
Returns:
bool: True if success, False if failed. ... | 36,466 |
def apply_parallel(data_frame, num_procs, func, *args, progress_bar=False, backend='loky'):
""" This function parallelizes applying a function to the rows of a data frame using the
joblib library. The function is called on each row individually.
This function is best used when func does not have mu... | 36,467 |
def _setdoc(super): # @ReservedAssignment
"""This inherits the docs on the current class. Not really needed for Python 3.5,
due to new behavior of inspect.getdoc, but still doesn't hurt."""
def deco(func):
func.__doc__ = getattr(getattr(super, func.__name__, None), "__doc__", None)
return ... | 36,468 |
def test_module(client: Client) -> str:
"""Tests API connectivity and authentication'
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:type client: ``Client``
:param Client: client t... | 36,469 |
def migrate_v8_to_v9(metadata, data, *args): # pylint: disable=unused-argument
"""Migration of archive files from v0.8 to v0.9."""
old_version = '0.8'
new_version = '0.9'
verify_metadata_version(metadata, old_version)
update_metadata(metadata, new_version)
# Apply migrations
migration_dbg... | 36,470 |
def warns(message, category=None):
"""警告装饰器
:param message: 警告信息
:param category: 警告类型:默认是None
:return: 装饰函数的对象
"""
def _(func):
@functools.wraps(func)
def warp(*args, **kwargs):
warnings.warn(message, category, stacklevel=2)
return func(*args, **kwargs)... | 36,471 |
def handle_exceptions(func) -> object:
"""
This is needed since pytube current version is
quite unstable and can raise some unexpected errors.
"""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except KeyError as e:
window.s_append('An error... | 36,472 |
def templated_sequence_component(location_descriptor_tpm3):
"""Create test fixture for templated sequence component"""
params = {
"component_type": "templated_sequence",
"region": location_descriptor_tpm3.dict(exclude_none=True),
"strand": "+"
}
return TemplatedSequenceComponent(... | 36,473 |
def _SetupOutputDir():
"""Setup output directory."""
if os.path.exists(OUTPUT_DIR):
shutil.rmtree(OUTPUT_DIR)
# Creates |OUTPUT_DIR| and its platform sub-directory.
os.makedirs(coverage_utils.GetCoverageReportRootDirPath(OUTPUT_DIR)) | 36,474 |
def joint_probability(people, one_gene, two_genes, have_trait):
"""
Compute and return a joint probability.
The probability returned should be the probability that
* everyone in set `one_gene` has one copy of the gene, and
* everyone in set `two_genes` has two copies of the gene, and
... | 36,475 |
def _is_child_path(path, parent_path, link_name=None):
""" Checks that path is a path within the parent_path specified. """
b_path = to_bytes(path, errors='surrogate_or_strict')
if link_name and not os.path.isabs(b_path):
# If link_name is specified, path is the source of the link and we need to re... | 36,476 |
def data_to_mindrecord_byte_image(image_files, image_anno_dict, dst_dir, prefix="cptn_mlt.mindrecord", file_num=1):
"""Create MindRecord file."""
mindrecord_path = os.path.join(dst_dir, prefix)
writer = FileWriter(mindrecord_path, file_num)
ctpn_json = {
"image": {"type": "bytes"},
"ann... | 36,477 |
def main():
"""The main progam."""
parser = argparse.ArgumentParser(
prog="mirror-gcode.py",
usage="%(prog)s [options] gcode-file",
description="Mirrors a gcode file in the X-axis about the origin"
)
parser.add_argument(
"-d", "--debug",
dest="debug",
acti... | 36,478 |
def zip(folder_name, files_to_be_zipped):
"""Creates a zip object from folder_name and zips a list of files (files_to_be_zipped)"""
# creates the zipped folder, D'OH
zip_file_name = folder_name + '.zip'
if type(files_to_be_zipped) != type([]):
files_to_be_zipped = [files_to_be_zipped]
wit... | 36,479 |
def rf_predict_img_win(win_arr, trained_classifier, prob=True):
"""Predict image window using input trained classifier.
Args:
win_arr (numpy.arr): In rasterio order (channels, y, x)
trained_classifier (sklearn.model): Trained sklearn model to use for predictions.
prob (bool, optional): ... | 36,480 |
def get_schema(passed_schema: 'Schema' = None, _cached_schema: Dict[str, Schema] = {}) -> 'Schema':
"""If passed a schema (not None) it returns it. If passed none,
it checks if the default schema has been initialized. If not
initialized, it initializes it. Then it returns the default schema."""
if pass... | 36,481 |
def print_ops():
""" Helper to print what operations exists in the frozen model"""
for op in graph.get_operations():
print(op.name) | 36,482 |
def run(context, id_, **kwargs):
""" Run test steps. """
# Initialize
run = tmt.Run(id_, context.obj.tree, context=context)
context.obj.run = run | 36,483 |
def ShowIPC(cmd_args=None):
""" Routine to print data for the given IPC space
Usage: showipc <address of ipc space>
"""
if not cmd_args:
print "No arguments passed"
print ShowIPC.__doc__
return False
ipc = kern.GetValueFromAddress(cmd_args[0], 'ipc_space *')
if not... | 36,484 |
def dqn(env, n_episodes=1001, max_t=1000 * FRAME_SKIP, eps_start=1.0,
eps_end=0.001, eps_decay=0.995, solution_threshold=13.0,
checkpointfn='checkpoint.pth', load_checkpoint=False,
reload_every=None):
"""Function that uses Deep Q Networks to learn environments.
Parameters
----------... | 36,485 |
def get_mesh_faces(edge_array):
"""
Uses an edge array of mesh to generate the faces of the mesh. For each triangle in the mesh this returns the list of indices
contained in it as a tuple (index1, index2, index3)
"""
triangles = []
neibs = neibs_from_edges(edge_array)
for edge in ... | 36,486 |
def lc_list(aws_config=None):
"""
@type aws_config: Config
"""
asg_client = get_client(client_type='autoscaling', config=aws_config)
all_lcs = asg_client.describe_launch_configurations().get('LaunchConfigurations')
if all_lcs:
output_lc_list(lc_list=all_lcs)
else:
exit("No la... | 36,487 |
def test_getitem(preston):
"""
Test getting an item by an index instead of attribute.
"""
assert preston.bloodlines().items[0].race() | 36,488 |
def _make_attribution_from_nodes(mol: Mol, nodes: np.ndarray,
global_vec: np.ndarray) -> GraphsTuple:
"""Makes an attribution from node information."""
senders, receivers = _get_mol_sender_receivers(mol)
data_dict = {
'nodes': nodes.astype(np.float32),
'sende... | 36,489 |
def test_upload_call_error(emitter, store_mock, config, tmp_path):
"""Simple upload but with a response indicating an error."""
errors = [
Error(message="text 1", code="missing-stuff"),
Error(message="other long error text", code="broken"),
]
store_response = Uploaded(ok=False, status=40... | 36,490 |
def subrepo(repo, subset, x):
"""Changesets that add, modify or remove the given subrepo. If no subrepo
pattern is named, any subrepo changes are returned.
"""
# i18n: "subrepo" is a keyword
args = getargs(x, 0, 1, _('subrepo takes at most one argument'))
pat = None
if len(args) != 0:
... | 36,491 |
def format_output(item, show_url=False):
""" takes a voat post and returns a formatted string """
if not item["Title"]:
item["Title"] = formatting.truncate(item["Linkdescription"], 70)
else:
item["Title"] = formatting.truncate(item["Title"], 70)
item["link"] = voat_fill_url.format(item["... | 36,492 |
def get_compiled_table_name(engine, schema, table_name):
"""Returns a table name quoted in the manner that SQLAlchemy would use to query the table
Args:
engine (sqlalchemy.engine.Engine):
schema (str, optional): The schema name for the table
table_name (str): The name of the table
... | 36,493 |
def build(filepath):
"""Returns the window with the popup content."""
ttitlebar = titlebar.build()
hheading = heading.build(HEADING_TITLE)
top_txt_filler = fillers.horizontal_filler(2, colors.BACKGROUND)
message = sg.Text(
text=MESSAGE_TEXT + filepath,
font=MESSAGE_FONT,
te... | 36,494 |
def format_float(digit=0, is_pct=False):
"""
Number display format for pandas
Args:
digit: number of digits to keep
if negative, add one space in front of positive pct
is_pct: % display
Returns:
lambda function to format floats
Examples:
>>> format_f... | 36,495 |
def updateTable(cur,tablename,types=None,mode="results",verbose=True):
"""
Create a table if it does not exist, or update the table if it does.
"""
# If the table does not exist, create it
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [r[0] for r in cur.fetchall()]
... | 36,496 |
def get_overexpressed_genes(
matrix: ExpMatrix, cell_labels: pd.Series,
exp_thresh: float = 0.05, ignore_outliers: bool = True,
num_genes: int = 20) -> pd.DataFrame:
"""Determine most over-expressed genes for each cluster."""
# make sure matrix and cell_labels are aligned
matrix = m... | 36,497 |
def printMenu():
"""
Prints the menu
"""
print()
print("Main Menu")
print("*********************")
print()
print("Please select an option:")
print()
print("1 - Run search")
print("2 - Export results")
print("3 - Export result archive")
print("4 - View all settings")
print("5 - Update API key")
prin... | 36,498 |
def stream_fasta(fastafile):
"""
Stream a fasta file, one read at a time. Saves memory!
Originally part of the roblib libary.
:param fastafile: The fasta file to stream
:type fastafile: str
:param whole_id: Whether to return the whole id (default) or just up to the first white space
:type w... | 36,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.