content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def analysis_protocol_lookup(protocol_filename):
""" get the correct analysis function by protocol name """
func=lambda:None
pro_ana_dict={
'.pro':func
}
return pro_ana_dict[protocol_filename] | 5cafa4a509a02e109e6770514fd435d9136fbe8a | 665,672 |
def get_config_file_needed(args):
"""
Determines whether or not we need to fetch additional config variables from a file.
"""
return not (args.project_name and args.source_dir and args.data_dir and args.volumes_dir) | e5ad6c8a67cab488b519e2e7eeca812cd7851f9a | 665,673 |
def get():
"""
Returns service status.
"""
return {'service_status': 'healthy'} | b732e1404cd76c2adeddbcf7a8e73a501d3c41e6 | 665,675 |
def get_floating_latest(api_versions_list, preview_mode):
"""Get the floating latest, from a random list of API versions.
"""
api_versions_list = list(api_versions_list)
absolute_latest = sorted(api_versions_list)[-1]
trimmed_preview = [
version for version in api_versions_list if "preview" ... | 66c2308420a657f821ca405f32f69bae035fbb44 | 665,676 |
def mastinMER(H, DRE = 2500):
"""Calculates Mass Eruption Rate (MER) using Mastin et al. 2009 equation.
Input is height (km), dense rock equivalent (DRE) (kg/m^3).
dV = volumetric flow rate (m^3/s)
Output is MER (kg/s). Optional input is DRE"""
p=1/0.241
dV=(H/2.00)**p
MER=dV*DRE
return... | 33e5229044560e412ba9ae2d80721bacbe094085 | 665,677 |
import os
import re
def get_version_from_file(version_filepath):
"""
Try to derive and then return the version number of the ``mcdm`` package
according to an existing file.
"""
if os.path.isfile(version_filepath):
with open(version_filepath, mode="r", encoding="utf-8") as fp:
m... | 90edf31365ab2f1046825cf01650a15fe6aaac75 | 665,678 |
def _set_vmin_vmax(d, cbrange):
"""Set minimum and maximum values of the color map."""
if 'vmin' not in d.keys():
d['vmin'] = cbrange[0]
if 'vmax' not in d.keys():
d['vmax'] = cbrange[1]
return d | 90b7e22fd3f340a0ff1c04729eef11ffb532dd23 | 665,679 |
import subprocess
def getOptionMessageStatus(domain):
"""
Check if Domain is receiving replies from OPTION Messages
:param domain: domain to check
:type domain: str
:return: whether domain handled OPTION message correctly
:rtype: bool
"""
response = subprocess.check_... | add58363695e3f28b20f767a548bbef7b71071d9 | 665,680 |
import csv
def return_column(file,column):
"""Egy listában vissza ad egy specifikus oszlopot a fájlban"""
column_data = []
dict_reader = csv.DictReader(open(file, 'r', newline='' ,encoding='ISO-8859-2'), delimiter = ',')
# Kikeresi az oszlopot a fájlban
if column in dict_reader.fieldnames:
... | 623f4254a68d6d02d882eb763659e16ea41991a9 | 665,681 |
def get_inputs_from_database(
scenario_id, subscenarios, subproblem, stage, conn
):
"""
:param subscenarios:
:param subproblem:
:param stage:
:param conn:
:return:
"""
subproblem = 1 if subproblem == "" else subproblem
stage = 1 if stage == "" else stage
sql = """
... | 79a433c497a2e18486f2e32081d0369f6181153d | 665,682 |
def get_param(request, name, default_value=None):
""" Return required request param, or default_value if not found. """
if request.body:
if default_value is None:
# This is required.
if request.POST:
# Must be a form POST.
return request.POST[name... | 3c1dc61ab01fa58646fe5dbb218979352833be4c | 665,683 |
def _convert31(pkg):
"""
Converts from JMI type 3 to JMI type 1.
"""
##
# A nested helper function to handle recursive JMI 3 to 1 conversion.
##
def _jmi31_helper(element, element_id):
# Reinsert the missing ID field
element['id'] = element_id
# Add the element to t... | 2069c719bd24c0ef70ed99f9ba919f631cc206e8 | 665,684 |
def save_userLUT(voidef, out_lut_file):
"""
Save look-up table for user-defined VOI.
Format for outputted table:
|user VOI No.|user VOI name|
"""
df = voidef[["user VOI No.", "user VOI name"]]
df2 = df.drop_duplicates(["user VOI name"])
df2.to_csv(out_lut_file, index=False, sep=" ... | 1af47899adecfe904f65b962794f19b186476897 | 665,685 |
def _fake_names(X):
"""We cannot have empty channel names, so we use it the MICROMED
convention
"""
for i in range(X['name'].shape[0]):
if X['name'][i] == '':
X['name'][i] = f'el{i + 1}'
return X | 5bc3b0bd5a6afa73a6a6f0fd23ee462a6debf36c | 665,686 |
from typing import Counter
def update_proposal_distribution(W, Z, P, Q_, Z_):
"""
Updates a proposal distribution using
old proposal Q_ and Z_,
new weights W and Z
and P
"""
m = len(Q_)
assert len(W) == m + 1
assert len(Z) == m + 1
assert len(P) == m + 1
assert len(Z_) == m... | 1b1d0b6e32a633445d4fda6d1c3c9c2a2dbb7668 | 665,687 |
import numpy as np
def random_point_sphere(npoints, rnd_seed = None):
"""
Utitlity function to provide test coordinates to measure
query times. It computes randomly distributed points on
a 2d sphere.
Parameters:
-----------
npoints: `int`
... | f545130e3396cadc763f1931e979715382dcf15e | 665,688 |
import argparse
def parse_command_line_arguments(command_line_args=None):
"""
Parse command-line arguments.
Args:
command_line_args: The command line arguments.
"""
parser = argparse.ArgumentParser(description='ARC delete util')
parser.add_argument('-p', '--project', type=str, nargs... | b73b4c89e9b3f8b0d8b903ea3f1bd18122ca2749 | 665,689 |
import six
import re
def _replace_series_name(seriesname, replacements):
"""Performs replacement of series name.
Allow specified replacements of series names in cases where default
filenames match the wrong series, e.g. missing year gives wrong answer,
or vice versa. This helps the TVDB query get the... | a5373553fb6a8f4a59801503a806828a953ba63f | 665,690 |
def dot(p0, p1):
"""
:return: dot product of the given 2d vectors
"""
return p0[0] * p1[0] + p0[1] * p1[1] | eb7ecfc25ce246abfb18ef81eea46186ca33ffb5 | 665,691 |
def merge_two_box(box_a, box_b):
"""
合并两个box
"""
x1_min, y1_min, x1_max, y1_max = box_a
x2_min, y2_min, x2_max, y2_max = box_b
nx_min, ny_min = min(x1_min, x2_min), min(y1_min, y2_min)
nx_max, ny_max = max(x1_max, x2_max), max(y1_max, y2_max)
tmp_box = [nx_min, ny_min, nx_max, ny_max]
... | 21afcec628152a1352a3af47b1cc7bbe0040a201 | 665,692 |
def is_experimental_class(klass):
"""
Test CIM compoments of the klass parameter and if any have the experimental
qualifier and its value is True return True. Otherwise return False
Parameters:
klass :class:`~pywbem.CIMClass`:
The CIMClass to test for the experimental qualifier
Retur... | a98771dd3e5d5e5200ada71a9c8285e1ea82c526 | 665,693 |
def BinaryTreeNodeDepthSum(root):
"""
Given a root of a binary tree find the sum of nodes depth.
"""
def calculate_depth(node, level, depth):
# base case to exit.
if not node:
return 0
if node.value:
depth["depth"] += level
if node.left:
... | 70a1418e5980474f0999d8c719891fe235e6482d | 665,694 |
import os
def getmypid(space):
""" Gets PHP's process ID"""
res = os.getpid()
return space.newint(res) | 5af8ff28c5b614aff474b200933b01ac2180570f | 665,695 |
def long2base(n, q):
""" Maps n to a list of digits corresponding to the base q representation of n in reverse order
:param int n: a positive integer
:param int q: base to represent n
:return: list of q-ary 'digits', that is, elements of {0,1,..,q-1}
:rtype: list"""
lt = []
while n > 0:
... | eda623195285685e91583f0caa51fa5c8158b326 | 665,696 |
def not_found(request):
"""
This is the view that handles 404 (not found) http responses
"""
request.response.status_int = 404
return {
'url': request.resource_url(request.root)
} | be166a3763abfdf14f5120c01538359747f1d189 | 665,697 |
def prompt(text, options):
"""Prompts the user to enter one of a set of options (either in full or first char) and
returns first char."""
option_string = '({} or {}) '.format(', '.join(options[:-1]), options[-1])
response = input(text + ' ' + option_string)
while not response or response[0].lower() ... | d6494e13ff070a31f4c5b4d75458ebb61f1e37d3 | 665,698 |
def assign_assumed_width_to_province_roads_from_file(asset_width, width_range_list):
"""Assign widths to Province roads assets in Vietnam
The widths are assigned based on our understanding of:
1. The reported width in the data which is not reliable
2. A design specification based understanding of the ... | afe1f7e19423802739c844952b244dc4f2c85eca | 665,699 |
from typing import Sequence
from typing import Any
def _get_element_from_recent_list(
target_list: Sequence[Any],
target_slot: int,
slot_relative_position: int) -> Any:
"""
Return the element from ``target_list`` by the ``target_slot`` number,
where the the element should be at ``t... | 6116b9ef9a5f62c287c439c0f24a0127d3169036 | 665,700 |
def photofolderPath():
"""
Input:
(none)
Output:
path string
History:
2017-03-08 - Written - F. Anders (AIP)
2019-06-10 - Adapted for pysvo - F. Anders (ICCUB)
"""
return './pysvo/photometry/' | 42d761fb58187c75a27a60d0d26abe05507825dc | 665,701 |
from typing import Optional
def _define_numerical_dict(dict_: Optional[dict]) -> Optional[dict]:
"""
Takes a dictionary and checks if all values in dictionary are integers and floats.
Can take None as argument.
Args:
the_dict: Dict to perform check against
Raises:
ValueError: If ... | cb1597e15a7ad5122ac35008257b462e4e434a56 | 665,702 |
def _computeobsoleteset(repo):
"""the set of obsolete revisions"""
obs = set()
getrev = repo.changelog.nodemap.get
getphase = repo._phasecache.phase
for node in repo.obsstore.successors:
rev = getrev(node)
if rev is not None and getphase(repo, rev):
obs.add(rev)
retur... | c59ddcf83edf4c14fc77a86f47532a46a05bb398 | 665,703 |
import subprocess
def safe_run(shell_cmd, retry=3, has_retry=0):
"""
Return linux command line executive result
Parameter
---------
shell_cmd : str
linux command
retry : int, default 3
the number of retry if command fail
has_retry: int, default 0
the number of retr... | cfd2ad18e5f103defee0e657e4dbe8a166a7bd9c | 665,704 |
def calculate_mturk_cost(payment_opt):
"""MTurk Pricing: https://requester.mturk.com/pricing
20% fee on the reward and bonus amount (if any) you pay Workers.
HITs with 10 or more assignments will be charged an additional
20% fee on the reward you pay Workers.
Example payment_opt format for paying r... | 8bbfb58031d884371d19c95755683c67ed6d6fdb | 665,705 |
from typing import Dict
def dict_union(*args: Dict) -> Dict:
"""
Unite two or more dicts into one.
Results in a new dict.
>>> dict_union({'a': 1}, {'b': 2})
{'a': 1, 'b': 2}
"""
new_dict = {}
for dict_ in args:
new_dict.update(dict_)
return new_dict | b771224cb777d812a7b81810ff9c1c5ebc1039f4 | 665,706 |
def assign_linux_server_policy(api, configuration, api_version, api_exception, computer_id):
""" Assigns a Linux server policy to a computer.
:param api: The Deep Security API modules.
:param configuration: Configuration object to pass to the api client.
:param api_version: The version of the API to us... | 92b00c7bd666265119651c0d05b3a318d130e316 | 665,707 |
def _df_elements(df):
"""Yields all the values in the data frame serially."""
return (x for row in df.itertuples() for x in row) | 6b9ae811693539f374e3125f870788c574a7eb79 | 665,708 |
from typing import OrderedDict
def filter_graph(dictionary, include_keys):
"""
Create new list that contains only values
specified in the ``include_keys`` attribute.
Parameters
----------
dictionary : dict
Original dictionary
include_keys : list or tuple
Keys that will co... | abdd07ef374a85718ac54319a1f982cf3043a28e | 665,709 |
def _get_collapsed_course_and_dist_req_sets(req):
"""
Returns the sets of all courses and all distribution requirements
in req's subtree as a tuple:
(course_set, dist_req_set)
Note: Sets may contain duplicate courses if a course is listed in multiple
different ways
"""
if "course_list" i... | 8ad1e36d40d751f06e380a73845cf5d082f1afe9 | 665,710 |
import math
def VD_5112_1(di, li, E):
"""
5.1.1.2 Bending Resilience
"""
# Bending angle
#gamma = (MB * lK) / (E * I) # (5.1/16)
Ii = math.pi / 64.0 * di**4
# The bending resilience
beta_i = li / (E * Ii) # (5.1/17)
#
return beta_i
# | 402698ff3fc153a8c494856d5ec00121b07ae218 | 665,711 |
from typing import List
def get_required_cols(geom_type: str, columns: List[str]) -> List[str]:
"""Get the required columns for a given geometry type."""
req_cols = ["id", geom_type, "dates", "region"]
for var in ["time_scale", "pet", "alpha"]:
if var in columns:
req_cols.append(var)
... | 8861004e54a4d741c9727b268164c87e9a091f12 | 665,712 |
def parse_spinsolve_par_line(line):
"""
Parse lines in acqu.par and return a tuple (paramter name, parameter value)
"""
line = line.strip() # Drop newline
name, value = line.split("=", maxsplit=1) # Split at equal sign (and ignore further equals in attribute values)
# remove spaces
name =... | 0f35597c5eb47205a4f8c880574b2ab187c82d94 | 665,713 |
def get_lca(r, assignranks, reportranks):
"""
Assign lowest common ancestor from a set of taxids.
Parameters
----------
r: pandas.DataFrame
Results for a single query, extracted from the main diamond results
file
assignranks: list
Taxonomic ranks to assign taxonomy for
... | ddc4dff266ef57acd9bfea95fd7ec91248bb830a | 665,714 |
def create_sloping_step_function(start_x, start_y, end_x, end_y):
"""
create sloping step function, returning start y-value for input values below starting x-value, ending y-value
for input values above ending x-value and connecting slope through the middle
:param start_x: float
starting x-... | 67c8778a9aaba03cb7847de59dd018e128876ba0 | 665,715 |
def oqueFazer():
"""
Função que garente que o usuário digitará uma opção
válida
"""
while True:
escolha = input("Deseja atacar (a), curar (c), salvar(s), ou desistir(d)?\n").lower()
if not escolha.isalpha():
print("Digite apenas letras.")
elif not (escolha.starts... | f3cd4ce67fbad36c90cb168ced24eb6d893d727c | 665,716 |
def iv_from_hsub(hsub, digits=16):
"""Return the decoded IV from an hsub. By default the IV is the first
64bits of the hsub. As it's hex encoded, this equates to 16 digits."""
# We don't want to process IVs of inadequate length.
if len(hsub) < digits:
return False
try:
return bytes... | 0c4dad9c55945917b5d5a32c7fd59feb473923a0 | 665,717 |
import logging
import os
def setup_logging(name, log_level=logging.INFO, log_file=None):
"""
E.g. setup, in '___main__'
log_fn = f"process_clevr_data.py_{args.dataset}_{args.split}.out"
logger = setup_logging(__name__, log_file=log_fn)
logger.info(f'Called with args: {args}')
main(args)
... | 98e32e5ad26270080bfab08c1c632796de746b1b | 665,718 |
def is_crud(sql):
"""Check that given sql is insert , update, delete or select
:param sql: Sql string to check for is_crud
:return: Boolean result
"""
crud = ['insert', 'update', 'delete', 'select']
if not isinstance(sql, str):
raise TypeError('`sql` argument is not valid. `sql` must... | 0639b370404ae1e7488124000be0d0963e8484cf | 665,719 |
import math
def split_array_old(totnum,nprocs,myrank):
""" Returns a split array based on the number of processes and ranks. """
n2=math.floor(totnum/nprocs)
remain=math.fmod(totnum,nprocs)
if (myrank < remain) :
n1=n2+1
ib=(myrank)*n1
ie=ib+(n1-1)
else :
n1=n2
... | 85bc017efdbab068860a632fc20e62822874b48c | 665,720 |
def findCongestionPercentage(db, start_time, end_time, metername):
"""Search for congestion **between** start_time and end_time
Returns True if avg time between usages is less than CONGESTION_THRESH"""
CONGESTION_THRESH = 900
time_between_charges = []
previous_previous_time = start_time # When I m... | e79f2913117a031f9a160b3a6d42a5fb6e3e62c7 | 665,721 |
def is_table(cur, table_name):
"""
Simple check to see if table exists or not
:param cur: cursor
:param table_name: str - name of table
:return: True/False
"""
sql_command = f"SELECT EXISTS ( SELECT FROM information_schema.tables WHERE table_name = '{table_name}' );"
cur.execute(sql_comm... | 0cdf2138a6ed1c9a6c698790e889cdaf20aa8bf3 | 665,722 |
import inspect
import functools
def memoize(f):
"""
Decorator for memoization of function which doesn't take only
keyword arguments
"""
table_field = '_memo_' + f.__name__
argnames = list(inspect.signature(f).parameters)
#
@functools.wraps(f)
def fun(self, *arg, **kwd) :
... | 92babbbada299653162e2db5b2a058712a8d9c88 | 665,723 |
def generic_mon_cb(source, signal):
"""
Create a generic callback for sending a signal from source value.
:param source: Object representing the EPICS PV data source. This object
needs to be properly initialized and monitored.
:type source: Pv
:param signal: Signal to send the v... | 6bc3c67681d7c46c57fa6911438b4aeedf137deb | 665,724 |
import uuid
def _make_job_id(job_id, prefix=None):
"""Construct an ID for a new job.
:type job_id: str or ``NoneType``
:param job_id: the user-provided job ID
:type prefix: str or ``NoneType``
:param prefix: (Optional) the user-provided prefix for a job ID
:rtype: str
:returns: A job ID... | 9d710f7103adc3a77f6f07d8d3d61877b360723c | 665,725 |
import logging
def all_transceivers_detected(dut, asic_index, interfaces, xcvr_skip_list):
"""
Check if transceiver information of all the specified interfaces have been detected.
"""
cmd = "redis-cli --raw -n 6 keys TRANSCEIVER_INFO\*"
asichost = dut.asic_instance(asic_index)
docker_cmd = asi... | 59b6b8329972f7f262a579faa4c4fd3cf0d16b07 | 665,726 |
import pathlib
def get_version(rel_path):
"""Get the version of the library
Args:
rel_path (str): Relative path to __init__.py with version.
Returns:
str: Version of library
"""
for line in pathlib.Path(rel_path).open('r').read().splitlines():
if line.startswith('__version_... | 5570a521737aac58bda6ac7a85ce21a5cba8fb44 | 665,727 |
import torch
def get_mae_off(data_loader, vae_model, classes_dict):
"""
off-grid/ off-range processing compute the doa mae over the supervised training set or the testing set
"""
predictions, actuals = [], []
error=0
nData=0
classes = classes_dict['model']
classes_off = classes_... | 03c43cf2ab91aa679d7ccab4df44e9279bb35dc2 | 665,728 |
def should_be_deactivated(message):
"""
Determines whether a message stands for an option to be turned off.
Args:
message(str): A message to test
Returns:
bool: True if the message is negative, False otherwise
"""
NEGATIVE_TERMS = ["deactivated", "disabled", "false", "no", "none"... | f0b9bae84fe196c8af58620cb8501dd7f91df64f | 665,729 |
def expand_float(data):
"""helper method for ``expand_thru_case_control``"""
out = []
for datai in data:
out.append(float(datai))
out.sort()
return out | f01be7ec7716246614a2c44085c9e377428fd4e1 | 665,731 |
import os
def nameHTML(file, htmlNames):
"""
Función que recibe un string con terminación .py
la cual cambia por la terminación .html
En caso de que el nombre de uno de los archivos a resaltar esté repetido (ya
exista en htmlNames), se le agrega al nombre un "-1".
"""
# Separar el nombre d... | 81907ff7a65bf81eeeec84e9c6ceb3290bf95178 | 665,732 |
def compute_reward_from_states(path, current_state, next_state, storage_for_reward):
"""
Compute the reward given by the transition from current_state to next_state
The reward depends on the path that the learning process is trying to learn
"""
reward_from_props = 0
# Reward is given only to th... | 48e75e9ea3bced66815b8dfa668fe50cd4337f7c | 665,733 |
import hmac
import hashlib
import time
def verify_access_token(token, key):
"""Verify that the given access token is still valid. Returns true if it is,
false if it either failed to validate or has expired.
A token is a combination of a unix timestamp and a signature"""
t = token[:15]
signature =... | 158ea66dd4f57507336f749b5e2a104450909d21 | 665,734 |
def pymodule_fpaths_to_objects(fpaths):
"""
Takes an iterable of file paths reprenting possible python modules and will return an
iterable of tuples with the file path along with the contents of that file if the file
exists.
If the file does not exist or cannot be accessed, the thir... | 420dc88ab2b2b146b762e937b4fe33c633dc082e | 665,735 |
def _normalize(arr, keep_ratio=False):
"""Normalize an array into [0, 1]."""
(x_min, y_min), (x_max, y_max) = arr.min(axis=0), arr.max(axis=0)
if keep_ratio:
a = 1. / max(x_max - x_min, y_max - y_min)
ax = ay = a
bx = .5 - .5 * a * (x_max + x_min)
by = .5 - .5 * a * (y_max +... | 3b655473751960a4516cf2ec547c58d235cf9b88 | 665,736 |
import torch
def load_net(net_path, device):
"""
loads the network to the passed device
:param net_path: the path of the network to load
:param device: the device to which the network is loaded
:return:
"""
# put the model on the gpu
if device.type == "cuda":
gpu_net =... | eca284b6d9a6708473f9868ff2efceba2dfacbff | 665,737 |
def the_driver(pytestconfig):
"""Set the user defined driver"""
return pytestconfig.getoption('driver') | f1431cfa7029f8cc341c3f3a2f6e2bfe9f0928fe | 665,738 |
def str_or_na(string):
"""Return the string or "na". """
try:
return string
except:
return "na" | be1804a1332c37c8fd2e6d04cd537cef71b02a84 | 665,739 |
def convert_list(*argv):
"""This api takes list/strings and
returns list
"""
ret_list = []
for arg in argv:
if arg:
if type(arg) == list:
ret_list += arg
else:
ret_list += [arg]
return ret_list | 736fd69a7ad712cc88903360effcb0143aaca8ea | 665,740 |
def get_fake_context(**config):
"""Generates a fake context description for testing."""
fake_credential = {
"user": "fake_user",
"host": "fake_host",
"port": -1,
"key": "fake_key",
"password": "fake_password",
}
return {
"task": {
"uuid": "fa... | e8484b13aad2f10f060bf928d4928100fd141475 | 665,741 |
def _rule_accuracy_cn(cn, rule, pos_pruneset_idx, neg_pruneset_idx):
"""Calculate accuracy value of object's classification.
object: Cond, Rule, or Ruleset
"""
P = len(pos_pruneset_idx)
N = len(neg_pruneset_idx)
if P + N == 0:
return None
tp = len(cn.rule_covers(rule, pos_pruneset_... | 689b259d888500b23501320174488e64e996d379 | 665,742 |
def expand_window(data, window_set=1):
"""
:param data: the original list
:param window_set: int or list of int
:return: a list of lists shifted by the bias which is specified by window_set
"""
if isinstance(window_set, int):
window_set = [window_set]
window_list = []
for bias in... | 191736346c536443b938382a49f3f80911b73549 | 665,743 |
import re
import os
def split_msms_title(line):
""" Split a title line into a useful format. """
regex = re.compile(r"\\|/")
sline = line.split(" ")
# Using a regex to spit on file paths to handle
# different OS's
filename = regex.split(sline[1])[-1]
basename = os.path.splitext(filename)... | 2cca0dd16e7dbf9562e0164b7c6518d4a50cafc0 | 665,744 |
import torch
def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float):
"""
Utility function that returns a first order derivative kernel of 3x3x3
"""
kernel = torch.tensor([[[[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0]],
... | ba3303a40dd622a881e44363cf6866b731e3ce68 | 665,745 |
def dirname(path):
"""Return the directory portion of a file path."""
if path == "/":
return "/"
parts = path.split("/")
if len(parts) > 1:
return "/".join(parts[:-1])
return "." | 8ae910d8a8ee5a213b75b404355e2155a70b8bff | 665,746 |
import functools
def drain(predicate=lambda x: True):
"""
Drains a generator function into a list, optionally filtering using predicate
"""
def wrapper(func):
@functools.wraps(func)
def inner(*args, **kwargs) -> list:
return [x for x in func(*args, **kwargs) if predicate(x... | 4d9b5505b168b4caa28c3efe474bf9f25e714f3d | 665,747 |
import pathlib
def sanitize_path(path):
"""Sanitize a path. Returns a pathlib.PurePath object.
If a path string is given, a PurePath object will be
returned. All relative paths will be converted to
absolute paths.
"""
pure_path = pathlib.Path(path).resolve()
return pure_path | 3a34af2bcea83172047217ebc8274aac38a55d8a | 665,748 |
import sys
def get_user_input():
"""
Get user input
Return:
- The lower bound and upper bound threshold
- exit if otherwise
"""
try:
lower_bound = int(input(
'Please enter a lower bound for the threshold (barrage): '))
upper_bound = int(input('Please ent... | db61f05456fad771535b4e9a07a3fdd00cb59606 | 665,749 |
import time
def server_time(request):
"""
Includes the server time as a millisecond accuracy timestamp
"""
return {"server_time": int(round(time.time() * 1000))} | 171cfae6ad9ae214bac17fc3dbff25738cae9067 | 665,750 |
def clearsky(three_days_hourly, albuquerque):
"""Clearsky at `three_days_hourly` in `albuquerque`."""
return albuquerque.get_clearsky(
three_days_hourly,
model='simplified_solis'
) | 9068bed1de581cca9794047b1b7c033a23633950 | 665,751 |
import os
def get_model_path(model_name, model_type='static'):
"""
Return the saved model dir name
"""
infer_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
model_path = os.path.join(infer_dir, "models", model_type, model_name)
return model_path | d4fb9d712906cc3e365f63e1fd052f4d11d28bcf | 665,752 |
import subprocess
def get_level():
"""
Returns the Battery Level of the Laptop in Integer
"""
bat = subprocess.run("WMIC PATH Win32_Battery Get EstimatedChargeRemaining", shell=True, capture_output=True)
cat = bat.stdout.decode()
level = int(cat.split("\n")[1].strip())
return level | 922eb58600d9e912ab9f1a49c42988918261edf0 | 665,756 |
def c_to_f(c):
"""
>>> c_to_f(38)
100.4
>>> c_to_f(32)
89.6
>>> c_to_f(5000)
9032.0
>>> c_to_f(100)
212.0
"""
return c * 9.0/5 + 32 | 2f1df16f8776b22223f838fdc9c7ba84bc292166 | 665,757 |
def generate_reqmgr_requests(workflowList):
"""
generate the request with following structure
{
"_id": "cmsdataops_sryu_test4_120111_114950_128",
"_rev": "6-02b17b4eabcf333e7499c0fa0ae5055b",
"inputdataset": "/Photon/Run2011A-v1/RAW",
"group": "cmsdataops",
"request_date... | 9573c246d019e4ed9ab9bc4cf6dca3e34f062973 | 665,758 |
def palindrome_permutation(w):
"""
This solution counts how often each distinct character appears
in w. Checking for a possible palindrome then proceeds in two
slightly different cases, depending on whether w is of even
or odd length.
"""
w = w.strip().replace(' ', '')
chars = {}
for... | 8a7cddb0acc2a755e7c752e3dd910b916dad34a1 | 665,760 |
import re
def extract_cga(l_sent):
"""
Extracts contracts, grants and abbreviations
:param page: string
:return: the list of contracts, grants and abbreviations
"""
y = ""
l_cga = []
if l_sent:
for s in l_sent:
s = s.replace("-\n", "-") # remove going to the next l... | a2c7fac2c94dce68bb45333930fd98874bdb0ce1 | 665,761 |
def JIRA(jira_issue):
"""Fake JIRA instance."""
class MockJIRA(object):
def __init__(self, *args, **kwargs):
pass
def search_issues(self, *args, **kwargs):
return [jira_issue, ]
return MockJIRA | 2576b87411029db21ca260e177ecb5a2bf572a07 | 665,762 |
import requests
def object_store_change_ownership(api_key, object_type, object_id, owner_id):
"""
Changes the ownership of an object (Extractor or Crawl Run) in the object store.
NOTE: The API KEY must be from an account that has SUPPORT role
:param api_key: Import.io API Key
:param object_type: S... | 89ee3e1b0a5823cd1e433b6c0e1029426b9e6f74 | 665,763 |
import json
def jsons_str_tuple_to_jsons_tuple(ctx, param, value):
"""
Converts json str into python map
"""
if value is None:
return []
else:
return [json.loads(a) for a in value] | 81fd7c68f5022fd74e051a4a4e8b8c4f65669b5a | 665,764 |
def lower_clean_string(string):
"""
Function used to make string lowercase filter out punctuation
:param string: Text string to strip clean and make lower case.
:return: String in lowercase with all punctuation stripped.
"""
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~[\n]'
lowercase_... | 27d7331215e513efad61d695ae5198a6dfd10cd3 | 665,766 |
import json
from typing import OrderedDict
def load_json_data(contract_contents):
"""
Given a string 'contract_contents', this method assumes it's
contents are JSON, and loads it into memory
"""
return json.loads(
contract_contents, object_pairs_hook=OrderedDict
) | cd0910528208199e9b4b165a8da95a83b0f8c937 | 665,767 |
import socket
def socket_ready(hostport):
"""
:param hostport: a pair (host, port) or a string (tcp://)host:port
:returns: True if the socket is ready and False otherwise
"""
if hasattr(hostport, 'startswith'):
# string representation of the hostport combination
if hostport.startsw... | d021462ca93521a74fd37931b62c856f86d5bf6a | 665,768 |
def eh_celula(cell):
"""
eh_celula: universal >>> logico
- Determina se o valor dado e do tipo celula ou nao
"""
if not isinstance(cell, dict):
return False
elif "valor" not in cell or len(cell.keys()) != 1:
return False
return cell["valor"] in (-1, 0, 1) | 452ab2904a28eea2c9eedc3755981c42973c9080 | 665,769 |
def find_first_common_ancestor(node1, node2):
"""
Find the first common ancestor for two nodes in the same tree.
Parameters
----------
node1 : nltk.tree.ParentedTree
The first node.
node2 : nltk.tree.ParentedTree
The second node.
Returns
-------
ancestor_node : nltk... | 37748766c76e3fd1d2b1f15202637536147a7a5c | 665,770 |
def reduce_gain_for_noclip(track_peaks, album_gain):
"""Reduce album gain value until no song is clipped.
No command switch give you the max no-clip in album mode.
So we consider the recommended gain and decrease it until no song is
clipped when applying the gain.
Formula found at:
http://www.... | 51d9dad98d7eaa6852d53ac091ff253d730b93c8 | 665,771 |
async def get_hmms_referenced_in_db(db) -> set:
"""
Returns a set of all HMM ids referenced in NuVs analysis documents
:param db: the application database object
:return: set of all HMM ids referenced in analysis documents
"""
cursor = db.analyses.aggregate([
{"$match": {
"... | aca44ad11eaff0c734503701f943cb8394db15a5 | 665,772 |
import asyncio
async def call(args, *, cwd, env=None, shell=False):
"""
Similar to subprocess.call but adapted for asyncio. Please add new arguments as needed.
cwd is added as an explicit argument because asyncio will not work well with os.chdir, which is not bound to the
context of the running corout... | 63063b8d9577287bcd5ad3a934899354c2a70cf0 | 665,773 |
import subprocess
def run (cmd, verbosity=0, **kwargs):
"""Run command without error checking.
@return: command return code"""
if kwargs.get("shell"):
# for shell calls the command must be a string
cmd = " ".join(cmd)
return subprocess.call(cmd, **kwargs) | 124be49905a4d614bad73e5f41312f38ea2a4e63 | 665,774 |
def wrapped_cvsolve(
gas,
sd,
max_tries=10,
t_end=1e-6,
max_step=1e-5,
):
"""
Look jack, I don't have time for your `breaking` malarkey
Try cvsolve a handful of times with increasing max time lengths to see if
maybe it's just being mean.
Parameters
-----... | 475100bc9ccd434cc196622b5cf179e46e09ccb6 | 665,775 |
def make_alias_dict(dict_file):
"""create an alias dictionary from a file"""
out_dict = {}
vocab = []
for line in open(dict_file, 'r'):
alias = line.strip('\n').strip('\r').split(',')
alias_target = alias[0] if alias[0] not in out_dict else out_dict[alias[0]]
for a in alias:
... | 88fb6e6bc0543f6b17954157cda4d517d8ee4976 | 665,776 |
from datetime import datetime
def get_dt_stamp():
"""Get date-timestamp."""
return str(datetime.now()).replace(
' ',
'_').replace(
':',
'_').replace(
'-',
'_').replace(
'.',
'_') | 48b09b13d846e1ec925774cc34e78680a76a8b45 | 665,777 |
def _pad_data(data: bytes, n: int = 16) -> bytes:
"""
Adds padding to the data according to the PKCS7 standard.
Note that at least one byte of padding is guaranteed to be added.
:param data: the data to pad
:param n: the length to pad the data to, defaults to 16
:return: the padded data
"""
... | c4241816fca3e180f793e464e36d7931aa3eb23f | 665,778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.