content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def cleanup(number_of_days, path, pattern=".*", delete=True):
"""
Removes files from the passed in path that are older than or equal
to the number_of_days
"""
logger.info("Running cleanup with params: days:{},path: {}, pattern: {},delete:{}".format(number_of_days, path, pattern, delete))
time_i... | 5,340,500 |
def primitive_name(method_name):
"""Given a method_name, returns the corresponding Phylanx primitive.
This primarily used for mapping NumPy mapped_methods to Phylanx primitives,
but there are also other functions in python that would map to primitives
with different name in Phylanx, e.g., `print` is ma... | 5,340,501 |
def _split_pandas_data_with_ratios(data, ratios, seed=SEED, shuffle=False):
"""Helper function to split pandas DataFrame with given ratios
Note:
Implementation referenced from `this source
<https://stackoverflow.com/questions/38250710/how-to-split-data-into-3-sets-train-validation-and-test>`_.
... | 5,340,502 |
def get_stock_information(stock, country, as_json=False):
"""
This function retrieves fundamental financial information from the specified stock. The retrieved
information from the stock can be valuable as it is additional information that can be used combined
with OHLC values, so to determine financial... | 5,340,503 |
def manual_run_change_reporter(accounts):
"""Manual change reporting from the command line"""
app.logger.info("[ ] Executing manual change reporter task...")
try:
for account in accounts:
time1 = time.time()
rep = Reporter(account=account)
for monitor in rep.all... | 5,340,504 |
def check_export_start_date(export_start_dates, export_end_dates,
export_day_range):
"""
Update export_start_date according to the export_end_date so that it could be export_end_date - EXPORT_DAY_RANGE.
Parameters:
export_start_date: dict
Read from params, va... | 5,340,505 |
def set_verbosity(module_name: str, verbose: bool = False, very_verbose: bool = False) -> logging.Logger:
"""
Used to set the verbosity of the logger.
:param module_name: Name of the module, e.g. ``__name__``.
:type module_name: str
:param verbose: Enables DEBUG level.
:type verbose: bool
:p... | 5,340,506 |
def openie6_run(document_file, output, config=NLP_CONFIG, no_entity_filter=False):
"""
Initializes OpenIE6. Will generate the corresponding input file, reads the output and converts it to our
internal OpenIE format
:param document_file: input file with documents to generate
:param output: the output... | 5,340,507 |
def walk_attrs(module: ModuleType, attr_name, converter=Converter()) -> str:
"""
Create stubs for given class, including all attributes.
:param module:
:param attr_name:
:param converter:
:return:
"""
buf = StringList(convert_indents=True)
buf.indent_type = " "
if not is_dunder(attr_name):
obj = geta... | 5,340,508 |
def reformat_adata(
adata: AnnData, brain_region: str, num_seq_lanes: int, transgenes_list: str
):
"""
script that takes in user specified inputs in the data_reformat script
transforms dataframe input to usable AnnData output with group cell count labels,
df_obs
it also makes genes in the index... | 5,340,509 |
def chunks(list_, num_items):
"""break list_ into n-sized chunks..."""
results = []
for i in range(0, len(list_), num_items):
results.append(list_[i:i+num_items])
return results | 5,340,510 |
def form_requires_input(form):
"""
Returns True if the form has at least one question that requires input
"""
for question in form.get_questions([]):
if question["tag"] not in ("trigger", "label", "hidden"):
return True
return False | 5,340,511 |
def read_dino_waterlvl_csv(fname, to_mnap=True, read_series=True):
"""Read dino waterlevel data from a dinoloket csv file.
Parameters
----------
fname : str
to_mnap : boolean, optional
if True a column with 'stand_m_tov_nap' is added to the dataframe
read_series : boolean, optional
... | 5,340,512 |
def random_range():
"""
Test 100 values and put them into ipbin.
"""
numbers_to_test = 100
integer_space = 4294967295.0
list_of_bins = []
for _ in range(numbers_to_test):
multiple = random.random()
value = multiple * integer_space
ipbin = encode(value)
list_of... | 5,340,513 |
def on_same_fs(request):
"""
Accept a POST request to check access to a FS available by a client.
:param request:
`django.http.HttpRequest` object, containing mandatory parameters
filename and checksum.
"""
filename = request.POST['filename']
checksum_in = request.POST['checksum... | 5,340,514 |
def get_memo(expense_group: ExpenseGroup, payment_type: str=None) -> str:
"""
Get the memo from the description of the expense group.
:param expense_group: The expense group to get the memo from.
:param payment_type: The payment type to use in the memo.
:return: The memo.
"""
expense_fund_so... | 5,340,515 |
def get_prefix_for_google_proxy_groups():
"""
Return a string prefix for Google proxy groups based on configuration.
Returns:
str: prefix for proxy groups
"""
prefix = config.get("GOOGLE_GROUP_PREFIX")
if not prefix:
raise NotSupported(
"GOOGLE_GROUP_PREFIX must be s... | 5,340,516 |
def client(tmpdir):
"""Test client for the API."""
tmpdir.chdir()
views.app.catchall = False
return webtest.TestApp(views.app) | 5,340,517 |
def print(*args, **kwargs) -> None:
"""Shadows python print method in order to use typer.echo instead."""
typer.echo(*args, **kwargs) | 5,340,518 |
def list_extract(items, arg):
"""Extract items from a list of containers
Uses Django template lookup rules: tries list index / dict key lookup first, then
tries to getattr. If the result is callable, calls with no arguments and uses the return
value..
Usage: {{ list_of_lists|list_extract:1 }} (get... | 5,340,519 |
def get_links(url):
"""Scan the text for http URLs and return a set
of URLs found, without duplicates"""
# look for any http URL in the page
links = set()
text = get_page(url)
soup = BeautifulSoup(text, "lxml")
for link in soup.find_all('a'):
if 'href' in link.attrs:
n... | 5,340,520 |
def get_merkle_root(*leaves: Tuple[str]) -> MerkleNode:
"""Builds a Merkle tree and returns the root given some leaf values."""
if len(leaves) % 2 == 1:
leaves = leaves + (leaves[-1],)
def find_root(nodes):
newlevel = [
MerkleNode(sha256d(i1.val + i2.val), children=[i1, i2])
... | 5,340,521 |
def BeginBlock(layer_to_call: torch.nn.Module,
user_id: str = None,
ipu_id: int = None) -> torch.nn.Module:
"""
Define a block by modifying an existing PyTorch module.
You can use this with an existing PyTorch module instance, as follows:
>>> poptorch.BeginBlock(myModel.a... | 5,340,522 |
def set_attrs_via_get(obj, attr_names):
"""Sets attrs `attrs` for `obj` by sending a GET request."""
retrieved_obj = get_obj(obj)
for attr_name in attr_names:
retrieved_attr_value = getattr(retrieved_obj, attr_name)
setattr(obj, attr_name, retrieved_attr_value) | 5,340,523 |
def print_samples_of_text_by_label(labeled_text, num_labels, num_samples):
"""Print random sample of documents from each label
Parameters
----------
labeled_text : pandas.DataFrame
Rows are documents, should have 'text' column and 'label' column
num_labels : int
Number of labels... | 5,340,524 |
def unbatch_nested_tensor(nested_tensor):
"""Squeeze the first (batch) dimension of each entry in ``nested_tensor``."""
return map_structure(lambda x: torch.squeeze(x, dim=0), nested_tensor) | 5,340,525 |
def DLXCPP(rows):
"""
Solves the Exact Cover problem by using the Dancing Links algorithm
described by Knuth.
Consider a matrix M with entries of 0 and 1, and compute a subset
of the rows of this matrix which sum to the vector of all 1's.
The dancing links algorithm works particularly well for... | 5,340,526 |
def row2dict(cursor, row):
""" タプル型の行データを辞書型に変換
@param cursor: カーソルオブジェクト
@param row: 行データ(tuple)
@return: 行データ(dict)
@see: http://docs.python.jp/3.3/library/sqlite3.html
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | 5,340,527 |
def test_correct_auth_post(operation, test_client, constants, put_allowed_class_names,
headers_with_correct_pass_and_id):
"""
GIVEN a Flask application
WHEN a collection endpoint has a PUT request with correct user credentials
THEN check that a '401' status code is not returne... | 5,340,528 |
def merge(left, right):
"""this is used for merging two halves """
# print('inside Merge ')
result = [];
leftIndex = 0;
rightIndex = 0;
while leftIndex < len(left) and rightIndex < len(right):
if left[leftIndex] < right[rightIndex]:
result.append(left[leftIndex])
... | 5,340,529 |
def parse_query(query):
"""Parse the given query, returning a tuple of strings list (include, exclude)."""
exclude = re.compile(r'(?<=-")[^"]+?(?=")|(?<=-)\w+').findall(query)
for w in sorted(exclude, key=lambda i: len(i), reverse=True):
query = query.replace(w, '')
query = " " + query
retur... | 5,340,530 |
def _m_verify_mg(state, method_name, multigoal, depth, verbose=0):
"""
Pyhop 2 uses this method to check whether a multigoal-method has achieved
the multigoal that it promised to achieve.
"""
goal_dict = _goals_not_achieved(state,multigoal)
if goal_dict:
raise Exception(f"depth {depth}: ... | 5,340,531 |
def eggs_attribute_decorator(eggs_style):
"""Applies the eggs style attribute to the function"""
def decorator(f):
f.eggs = eggs_style
@wraps(f)
def decorated_function(*args, **kwargs):
return f(*args, **kwargs)
return decorated_function
return decorator | 5,340,532 |
def byte_size(num, suffix='B'):
"""
Return a formatted string indicating the size in bytes, with the proper
unit, e.g. KB, MB, GB, TB, etc.
:arg num: The number of byte
:arg suffix: An arbitrary suffix, like `Bytes`
:rtype: float
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
... | 5,340,533 |
def cdsCoverage(genome_coverage, dict_cds, datatype, coverage):
"""Return Mean Coverage or Raw Counts for each CDS, or their promotor regions for tss and chip"""
genome_coverage = [map(int, genome_coverage[0]), map(int, genome_coverage[1])]
# CDS coverage is calculated from genome coverage on the entire gen... | 5,340,534 |
def div88():
"""
Returns the divider ZZZZZZZZZZZZ
:return: divider88
"""
return divider88 | 5,340,535 |
def laplace_noise(epsilon, shape, dtype, args):
"""
Similar to foolbox but batched version.
:param epsilon: strength of the noise
:param bounds: min max for images
:param shape: the output shape
:param dtype: the output type
:return: the noise for images
"""
scale = epsilon / np.sqrt... | 5,340,536 |
async def forecast(ctx, *args):
"""Reply sender with forecast."""
await forecast_controller(ctx, format_darksky_forecast, *args) | 5,340,537 |
def while_u():
""" Lower case Alphabet letter 'u' pattern using Python while loop"""
row = 0
while row<4:
col = 0
while col<4:
if col%3==0 and row<3 or row==3 and col>0:
print('*', end = ' ')
... | 5,340,538 |
def import_by_path(dotted_path, error_prefix=''):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImproperlyConfigured if something goes wrong.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
... | 5,340,539 |
def test_group_advanced_true_invisible_false_field_advanced_true_invisible_true_active_true(
sdk_client_fs: ADCMClient, path, app, login):
"""Field invisible
:param sdk_client_fs:
:param path:
:param app:
:param login:
:return:
"""
bundle = sdk_client_fs.upload_from_fs(path)
... | 5,340,540 |
def grid_convergence(lat, lon, radians=False):
"""
Given the latitude and longitude of a position, calculate the grid convergence
Args:
lat: latitude (degrees or radians)
lon: longitude (degrees or radians)
radians: true if lat/lon in radians
Returns: gamma, the grid convergence... | 5,340,541 |
def _make_index_item(resource_type):
""" """
id_prefix = "2c1|"
uuid_ = uuid.uuid4().hex
tpl = {
"access_roles": [
"guillotina.Reader",
"guillotina.Reviewer",
"guillotina.Owner",
"guillotina.Editor",
"guillotina.ContainerAdmin",
... | 5,340,542 |
def mol_to_graph(mol):
"""
Converts Mol object to a graph compatible with Pytorch-Geometric
Args:
mol (Mol): RDKit Mol object
Returns:
node_feats (LongTensor): features for each node, one-hot encoded by element
edge_feats (LongTensor): features for each node, one-hot encoded by... | 5,340,543 |
def _tournament(evaluated_population: List[Eval], tournament_size: int = 5,
previous_winner: Chromosome = None) -> Chromosome:
"""Selects tournament_size number of chromosomes to 'compete' against each other. The chromosome with the highest
fitness score 'wins' the tournament.
Params:
... | 5,340,544 |
def interpolate_drift_table(table, start=0, skip=0, smooth=10):
"""
Smooth and interpolate a table
:param table: fxyz (nm) array
:param start: in case of renumbering needed : first frame
:param skip: how many frame were skipped
:param smooth: gaussian smoothing sigma
:return: interpolated ta... | 5,340,545 |
def on_mrsim_config_change():
"""Update the mrsim.config dict. Only includes density, volume, and #sidebands"""
existing_data = ctx.states["local-mrsim-data.data"]
fields = ["integration_density", "integration_volume", "number_of_sidebands"]
# if existing_data is not None:
print(existing_data["conf... | 5,340,546 |
def createuser(name, email, password, role):
"""
Creates a new user with specified roles
:return:
"""
from middleman.models import Role
user = user_controller.create(current_app.config['SECRET_KEY'], name, email, password)
role = db.session.query(Role).filter(Role.name == role).one()
... | 5,340,547 |
def decrypt(encrypted, passphrase):
"""takes encrypted message in base64 and key, returns decrypted string without spaces on the left
IMPORTANT: key must be a multiple of 16.
Finaly, the strip function is used to remove the spaces from the left of the message"""
aes = AES.new(passphrase, AES.MODE_ECB)
... | 5,340,548 |
def automig(name):
"""
Create auto south migration and apply it to database.
"""
api.local('./manage.py schemamigration %s --auto' % name)
api.local('./manage.py migrate %s' % name) | 5,340,549 |
def multi_ale_plot_1d(
features,
title=None,
xlabel=None,
ylabel=None,
x_rotation=20,
markers=("o", "v", "^", "<", ">", "x", "+"),
colors=plt.rcParams["axes.prop_cycle"].by_key()["color"],
zorders=None,
xlabel_skip=2,
format_xlabels=True,
show_full=True,
margin=0.03,
... | 5,340,550 |
def test_array_field_exact_no_match(Query):
"""
Test exact filter on a array field of string.
"""
schema = Schema(query=Query)
query = """
query {
events (tags: ["concert", "music"]) {
edges {
node {
name
}
}
... | 5,340,551 |
def load_ckpt(ckpt):
"""
:param ckpt: ckpt 目录或者 pb 文件
"""
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.per_process_gpu_memory_fraction = 0.2
if os.path.isdir(ckpt):
graph = tf.Graph()
with graph.as_default():
sess = tf.Session(config=config)... | 5,340,552 |
async def total_conversations(request: HistoryQuery = HistoryQuery(month=6),
collection: str = Depends(Authentication.authenticate_and_get_collection)):
"""Fetches the counts of conversations of the bot for previous months."""
range_value, message = HistoryProcessor.total_convers... | 5,340,553 |
def tiger2dot(tiger_filename, dot_filename):
"""
Genera un archivo en el formato DOT de Graphviz con el árbol de sintáxis
abstracta correspondiente a un programa Tiger.
Se utiliza la función auxiliar C{syntactic_analysis} para realizar el
análisis léxico-gráfico y sintáctico durante el cual se ... | 5,340,554 |
def update_app_trending():
"""
Update trending for all apps.
Spread these tasks out successively by 15 seconds so they don't hit
Monolith all at once.
"""
chunk_size = 50
seconds_between = 15
all_ids = list(Webapp.objects.filter(status=amo.STATUS_PUBLIC)
.values_lis... | 5,340,555 |
def log_pool_worker_start(metric_name, worker_name, data, args):
"""
Logging method for processing pool workers.
"""
logging.debug('{0} :: {1}\n'
'\tData = {2} rows,'
'\tArgs = {3},'
'\tPID = {4}'.format(metric_name, worker_name, len(data),
... | 5,340,556 |
def restler_fuzzable_datetime(*args, **kwargs) :
""" datetime primitive
@param args: The argument with which the primitive is defined in the block
of the request to which it belongs to. This is a date-time
primitive and therefore the arguments will be added to the
... | 5,340,557 |
def intersect(table_dfs, col_key):
""" intsc tables by column
"""
col_key_vals = list(unique_everseen(chain(*(
table_df[col_key] for table_df in table_dfs))))
lookup_dcts = [lookup_dictionary(table_df, col_key)
for table_df in table_dfs]
intscd_rows = []
for val in co... | 5,340,558 |
def p_class_def(p):
"""
class_def : CLASS TYPE INHERITS TYPE OCUR feature_list CCUR
| CLASS TYPE OCUR feature_list CCUR
"""
if len(p) == 8:
p[0] = ast.ClassDeclarationNode(p[2], p[6], p[4])
else:
p[0] = ast.ClassDeclarationNode(p[2], p[4])
p[0].set_pos(p.lineno(2),... | 5,340,559 |
def ask_peer(peer_addr, req_type, body_dict, return_json=True):
"""
Makes request to peer, sending request_msg
:param peer_addr: (IP, port) of peer
:param req_type: type of request for request header
:param body_dict: dictionary of body
:param return_json: determines if json or string response s... | 5,340,560 |
def generate_invoices(based_on_date=None):
"""
Generates all invoices for the past month.
"""
today = based_on_date or datetime.date.today()
invoice_start, invoice_end = get_previous_month_date_range(today)
log_accounting_info("Starting up invoices for %(start)s - %(end)s" % {
'start': i... | 5,340,561 |
def describe_instances_header():
"""generate output header"""
return misc.format_line((
"Account",
"Region",
"VpcId",
"ec2Id",
"Type",
"State",
"ec2Name",
"PrivateIPAddress",
"PublicIPAddress",
"KeyPair... | 5,340,562 |
def ordered_scaffold_split(dataset, lengths, chirality=True):
"""
Split a dataset into new datasets with non-overlapping scaffolds and sorted w.r.t. number of each scaffold.
Parameters:
dataset (Dataset): dataset to split
lengths (list of int): expected length for each split.
No... | 5,340,563 |
def read_plain_byte_array(file_obj, count):
"""Read `count` byte arrays using the plain encoding."""
return [file_obj.read(struct.unpack(b"<i", file_obj.read(4))[0]) for i in range(count)] | 5,340,564 |
def test_product_create_without_model_permissions(api_client, user, list_url, product_data):
"""
Tests that a user without permissions cannot create a product.
"""
response = api_client.post(list_url, data=product_data)
assert response.status_code == 401
api_client.force_authenticate(user=user)... | 5,340,565 |
def find_django_migrations_module(module_name):
""" Tries to locate <module_name>.migrations_django (without actually importing it).
Appends either ".migrations_django" or ".migrations" to module_name.
For details why:
https://docs.djangoproject.com/en/1.7/topics/migrations/#libraries-third-party-apps... | 5,340,566 |
def test_io_import_bom_rf3_shape():
"""Test the importer Bom RF3."""
root_path = pysteps.rcparams.data_sources["bom"]["root_path"]
rel_path = os.path.join("prcp-cscn", "2", "2018", "06", "16")
filename = os.path.join(root_path, rel_path, "2_20180616_100000.prcp-cscn.nc")
precip, _, _ = pysteps.io.im... | 5,340,567 |
def big_number(int_in):
"""Converts a potentially big number into a lisible string.
Example:
- big_number(10000000) returns '10 000 000'.
"""
s = str(int_in)
position = len(s)
counter = 0
out = ''
while position != 0:
counter += 1
position -= 1
out = s[posit... | 5,340,568 |
def setup(app): # lint-amnesty, pylint: disable=redefined-outer-name
"""Sphinx extension: run sphinx-apidoc."""
event = 'builder-inited'
app.connect(event, on_init) | 5,340,569 |
def action_list_to_string(action_list):
"""Util function for turning an action list into pretty string"""
action_list_string = ""
for idx, action in enumerate(action_list):
action_list_string += f"{action['name']} ({action['action']['class_name']})"
if idx == len(action_list) - 1:
... | 5,340,570 |
def select_demands_matrix(vrp_params, name=None):
"""
Selects a demands matrix subject to being loaded, for specified VRP.
This is an interactive function, where the name of
the text file is requested.
:param vrp_params: VRP parameters.
:param name: Data file name.
"""
if name is None:
... | 5,340,571 |
def segment(img_fpath, bbox_, new_size=None):
""" Runs grabcut """
printDBG('[segm] segment(img_fpath=%r, bbox=%r)>' % (img_fpath, bbox_))
num_iters = 5
bgd_model = np.zeros((1, 13 * 5), np.float64)
fgd_model = np.zeros((1, 13 * 5), np.float64)
mode = cv2.GC_INIT_WITH_MASK
# Initialize
#... | 5,340,572 |
def initialize_db():
"""Ensure that the database has the CURRENT_KEY key and exists"""
db = sqlite3.connect(DATABASE)
cur = db.cursor()
cur.execute(
"""CREATE TABLE IF NOT EXISTS survey_results (id INTEGER PRIMARY KEY AUTOINCREMENT, data BLOB);""")
cur.close()
db.close() | 5,340,573 |
def test_pandigital_9(*args):
"""
Test if args together contain the digits 1 through 9 uniquely
"""
digits = set()
digit_count = 0
for a in args:
while a > 0:
digits.add(a % 10)
digit_count += 1
a //= 10
return digit_count == 9 and len(digits) == ... | 5,340,574 |
def WMT14(
root,
split,
language_pair=("de", "en"),
train_set="train.tok.clean.bpe.32000",
valid_set="newstest2013.tok.bpe.32000",
test_set="newstest2014.tok.bpe.32000",
):
"""WMT14 Dataset
The available datasets include following:
**Language pairs**:
+-----+-----+-----+
|... | 5,340,575 |
def volume_attached(context, volume_id, instance_id, mountpoint):
"""Ensure that a volume is set as attached."""
return IMPL.volume_attached(context, volume_id, instance_id, mountpoint) | 5,340,576 |
def findby1email(session, email):
"""<comment-ja>
メールアドレスを指定して1件のユーザ情報を取得します
@param session: Session
@type session: sqlalchemy.orm.session.Session
@param email: メールアドレス
@type email: str
@return: karesansui.db.model.user.User
</comment-ja>
<comment-en>
TODO: English Comment
</... | 5,340,577 |
def _onJobSave(event):
"""
If a job is finalized (i.e. success or failure status) and contains
a temp token, we remove the token.
"""
params = event.info['params']
job = event.info['job']
if 'itemTaskTempToken' in job and params['status'] in (JobStatus.ERROR, JobStatus.SUCCESS):
tok... | 5,340,578 |
def _startswith(
self: str | ir.StringValue, start: str | ir.StringValue
) -> ir.BooleanValue:
"""Determine whether `self` starts with `end`.
Parameters
----------
self
String expression
start
prefix to check for
Examples
--------
>>> import ibis
>>> text = ibis... | 5,340,579 |
def convert_fields_in_iterator(iterator, fields):
"""Rename field names and eventually add fields with decoded values as defined in the fields structure."""
encoding_map, encoding_field_names = encoding(fields)
yield from add_decoded_fields_in_iterator(
rename_fields_in_iterator(iterator, fields), e... | 5,340,580 |
def get_models(modelType=None, modelId=None, nextToken=None, maxResults=None):
"""
Gets all of the models for the AWS account, or the specified model type, or gets a single model for the specified model type, model ID combination.
See also: AWS API Documentation
Exceptions
:example: respon... | 5,340,581 |
def read_XMLs(input_path):
"""Reads the building XMLs to list of `BuildingInfo` objects
Parameters
----------
input_path : str
Path where the XMLs are located
Returns
-------
info_list: list
A list of `BuildingInfo` objects with information about each building
"""
... | 5,340,582 |
def _get_all_scopes(blocks):
"""Get all block-local scopes from an IR.
"""
all_scopes = []
for label, block in blocks.items():
if not (block.scope in all_scopes):
all_scopes.append(block.scope)
return all_scopes | 5,340,583 |
def get_equinox_type(date):
"""Returns a string representing the type of equinox based on what month
the equinox occurs on. It is assumed the date being passed has been
confirmed to be a equinox.
Keyword arguments:
date -- a YYYY-MM-DD string.
"""
month = datetime.strptime(date, '%Y-%m-%d'... | 5,340,584 |
def skip_test_module_over_backend_topologies(request, tbinfo):
"""Skip testcases in the test module if the topo is storage backend."""
if "backend" in tbinfo["topo"]["name"]:
module_filename = request.module.__name__.split(".")[-1]
pytest.skip("Skip %s. Unsupported topology %s." % (module_filena... | 5,340,585 |
def mcs_worker(k, mols, n_atms):
"""Get per-molecule MCS distance vector."""
dists_k = []
n_incomp = 0 # Number of searches terminated before timeout
for l in range(k + 1, len(mols)):
# Set timeout to halt exhaustive search, which could take minutes
result = FindMCS([mols[k], mols[l]], ... | 5,340,586 |
def rows_as_dicts(cur):
"""returns rows as dictionaries in a generator when
provided cx_Oracle Cursor"""
columns = column_names_from_cursor(cur)
for row in cur:
yield dict(zip(columns, row)) | 5,340,587 |
def test_html_blacklist_label():
"""The label element defines the label for another element."""
check_html_has_no_output("""
<label><input type=radio name=size/>Large</label>
""") | 5,340,588 |
def get_tally_sort_key(code, status):
"""
Get a tally sort key
The sort key can be used to sort candidates and other tabulation
categories, for example the status and tally collections returned by
rcv.Tabulation().tabulate().
The sort codes will sort candidates before other tabulation
categories; electe... | 5,340,589 |
def plot_corelevel_spectra(coreleveldict,
natom_typesdict,
exp_references=None,
scale_to=-1,
show_single=True,
show_ref=True,
energy_range=None,
... | 5,340,590 |
def get_lidar_point_cloud(sample_name, frame_calib, velo_dir, intensity=False):
"""Gets the lidar point cloud in cam0 frame.
Args:
sample_name: Sample name
frame_calib: FrameCalib
velo_dir: Velodyne directory
Returns:
(3, N) point_cloud in the form [[x,...][y,...][z,...]]
... | 5,340,591 |
def url2filename(url):
"""Return basename corresponding to url.
>>> print(url2filename('http://example.com/path/to/file%C3%80?opt=1'))
file??
>>> print(url2filename('http://example.com/slash%2fname')) # '/' in name
Traceback (most recent call last):
...
ValueError
"""
urlpath = urlsp... | 5,340,592 |
def test_Timer():
"""Unit tests for Timer class"""
with Timer(verbose=True):
sleep(0.1)
logging.info('<< PASS : test_Timer >>') | 5,340,593 |
def make_mlp(dim_list, activation_list, batch_norm=False, dropout=0):
"""
Generates MLP network:
Parameters
----------
dim_list : list, list of number for each layer
activation_list : list, list containing activation function for each layer
batch_norm : boolean, use batchnorm at each layer,... | 5,340,594 |
def pddobj_video_file_path(instance, filename):
"""Generate file path for new video file"""
ext = filename.split('.')[-1]
filename = f'{uuid.uuid4()}.{ext}'
return os.path.join('uploads/videos/', filename) | 5,340,595 |
def browse_files():
"""
# Function for opening the file explorer window
:return:
"""
filename = filedialog.askopenfilename(
initialdir='/',
title='Selecionar arquivo zipado (.zip)',
filetypes=(('Zip files', '*.zip'), ('All files', '*.*'))
)
# Change label contents
... | 5,340,596 |
def load_and_prep_image(filename):
"""
Reads an image from filename, turns it into a tensor
and reshapes it to (img_shape, img_shape, colour_channel).
"""
image = cv2.imread(filename)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(haarcascade)
fa... | 5,340,597 |
def DoH(im, canvas, max_sigma=30, threshold=0.1, display=True):
""" Difference of Hessian blob detector
:param im: grayscale image
:param max_sigma: maximum sigma of Gaussian kernel
:param threshold: absolute lower bound Local maxima smaller than threshold ignore
"""
blobs = blob_doh... | 5,340,598 |
def setup_communityservice(ts3bot):
"""
Setup the a community bot.
:return:
"""
global bot
global ts3conn
bot = ts3bot
ts3conn = bot.ts3conn
global channel_config
global channels_configured
channel_config = {int(k):v for k,v in config["channel_config"].items()}
cha... | 5,340,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.