content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def model_outputs() -> str:
"""
Parses the model outputs in a human readable format. It also gets the
boathouses by reach, so the user knows what boathouses are associated with
each reach.
Returns:
Rendering of the model outputs via the `model_outputs.html` template.
"""
df = latest... | 5,287,800 |
def check_process(process, evaluator, quick, options):
"""Check the helas calls for a process by generating the process
using all different permutations of the process legs (or, if
quick, use a subset of permutations), and check that the matrix
element is invariant under this."""
model = process.ge... | 5,287,801 |
def getFileState(fileName, workDir, jobId, ftype="output"):
""" Return the current state of a given file """
# create a temporary file state object
FS = FileState(workDir=workDir, jobId=jobId, ftype=ftype)
# update this file
state = FS.getFileState(fileName)
# cleanup
del FS
return s... | 5,287,802 |
def to_minimal_subject_jobject(subdomain, minimal_subject):
"""Converts the given MinimalSubject of Subject into an object that
can be passed to to_json()."""
subject_types = cache.SUBJECT_TYPES[subdomain]
attributes = get_attributes_to_render(subject_types)
attribute_jobjects, attribute_is = make_j... | 5,287,803 |
def left_ascending_super_operator(hamiltonian, isometry, unitary):
"""
binary mera left ascending super operator
Args:
hamiltonian (tf.Tensor): hamiltonian
isometry (tf.Tensor): isometry of the binary mera
unitary (tf.Tensor): disentanlger of the mera
Returns:
tf.Tensor... | 5,287,804 |
def main():
""" cria scripts de variaveis.tf
"""
path_to_include = sys.argv[1]
terragrunt_path = sys.argv[2]
common_vars = buildvars(path_to_include, terragrunt_path)
with open("{}/custom.tfvars".format(terragrunt_path), 'w') as file: # Use file to refer to the file object
vars = """
... | 5,287,805 |
def TASK_JUMP_FWD(step=1):
"""Jumps to the next task - eng.jumpCallForward()
example: A, B, TASK_JUMP_FWD(2), C, D, ...
will produce: A, B, D
@var step: int
"""
def _x(obj, eng):
eng.jumpCallForward(step)
_x.__name__ = 'TASK_JUMP_FWD'
return _x | 5,287,806 |
def __save__(
script_name: str, benchbuild: BoundCommand, experiment: 'Experiment',
projects: tp.Iterable[str]
) -> str:
"""
Dump a bash script that can be given to SLURM.
Args:
script_name (str): name of the bash script.
commands (list(benchbuild.utils.cmd)):
List of pl... | 5,287,807 |
def main():
"""Make a jazz noise here"""
args = get_args()
debug = args.debug
min_len = args.min_len
ham = args.hamming_distance
logfile = args.logfile
table = args.table
f1, f2 = args.positional
logging.basicConfig(
filename=logfile,
filemode='w',
level=l... | 5,287,808 |
def print_info(department_num, info):
"""
按照第一层字典的键,值打印员工的所有信息
:param department_num: 部门编号
:param info: 信息的字典
:return: none
"""
print("%s的员工编号是%d,部门编号是%d,月薪%d元." % (info["name"], info["did"], department_num, info["money"])) | 5,287,809 |
def fib_iterative(n):
"""Calcualte n-th element of Fibonacci sequence. Assumes n >= 2
Returns: Fibonacci sequence up to element n, and n-th element of the seq.
"""
fibSeq = [0, 1] # base case
for ii in range(2,n): # note: list(range(2,2)) is an empty list []
fibSeq.append(fibSeq[ii-2... | 5,287,810 |
def discover_functions(
source: Union[Path, str, Module, Iterable[Module], type],
signature: Type[Callable] = Callable, # type: ignore
include_privates: bool = False,
in_private_modules: bool = False,
raise_on_fail: bool = False) -> List[type]:
"""
Discover any functions... | 5,287,811 |
def is_single_file(source_ref_path):
"""return bool"""
return path.isfile(source_ref_path) or uri_validator(source_ref_path) | 5,287,812 |
def write(obj, format, into, mode='w', **kwargs):
"""Write a supported skbio file format from an instance or a generator.
This function is able to reference and execute all *registered* write
operations in skbio.
Parameters
----------
obj : object
The object must have a registered writ... | 5,287,813 |
def translate_connstring(connstring):
"""
Acepta un parámetro "connstring" que tenga la forma user@host/dbname
y devuelve todos los parámetros por separado. Tiene en cuenta los
valores por defecto y las diferentes formas de abreviar que existen.
"""
user = "postgres"
passwd = "pa... | 5,287,814 |
def bytescale(im):
"""
The input should be between [0,1]
output is [0,255] in a unsigned byte array
"""
imout = (im*255).astype('u1')
return imout | 5,287,815 |
def pylsp_commands(config, workspace):
"""The list of command strings supported by the server.
Returns:
List[str]: The supported commands.
""" | 5,287,816 |
def gen_md5(src_byte):
""" gen md5
:param src_byte:
:return:
"""
m2 = hashlib.md5()
m2.update(src_byte.encode("utf-8"))
return m2.hexdigest() | 5,287,817 |
def workout_map_shot(context, request):
"""
Ask for the screenshot of a map, creating one if it does not exist.
A json object is returned, containing the info for the needed screenshot
"""
if context.map_screenshot is None:
save_map_screenshot(context, request)
info = {'url': request.st... | 5,287,818 |
def config_read_only(host):
""" Determine how read_only should be set in the cnf file
Args:
host - a hostaddr object
Returns:
The string value of READ_ONLY_OFF or READ_ONLY_ON.
"""
zk = MysqlZookeeper()
try:
(_, replica_type) = zk.get_replica_set_from_instance(host)
except:... | 5,287,819 |
def to_string(opt):
"""Encodes the option into a string"""
entry = opt.entry
if not tosave(entry):
return False
line = ''
for key, val in entry.items():
if key in ['kid']:
continue
val = '{!r}'.format(val)
val = val.replace(assign_sym,
... | 5,287,820 |
def sleep(seconds):
"""Delay execution by the given number of seconds"""
# This version of "sleep" does not throw an excpetion if passed a negative
# waiting time, but instead returns immediately.
from time import sleep
if seconds > 0: sleep(seconds) | 5,287,821 |
def test_spreadsheet_to_plan_list_1(tmp_path, ext):
"""
Basic test for ``spreadsheet_to_plan_list()`` function. Check that the list of
plans could be saved and then restored from the spreadsheet without change.
Check that the restored parameters have correct types.
"""
# Add plans with a kwarg t... | 5,287,822 |
def search_in_comments(
comments: List[Union[str, Comment]], filter_regex: str
) -> Optional[Match[str]]:
"""
Find match in pull request description or comments.
Args:
comments: List of comments or bodies of comments
to be searched through.
filter_regex: Regex to be used for... | 5,287,823 |
def train():
"""Train fasterrcnn dataset."""
config_train = DatasetConfig().to_dict()
config_train = config_train['_class_data'].train
prefix = "FasterRcnn.mindrecord"
mindrecord_dir = config_train.mindrecord_dir
mindrecord_file = os.path.join(mindrecord_dir, prefix + "0")
print("CHECKING MI... | 5,287,824 |
def create_local_adapter_access(mmu_access, adapter_description, adapter):
"""
Creates a local adapter access.
Parameters
------------
mmu_access : MMUAccess
The mmu access the adapters are connected to
adapter_descriptions : AdapterDescription
The adapter description
ad... | 5,287,825 |
def avro_artifacts(version = "1.8.2"):
"""
version: str = "1.8.2" - the version of avro to fetch
"""
return [
maven.artifact(
group = group_id,
artifact = artifact_id,
version = version,
)
for [group_id, artifact_id] in [AVRO, AVRO_TOOLS]
] | 5,287,826 |
def build_resnet(
repetitions=(2, 2, 2, 2),
include_top=True,
input_tensor=None,
input_shape=None,
classes=1000,
block_type='conv',
attention=None):
"""
TODO
"""
import keras.backend as K
from keras.layers import Input
from keras.layers im... | 5,287,827 |
def bed_generate_random_negatives(in_bed, chr_sizes_file, out_bed,
incl_bed=False,
excl_bed=False,
allow_overlaps=False):
"""
Shuffle given in_bed, generating random negative regions. Optionally,
the region... | 5,287,828 |
def parse(docs):
"""Parse __docs__ text into markdown. Will parse directives like `:param name:` etc"""
# strip leading tabs
if not docs:
return ""
docs = strip_leading_tabs(docs)
if ":param" in docs:
out, title_set = [], False
for line in docs.splitlines():
if ":param" in line:
if not title_set:
... | 5,287,829 |
def store_ticker_to_csv(ticker_history: TickerHistory, file_path: Union[str, io.StringIO]):
"""Store a ticker's historical price information in a csv file.
We should always use this function to store ticker history data since it
ensures that we use a unified frame layout and float precision.
Otherwise,... | 5,287,830 |
def mergersort(arr):
"""Sort function."""
def split(arr):
if len(arr) <= 1:
return lst
mid = len(arr) // 2
left = arr[:middle]
right = arr[middle:]
left = split(left)
right = split(right)
return merge(left, right)
def merge(left, right):... | 5,287,831 |
def default_interface():
"""
Return just the default interface device dictionary.
"""
parser = get_parser()
return parser.default_interface | 5,287,832 |
def ape(y, p):
"""Absolute Percentage Error (APE).
Args:
y (float): target
p (float): prediction
Returns:
e (float): APE
"""
assert np.abs(y) > EPS
return np.abs(1 - p / y) | 5,287,833 |
def new_record(score):
"""Verifie si le score peu entrer dans le top ten"""
topten = load_json('topten.json')
for index, player in enumerate(topten):
if score > player["score"]:
return index
return None | 5,287,834 |
def _mean_of_cycle(data, setup_time=30, data_dict={}):
"""
Calculates mean of raw and reference signal during a zero cycle
setup_time in seconds
"""
row_selection = (data.zerocycle_runtime >= setup_time) & (data.State_Zero == 1)
cycle = data.loc[row_selection].agg(
{
"times... | 5,287,835 |
def proteinnet_tf_dataset(pn_map, batch_size, prefetch=0,
shuffle_buffer=0, repeat=True):
"""
Initiate a TensorFlow Dataset from a ProteinNetMap.
Create a TensorFlow Dataset from a ProteinNetMap, taking the output of the map and adding batching, shuffling and repeating in additio... | 5,287,836 |
def down(services):
"""Bring down one or more services
"""
if len(services) > 0:
_docker_compose('stop', *services)
else:
_docker_compose('down') | 5,287,837 |
def setup_deploy_map(map):
"""
Calls copy_map_dirs, extract_tiles, deploy_map and deploy_json.
"""
copy_map_dirs(map)
extract_tiles(map)
deploy_map(map)
deploy_json(map) | 5,287,838 |
def post_gist(content, description="", filename="file", auth=False):
"""Post some text to a Gist, and return the URL."""
post_data = json.dumps(
{
"description": description,
"public": True,
"files": {filename: {"content": content}},
}
).encode("utf-8")
... | 5,287,839 |
def lru_cache(protected: bool = False, maxsize: int = 128, typed: bool = False):
"""
Wrapped version of the functools.lru_cache decorator which
keeps track of all decorated functions to allow clearing all caches.
:param protected: if set to True, the cache for this function will only be cleared by
... | 5,287,840 |
def mask2rle(mask):
"""
Efficient implementation of mask2rle, from @paulorzp
img: numpy array, 1 - mask, 0 - background
Returns run length as string formated
Source: https://www.kaggle.com/xhlulu/efficient-mask2rle
"""
pixels = mask.T.flatten()
pixels = np.pad(pixels, ((1, 1), ))
ru... | 5,287,841 |
def CreateUniformBuffer(program, uniform_type, uniform_name, default_data=None):
""" create uniform buffer from .mat(shader) file """
uniform_classes = [
UniformBool, UniformInt, UniformUint, UniformFloat,
UniformVector2, UniformVector3, UniformVector4,
UniformBoolVector2, UniformBoolVec... | 5,287,842 |
def root():
"""Base view."""
over10 = Record.query.filter(Record.value >= 10).all()
return str(over10) | 5,287,843 |
def on_wake( va_config ):
"""唤醒后的处理函数: 闪烁远程麦克风上的灯"""
data = { "entity_id": signal_light,
"effect": "Strobe"
}
ha_api.post_service( "light.turn_on", data ) | 5,287,844 |
def quadratic_2d(data):
"""
Compute the quadratic estimate of the centroid in a 2d-array.
Args:
data (2darray): two dimensional data array
Returns
center (tuple): centroid estimate on the row and column directions,
respectively
"""
arg_data_max = np.argm... | 5,287,845 |
def tr_to_final_ph(stage, tr_to_ph, wind_final_perf, final_ph):
""" Computes the number of trials required to reach the final phase.
"""
time = np.where(stage == final_ph)[0] # find those trials in phase 4
reached = False
if len(time) != 0:
first_tr = np.min(time) # min trial is first tria... | 5,287,846 |
def get_shannon_entropy(sequence):
"""Given a sequence, compute the Shannon Entropy, defined in
https://ijssst.info/Vol-16/No-4/data/8258a127.pdf
Args:
sequence (np.array, [t, ]): sequence over which to compute.
Returns:
float: shannon entropy.
"""
# Remove zero entries in sequ... | 5,287,847 |
def interpolate_df(x, name, fp):
"""Interpolate a dataframe
:param x: the x-coordinates at which to evaluate the interpolated values
:type x: array
:param name: the name of the column to use in the dataframe for the x-coordinate
:type name: str
:param fp: the dataframe containing the y-coordina... | 5,287,848 |
def geocoder_to_place(result):
"""Convert a result object from geocoder to a Place object"""
return Place(
name=result.address,
country=result.country,
country_code=result.country_code,
state=result.state,
description=result.description + " - " + result.class_description,... | 5,287,849 |
def query_session_job_status(session, status, user=None):
"""
:type session: Session
:type user: User
"""
session = Session.objects.with_id(session)
if not session:
return None, HTTPStatus.NOT_FOUND
if status not in ['success', 'started', 'dispatched', 'ready', 'failure', 'created']... | 5,287,850 |
def replace_string_newline(str_start: str, str_end: str, text: str) -> str:
"""
re.sub function stops at newline characters, but this function moves past these
params: str_start, the start character of the string to be delted
str_end, the end character of the string to be deleted
te... | 5,287,851 |
def convert_cell(ase_cell):
"""
Convert a parallelepiped (forming right hand basis)
to lower triangular matrix LAMMPS can accept. This
function transposes cell matrix so the bases are column vectors
"""
cell = ase_cell.T
if not is_upper_triangular(cell):
tri_mat = np.zeros((3, 3))
... | 5,287,852 |
def header_required(response, name, callback=do_nothing):
"""Checks that a specific header is in a headers dictionary.
Args:
response (object): An HTTP response object, expected to have a
``headers`` attribute that is a ``Mapping[str, str]``.
name (str): The name of a required heade... | 5,287,853 |
def test_node_catchup_when_3_not_primary_node_restarted(
looper, txnPoolNodeSet, tdir, tconf,
allPluginsPath, steward1, stewardWallet):
"""
Test case:
1. Create pool of 4 nodes
2. Stop not primary node
3. Send some txns
4. Start stopped node
5. Ensure, that restarted node go... | 5,287,854 |
def get_model(point_cloud, is_training, num_class, bn_decay=None):
""" Semantic segmentation PointNet, input is BxNx3, output Bxnum_class """
if isinstance(num_class, int):
num_class = [num_class]
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
end_... | 5,287,855 |
def test_kubernetes_resource_get_uid_incomplete():
"""
This test verifies that KubernetesResource.get_uid() returns None for an undefined resource.
"""
assert KubernetesResource(dict()).get_uid() is None | 5,287,856 |
def get_internal_weights(model):
"""Get all weights of a model without Wrapper specific weights.
Args:
model (keras.models.Model): wrapped model
Returns:
internal layer weights
"""
weights = []
for layer in model.layers:
if isinstance(layer, PruningWrapper):
weig... | 5,287,857 |
def get_visit_date(fecha_inicio):
"""
:param fecha_inicio:
:return: date string YYYY-mm-dd
"""
if not fecha_inicio.strip():
return ""
try:
date_obj = datetime.strptime(fecha_inicio, "%m/%d/%y %H:%M %p")
except ValueError:
try:
date_obj = datetime.strptime... | 5,287,858 |
def text_normalize(text):
"""
Normalize Vietnamese accents
"""
text = re.sub(r"òa", "oà", text)
text = re.sub(r"óa", "oá", text)
text = re.sub(r"ỏa", "oả", text)
text = re.sub(r"õa", "oã", text)
text = re.sub(r"ọa", "oạ", text)
text = re.sub(r"òe", "oè", text)
text = re.sub(r"óe"... | 5,287,859 |
def from_iso8601(s):
""" convert iso8601 string to datetime object.
refer to http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
for details.
:param str s: time in ISO-8601
:rtype: datetime.datetime
"""
m = _iso8601_fmt.match(s)
if not m:
m = _iso8601_fmt_date.match(s)... | 5,287,860 |
def _ExtStorageEnvironment(unique_id, ext_params,
size=None, grow=None, metadata=None,
name=None, uuid=None,
snap_name=None, snap_size=None,
exclusive=None):
"""Calculate the environment for an External Storage... | 5,287,861 |
async def process_invoise_invalid(message: types.Message):
"""
If invoise is invalid
"""
return await message.reply("Номер заказа должен быть цифровой.\nВведите последние 5 цифр заказа:") | 5,287,862 |
def g(i, k, l):
"""
Stage cost. Please check page 384 and page 385 of [1].
:param i: state
:param k: control
:param l: switching
:return: the cost
"""
n = 9
m = 4
X = inverse_map(i, n)
U = inverse_map(k, m)
A = [-28, -12, 12, 16, 0, 0, 0, 20, 16]
B = [-8, 40, 20, 40]... | 5,287,863 |
def request_workload_stop(data):
"""Request to stop a container"""
wl = utils.get_managed_object(data.client, "workload", "workload", data.id_or_name)
if not wl:
return
try:
data.client.request("workload", "request", wl["id"], {"request": {"command": "stop"}})
except client.ObjectNo... | 5,287,864 |
def fit_predict_update(clf, X_train, X_tests,
y_train, y_tests, t_train, t_tests,
fit_function=None, predict_function=None,
rebalancers=(), rejectors=(), selectors=()):
"""Sliding window classification of a timestamp partitioned dataset.
This... | 5,287,865 |
def is_expired(epoch_time):
"""True if current time has passed the provided epoch_time"""
return time.time() > epoch_time | 5,287,866 |
def _assembleInit(xdata, ydata, bounds=None):
"""assemble the initial values based on the spectrum"""
#INTITIALIZE VARIABLES
init = scipy.zeros((3*len(semiEmperical)+1,))
output = scipy.zeros((len(init), 2))
ones = scipy.ones(semiEmperical.shape)
#set baseline
init[0] = ydata.min()#_in... | 5,287,867 |
def main(path: Union[None, str, pathlib.Path] = None):
"""Plot difficulty and engagement for private leaderboard
:param path: Location of json dump from leaderboard api.
"""
if path is None:
path = more_itertools.one(pathlib.Path.cwd().glob("*.json"))
else:
path = pathlib.Path(path)... | 5,287,868 |
def import_settings(method, filename=None, dictconfig:DictConfig=None, parent=None, **kwargs):
"""
Imports a filepath or a DictConfig/SettingsINI object and
applies settings to the dialog.
:param filename: (str, default None)
The file path to the configuration settings.
:param diciguration ... | 5,287,869 |
def strtobool(val: str) -> bool:
"""Convert a string representation of truth to True or False.
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
if not isinstance(val, str):
... | 5,287,870 |
def _convert_value_to_timestamp(value):
"""Convert SQL value to Python datetime object."""
# TODO: Use ciso8601 for faster conversions.
if util.isString(value):
return datatypes.convertTimestamp(value)
else:
return datetime.datetime.fromtimestamp(value / datatypes.SECS_IN_MILLISECS) | 5,287,871 |
def programs2go(program2gene_dict,organism="hsapiens",fdr=0.1):
"""Get GO terms for programs.
... | 5,287,872 |
def test_create_project_unknown_field(client):
"""Make request with unknown field passed."""
# Make sure there's 3 unit admins for unit
create_unit_admins(num_admins=2)
current_unit_admins = models.UnitUser.query.filter_by(unit_id=1, is_admin=True).count()
assert current_unit_admins == 3
# Att... | 5,287,873 |
def api_string_search_choices(request, slug):
"""Return valid choices for a string search given other search criteria.
This is a PRIVATE API.
Return all valid choices for a given string search slug given the partial
search value entered for that slug, its q-type, and the remainder of the
normal se... | 5,287,874 |
def get_screensaver_running_status():
""" Get the status of the running screensaver. """
screensaver = {
'name': 'screensaver_status'
}
is_screensaver_running = False
try:
is_screensaver_running = checkPidRunning(int(get_pid("xautolock")))
except:
screensaver['full_text'... | 5,287,875 |
def _unwrap(variable_parts: VariablePartsType):
"""
Yield URL parts. The given parts are usually in reverse order.
"""
curr_parts = variable_parts
var_any = []
while curr_parts:
curr_parts, (var_type, part) = curr_parts
if var_type == Routes._VAR_ANY_NODE:
var_any.a... | 5,287,876 |
def main():
"""Build template and output to file."""
args = parse_args()
if args.execute_step:
args.execute_step(args) | 5,287,877 |
def position_extrapolate(dist_1_coords, dist_2_coords, delta_heading, delta_distance):
"""
update pdr predictions based on extrapolating last SfM position and direction
:param dist_1_coords: sfm point immediately preceding or following (distance = 1)
:param dist_2_coords: sfm point next to dist_1_coord... | 5,287,878 |
def detect_nose(cv_image):
"""Detects nose based on haar. Returns ponts"""
return NOSE_HAAR.detectMultiScale(cvimage_grayscale(cv_image)) | 5,287,879 |
def cvt_try_stmt(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base:
"""
try_stmt: ('try' ':' suite
((except_clause ':' suite)+
['else' ':' suite]
['finally' ':' suite] |
'finally' ':' suite))
"""
#-# Try(stmt* body, excepthandler* handlers, stm... | 5,287,880 |
def plot(**pdata):
""" Generic plotting routine. Sets basic options then passes parameters to detailed plotting functions. """
# Sanity checks
ndata = 0
assert 'ax' not in pdata or 'save' not in pdata, 'Attempted to save the figure, but the axis has been supplied manually!'
asser... | 5,287,881 |
def get_date_tag(date_format: str = DATE_FORMAT) -> str:
"""Returns a date string tag according to the DATE_FORMAT specifier,
e.g. '2019-04-01'"""
return datetime.now().strftime(date_format) | 5,287,882 |
def translate(image, dx, dy, **kwargs):
"""
Shift image horizontally and vertically
>>> image = np.eye(3, dtype='uint8') * 255
>>> translate(image, 2, 1)
array([[ 0, 0, 0],
[ 0, 0, 255],
[ 0, 0, 0]], dtype=uint8)
:param numpy array image: Numpy array with ran... | 5,287,883 |
def iot() -> None:
"""Internet-of-Things.""" | 5,287,884 |
def stations_by_river(stations, river):
"""Takes a list of stations and returns a list of all the station names
on a specific river in alphabetic order"""
station_names = []
for station in stations:
if station.river == river:
station_names.append(station.name)
station_names = sor... | 5,287,885 |
def read_career_info(carrera_id, test=False):
"""Consulta la información de una carrera según su código."""
query = 'SELECT * FROM carrera WHERE id = %s'
return execute_sql(query, args=[carrera_id], rows=1, test=test) | 5,287,886 |
def get_atomic_species_card(name, **kwargs):
"""
Convert XML data to ATOMIC_SPECIES card
:param name: Card name
:param kwargs: Dictionary with converted data from XML file
:return: List of strings
"""
try:
atomic_species = kwargs['atomic_species']
species = atomic_species['s... | 5,287,887 |
def _get_document_pdf(data: dict, data_key: str, token: str, config: BaseConfig) -> Tuple[bytes, HTTPStatus]:
"""Retrieve the document pdf from the Reports API.
Args:
data: The data to send to the API.
token: The token to access the API.
config: The application config data.
end_... | 5,287,888 |
async def _process_group_platform(hass, domain, platform):
"""Process a group platform."""
current_domain.set(domain)
platform.async_describe_on_off_states(hass, hass.data[REG_KEY]) | 5,287,889 |
def is_url(arg):
"""输入是一个字符串,且值是一个合法的url"""
if not isinstance(arg, str): return False
try:
result = urlparse(arg)
return all([result.scheme, result.netloc])
except ValueError:
return False | 5,287,890 |
def rm(target):
"""Remove target which may be file or dir.
"""
if os.path.isfile(target):
os.remove(target)
else:
shutil.rmtree(target) | 5,287,891 |
def scrape_indeed(database, indeed_client, logger, job_title, locations):
"""
Scrape job data from indeed and save it to the database
:param database: Database to save the indeed data
:param indeed_client: Indeed API client
:param logger: Logger to log activity
:param job_title: Job title to sea... | 5,287,892 |
def upload_product(product_path, cfg, conn, browse_path=None, skip_notify=False):
"""Upload a product to the AWS S3 bucket.
Takes a product path, the subscription ID for the product, the
configuration parameters, and a database connection, uploads the
product to the AWS S3 bucket, and emails the user.
... | 5,287,893 |
def run_hybrid(wf, selector, workers):
"""
Returns the result of evaluating the workflow; runs through several
supplied workers in as many threads.
:param wf:
Workflow to compute
:type wf: :py:class:`Workflow` or :py:class:`PromisedObject`
:param selector:
A function selecting ... | 5,287,894 |
def getCompartment(rxn):
"""
This function is used to obtain the compartment information from reaction of yeastGEM
:param rxn: example acetyl-CoA[m] + L-glutamate[m] -> coenzyme A[m] + H+[m] + N-acetyl-L-glutamate[m]'
:return:
"""
cp1 = ['[c]','[ce]','[e]','[er]','[erm]','[g]','[gm]','[lp]','[... | 5,287,895 |
def compose_class(class_names):
"""Create a composite class from a list of class names."""
classes = []
classes.append(Basic) # Class is the root of inheritance
for class_name in class_names:
if class_name != "basic": # Normally this is not explicitly specified, so is implicit, but even it i... | 5,287,896 |
def copy_outputfiles(model_id: str, new_model_id: str):
"""
Copy outputfiles for a single model_id to a new_model_id
"""
outputfiles = get_outputfiles(model_id)
if type(outputfiles) == Response:
return False
model_outputs = []
changed_uuids = {}
for f in outputfiles:
old... | 5,287,897 |
def create_cancel_jobs_messages(job_ids, when):
"""Creates messages to cancel the given jobs
:param job_ids: The job IDs to cancel
:type job_ids: list
:param when: The cancel time
:type when: :class:`datetime.datetime`
:return: The list of messages
:rtype: list
"""
messages = []
... | 5,287,898 |
def adsorbate_property_type_to_db(
type_dict,
db_path: str = None,
overwrite: bool = False,
verbose: bool = True,
**kwargs: dict,
):
"""
Uploads an adsorbate property type.
The type_dict takes the form of::
{
'type' : 'the_type',
'unit': 'the_unit',
... | 5,287,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.