content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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...
c95f25221a93b26b03bc34e42f7da624a50650c1
3,611,000
from datetime import datetime 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: ...
a64f739b471e5c7d4f9bd20812e7670c6b679845
3,611,001
import re 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 = ...
840aef0f8412d52b71a89c7803f46488883d45b9
3,611,002
from datetime import datetime 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: ...
ff3357035bb4eab0111febcf02a438a0e965a8c4
3,611,003
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...
323c9fae9e6cbc1c1a107dd018bbe5f95520a8fe
3,611,004
import types async def process_invoise_invalid(message: types.Message): """ If invoise is invalid """ return await message.reply("Номер заказа должен быть цифровой.\nВведите последние 5 цифр заказа:")
a72758c137ceaceb17db7114c231ef5d98f63850
3,611,005
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]...
a0f58aea9bc8b2722ee7973d4bb57e260367dd8f
3,611,006
import tqdm import scipy 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 par...
5170a800d289342909e1aec56e8139534229c06d
3,611,007
import time def is_expired(epoch_time): """True if current time has passed the provided epoch_time""" return time.time() > epoch_time
b264fd1d73fe7f9c97592e6bffc27c81574d6bde
3,611,008
import scipy 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] = ...
64989a0df41a7d29028674b8e7663944769ae8a0
3,611,009
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): ...
edf32dd502abe2058ad43deff91cd722509bb1d0
3,611,010
from datetime import datetime 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 / d...
12f28feb0e69c3ed839212c35f3908b6a96e9513
3,611,011
from statsmodels.stats.multitest import multipletests def programs2go(program2gene_dict,organism="hsapiens",fdr=0.1): """Get GO terms for programs. ...
16a23c80216539848b5f87b2e3e1a5bddeef2a88
3,611,012
import hashlib import re import regex 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...
f94136660e8bd3f57044b2d0c985b48e3453e3bd
3,611,013
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'...
5012403025e1b4c5ebbc076f9792eecc11c3a889
3,611,014
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...
de4ed0e788a14204c993aaeee01978ff8e6453f4
3,611,015
def detect_nose(cv_image): """Detects nose based on haar. Returns ponts""" return NOSE_HAAR.detectMultiScale(cvimage_grayscale(cv_image))
0b3c8fa78a9897374b06f89c5479982a9105db04
3,611,016
import token 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...
d7cd6998d3014d3c001ae5b995b88632c562f1e5
3,611,017
from datetime import datetime 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)
cff2c9131323ef7458754b7a67caa99acc435c03
3,611,018
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...
f7abec87f1bb656e256485c2198891f0c967c2b5
3,611,019
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...
078e83affc54b90f2a58ad46cefdd895d9f8c1e6
3,611,020
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)
6a89cd194a65d22b647313836b20d9a8db3e4f39
3,611,021
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...
d10950bb03d1ef5a26b065eb5f8cb928b52bda32
3,611,022
from typing import Tuple import requests import json import logging 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 acc...
4d7315bf8177e40644e1be1c5fc7feec7d9f23d3
3,611,023
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
e5800b46116de8f7a9cd742ad448ecdc9d72eb84
3,611,024
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 ...
b18d7a74fda52fb625680eb178de11f023878c25
3,611,025
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]','[...
2bb34ca20df1a82c6cffcf0c46728fc1687e6db9
3,611,026
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...
a3884b8a5bc5f836b12757a288605f49a57b6e9f
3,611,027
import uuid import requests import os 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 = {...
e0149e74e800baa418d5bb91f6c0b41cd4f23cb7
3,611,028
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 = [] ...
876e255f221b79da3aac10757ff3af9ada50974e
3,611,029
import functools def postprocess(output, length_1, length_2): """Post process the output of the inferred alignment.""" score, paths, sw_params = tf.nest.map_structure( functools.partial(tf.squeeze, axis=0), output) # Stacks SW params, flipping sign of gap penalties for convenience. substitution_scores, ...
e7027fa4d7e8408b491e7fd9febad99e5ac20e98
3,611,030
def select_random_word() -> str: """Selects a random word from the lexicon.""" next_word = lexicon.sample(RandomWordSelectStrategy()) print(f"Chose: {next_word}!") return next_word
412a62c58ea6978e2ca40e5ca614c06589f5ba64
3,611,031
def edit_profile(request, username=None): """Edit user profile.""" # If a username is specified, we are editing somebody else's profile. user = None if username: username = username.replace(" ", "+") if username != request.user.username: try: user = User.obje...
6350f1b118966444db11531f831dd383b26d51ec
3,611,032
import regex def split_at_pattern(text, pattern): """ Split a string where a pattern begins """ obj = regex.search(pattern, text) if obj: start = obj.start() return text[0:start], text[start:] else: return text, ""
a33bc599eb2575fc0ec0e09571095b49fa3ac74b
3,611,033
from typing import List def store_deepdeps(roots:List[Ref])->List[Ref]: """ Return an exhaustive list of dependencies for the `roots` references. References themselves are also included """ frontier=set(roots) processed=set() while frontier: ref = frontier.get() #FIXME processed.add(ref) for dep...
e4f53a76cb235a8b18a2158d38e41c9cd82b7fd3
3,611,034
def focal_lossIII(prediction_tensor, target_tensor, weights, gamma=2., epsilon=0.00001, ): """Compute loss function. This function was adapted from the Tensorflow issues section on GitHub. Args: prediction_tens...
4f9b332165ce2565344de4d62dd7e73e2dee35af
3,611,035
def draw_vertical_bar(info:pd.Series)->plt.Figure: """Dibuja un vertical bar chart basado en un analisis previamente hecho Args: info (pd.Series): Los datos a graficar Returns: [plt.Figure]: La figura armada """ plt.bar(info.index, height=info) return plt.gcf()
93b46e3dd5f15d8c8d619db79145b10fd50eb391
3,611,036
import collections def set_seed_iftrue(condition, seed=10): """ Fix the seed for random test. Parameters ---------- seed : int Random seed passed to np.random.seed Returns ------- decorator : function Decorator which, when applied to a function, sets the random ...
d791bb843594ea64f795b517334da6364a9d3e95
3,611,037
from datetime import datetime def get_current_utc_time(): """Return string representation of current time in UTC.""" utcnow = datetime.datetime.utcnow() return str(utcnow.timestamp())
0f5be8928a6706e9fe8db497d314502db35b6317
3,611,038
import unittest def _split_extension_test(ctx): """Unit tests for paths.split_extension.""" env = unittest.begin(ctx) # Try some degenerate cases. asserts.equals(env, ("", ""), paths.split_extension("")) asserts.equals(env, ("/", ""), paths.split_extension("/")) asserts.equals(env, ("foo", ""...
c60a5ce93cc746a7e0c1d140931298c9e54712a0
3,611,039
import configparser def get_cluster_details(): """ Gets the credentials from the config file """ config = configparser.ConfigParser() config.read_file(open('dwh.cfg')) KEY = config.get('AWS','KEY') SECRET = config.get('AWS','SECRET') DWH_CLUSTER...
a7d19c76e134b74d18a37289c16221064664c036
3,611,040
import select def get_publication_comments(project, publication_id): """ List all comments for the given publication """ connection = db_engine.connect() publications = get_table("publication") publication_comments = get_table("publication_comment") statement = select([publications.c.publi...
286c6ab192fdd5d235bf52ae4191ef37a1b99ab5
3,611,041
from typing import Dict from typing import Optional def parse_genapp_customer(genapp_record: Dict) -> Optional[X12Demographics]: """ Parses a GenApp Customer from a JSON response to a X12Demographics model :param genapp_record: The GenApp Customer record :return: The X12Demographics model for the cust...
4fae35ea6f8fc57639f0eb7672eae7d359b0c1f4
3,611,042
from typing import Union from pathlib import Path import os import errno def make_dirs(directory: Union[str, Path], mode: int = 0o777) -> bool: """Wrapper around os.makedirs to make it suitable for using in a multithreaded/multiprocessing enviroment: Unlike the regular function, this wrapper does not thro...
f0d79ee882af787c88856f994914e7e79ba70e3d
3,611,043
def get_best_shift(img): """ DESCRIPTION: Calculate the center of mass of the input image and return the best shift amount to center an image on the character. INPUT: Image OUTPUT: Calculated shift amount for x and y directions """ # Calculate the center of mass through scipy center_y, c...
328a48d0a2c041c55260f591ce50ef93f3265b63
3,611,044
def main(): """ The main function to execute upon call. Returns ------- int returns integer 0 for safe executions. """ print("Program to check positive, negative, or zero input.") temp = check_number_sign() return 0
cd551c867c50b258bfd109b1c6ad326a6d039b19
3,611,045
import os def read_openPMD_params( filename ): """ Extract the time and some openPMD parameters from a file Parameter --------- filename: string The path to the file from which parameters should be extracted Returns ------- A tuple with: - A float corresponding to the tim...
cff453fd3a844c55e467d0dd9fd74704e0e9f3c6
3,611,046
import torch def class_to_val(raw_scores): """ Finds the highest softmax for each class :param raw_scores: tensor (batch, verts, classes) :return: highest class (batch, verts) """ cls = torch.argmax(raw_scores, dim=2) val = (cls + 0.5) / DEEPCONTACT_NUM_BINS return val
9d42a6d3457fd98b2174dc7bf7ffbf444aef5b38
3,611,047
import functools import inspect import six def map_arg(**maps): """ Apply a mapping on certains argument before calling the original function. Args: maps (dict): {key: map_func} """ def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): argmap = i...
4b327d3167a6c9bd4da84671a661767db04bcb6b
3,611,048
def create_spark_session(): """Create an apache spark session on AWS""" spark = SparkSession \ .builder \ .config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:2.7.0") \ .getOrCreate() return spark
3077bb7bb67c404131b04119e8791e64758c6362
3,611,049
def clean_catalog(ukidss_catalog, clean_band='K_1', badclass=-9999, maxerrbits=41, minerrbits=0, maxpperrbits=60): """ Attempt to remove 'bad' entries in a catalog. Parameters ---------- ukidss_catalog : `~astropy.io.fits.BinTableHDU` A FITS binary table instance from the ...
4fa593f758a645bf49fe7479a0876e6a1fc6068b
3,611,050
def setmask(arr, x1=None, x2=None): """setmask(arr, x1, x2) arr = 1D arr x1 = lower value x2 = upper value by default it returns a mask that is the full range of arr returns ======= mask, x1, x2 if input x1 and x2 are out of bounds then it sets x1 and x2 to the boundry of arr...
a2e97675045dfb67ba23838493ce19020453c4f9
3,611,051
def get_tree(splits): """Convert a dict keyed by splits into the equivalent tree. The dict values should be dicts appropriate for the params input to TreeBuilder.create_edge. """ Edge = TreeBuilder().create_edge # Create a star from the tips tips = [] the_rest = [] for split, params...
29fbdb3682713cdf18174981bfc8d71f2d188a2f
3,611,052
import hashlib def create_hash(secret: str, url: str) -> str: """Create a hash of the secret and url.""" s = f'{secret}{url}' return str(hashlib.md5(s.encode()).hexdigest()[0:8])
891fcc45fe7706a984fb9282ab17887710e6da0a
3,611,053
def get_model_name(model): """Obtains the model name for a Scikit-Learn, ML Studio estimator Obtains the model name for Scikit-Learn estimators, ML Studio estimators, and GridSearchCV and RandomSearchCV objects Parameters ---------- model : BaseEstimator, GridSearchCV, RandomSearchCV ...
a6385bf7795a0966bfb0a61c9a74f1e1ca969802
3,611,054
import collections def create_script_to_chars(): """Returns a mapping from script to defined characters, based on script and extensions, for all scripts.""" load_data() result = collections.defaultdict(set) for cp in _defined_characters: if cp in _script_data: result[_script_da...
e837b1993e17971a97cc48c35bf0b1db01e6d59c
3,611,055
import math def get_filter(): """ Вывод товаров на странице каталогов :return: context """ price = dict() seller = Seller.objects.values('title', 'title_en').all() price['max'] = math.ceil(seller.aggregate(max=Max('catalog__price')).get('max')) price['min'] = math.floor(seller.aggrega...
8089414ee80db8e5f45f8b41647a0a31f7234138
3,611,056
from datetime import datetime def email_weekly_orders_csv(current_menu_meal_totals): """ Emails all the current admins an email containing every users current order. Email contains a csv file as well. Returns total emails sent and the email for every admin. """ all_orders = get_all_users_order...
2bcb92ae291ab0e031e0c920e43ccad2d05969c7
3,611,057
from typing import Sequence from typing import Optional from typing import Tuple def ConvTranspose(out_chan: int, filter_shape: Sequence[int], strides: Optional[Sequence[int]] = None, padding: str = Padding.VALID.name, W_std: float = 1.0, ...
0e3fdc2fc414e2198b2b4696923047fd1c3da958
3,611,058
import time def wait_for_result_is_none(method, timeout, wait_msg=None): """Calls the method until the return value is None.""" count = 0 end_time = time.time() + timeout while True: try: result = method() if result is None: return True except: ...
e90d40b319762da41f315820c00e6d8b04cb5565
3,611,059
def connect(db_uri): """Connect to a database to record deployments. :param db_uri: Database URI to connect to :return: SQLAlchemy session for interacting with this database """ engine = create_engine(db_uri, convert_unicode=True) session = scoped_session(sessionmaker(autocommit=False, autoflus...
4063331d42c29e0c012e513a978c8bad1ffc935b
3,611,060
def final_run_could_be_extended(values, end_idx): """Heuristically see if the value run at end_idx could be extended Returns true if there is a run at end_idx, if end_idx is not the last value, and if the value after end_idx could be part of a run. To keep this constant-time, we aren't checking if the...
99244baa3379f261d9cc2e5475b33c824dff6781
3,611,061
import os import sys def merge_filename(filename, pat, sep): """ Apply a merging pattern to a filename. Sections of the base filename are kept according to the provided pattern. Args: filename: The filename to merge. pat: The merging pattern to use. sep: String separating fil...
e4e92818e6ff4fec65d44a19950ec062b5d7c10e
3,611,062
from typing import Optional import http async def fetch_geoloc_web(ip: IPAddress) -> Optional[Geolocation]: """Fetch geolocation data based on ip (using ip-api).""" url = f"http://ip-api.com/line/{ip}" async with http.get(url) as resp: if not resp or resp.status != 200: log("Failed to...
478e66fe31d16f28a90ad640bbae40dab4b63f6a
3,611,063
def task_query(job_key=None, hosts=None, job_keys=None): """Creates TaskQuery optionally scoped by a job(s) or hosts. Arguments: job_key -- AuroraJobKey to scope the query by. hosts -- list of hostnames to scope the query by. job_keys -- list of AuroraJobKeys to scope the query by. """ return TaskQuery( ...
2728aedfc31d1f6299e457292cd23fddd5b62ea2
3,611,064
def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): """ Returns the previous session date in the calendar before the provided date. Parameters ---------- date : Timestamp The date whose previous date is needed. Returns ------- Timestamp The previ...
aafe234037da69ffc07474e48106ff29c22c46d9
3,611,065
def measure_distance_euclidean(point1, point2): """Return euclidean distance between two shapely Points as float.""" if (type(point1) != Point) or (type(point2) != Point): raise TypeError("Only Points are supported as arguments, got {} and {}".format(point1, point2)) return point1.distance(point2)
42c26523df3568029ba705e420abee91b850bef0
3,611,066
import struct def _unpack_asf_image(data): """Unpack image data from a WM/Picture tag. Return a tuple containing the MIME type, the raw image data, a type indicator, and the image's description. This function is treated as "untrusted" and could throw all manner of exceptions (out-of-bounds, etc.)...
cd6b4646cb8b4c10043935761cd2d6929f27fa68
3,611,067
def dicenet_w3d2(**kwargs): """ DiCENet x1.5 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,' https://arxiv.org/abs/1906.03516. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/....
11a460ad45dc97be6ce9125c2a7b4c2c7fea33a2
3,611,068
def patch_vertices(vertices,pole, width): """ find 'vertices' within the cone of 'width' degrees around 'pole' """ return [i for i,v in enumerate(vertices) if np.abs(np.dot(v,pole)) > np.abs(np.cos(np.pi*width/180))]
ccefb15414bfa3fc6c24eb82687fb5f6d84197d8
3,611,069
def plot_gcam_reclassified(gcam_df, landclass, start_yr=2015, through_yr=2100, interval=5): """Plot GCAM landclass allocation over a time period reclassified to Demeter land cover types.""" yrs = [str(i) for i in range(start_yr, through_yr + interval, interval)] lc_mapping = gcam_to_demeter_lc_map() ...
03892897c1e18a0f3e7320783b9b7471de4ec68d
3,611,070
def get_sigmas_index(indices): """Takes a tuple and gives back a length-16 array with a single 1. Parameters ---------- indices: a tuple of two integers, each one between 0 and 3. Examples -------- >>> get_sigmas_index((1, 0)) array([ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0...
a7120ca1633d3ce2fca9466b36ed6fdce0bfd18e
3,611,071
def authenticated(): """Utility function checking if the current user is logged in or not.""" fas_user = None try: fas_user = flask.g.fas_user except (RuntimeError, AttributeError): pass return fas_user is not None
0a8c1071897d2914bb00a21b7bd2660d37c1cb32
3,611,072
from azureml._base_sdk_common.workspace.models import Workspace def _get_or_create_workspace(auth, subscription_id, resource_group_name, workspace_name, location): """ Gets or creates a workspace. :param auth: :type auth: azureml.core.authentication.AbstractAuthentication :param subscription_id: ...
c7440195d85d680acb8fa8b3be48c7fbcdc87435
3,611,073
from typing import Dict from typing import Any from typing import Optional def add_calculated_fields(*, current_item: Dict[str, Any], initial_status, current_status, position_list, lap_lis...
cc7bca6ddb9c98216285bdd5807b488a9b24ee5b
3,611,074
def check_if_all_passed(statuses): # type: (Dict[str, str]) -> bool """ Check if all items in supplied `statuses` dict passed parsing and conversion. :param statuses: dictionary init info statuses (files/nodes to their status) :type statuses: dict :return: boolean indicating if all files and no...
e44b363684fd072bdd4a1859a0943dd829e78645
3,611,075
def get_database_connection(): """Returns a connection to Redis DB or creates a new one if it does not already exist.""" global _database try: return _database except NameError: config = get_config() _database = redis.Redis(host=config['redis_db_address'], ...
47bbc7af54b53efc9b9464810b4d7cb6825bf69c
3,611,076
def _get_config(**kwargs): """ Return configuration """ config = { "filter_id_regex": [".*!doc_skip"], "filter_function_regex": [], "replace_text_regex": {}, "proccesser": "highstate_doc.proccesser_markdown", "max_render_file_size": 10000, "note": None, ...
437dfc35b5f24b8322df9ef7415577e9437187e8
3,611,077
import sysconfig import sys import re def get_neon_core_root(): """ Determines the root of the available/active Neon Core. Should be the immediate parent directory of 'neon_core' dir Returns: Path to the core directory containing 'neon_core' """ site = sysconfig.get_paths()['platlib'] ...
4785fd737a679d87be0fa065733bc39993cbf28a
3,611,078
from typing import Union import torch from typing import List def signal_framing( signal: Union[torch.Tensor, ComplexTensor], frame_length: int, frame_step: int, bdelay: int, do_padding: bool = False, pad_value: int = 0, indices: List = None, ) -> Union[torch.Tensor, ComplexTensor]: ""...
dbbc1cd37deb2fb4a08eea3b7f026a691b0801f6
3,611,079
def test_abstract_classes(): """很多时候我们会觉得mongoengine.Document提供的方法不够多, 我们会想要自定义 一些方法。为了减少冗余代码, 我们想要将通用的方法以继承的方式实现。这时, 我们 需要建立一个新的Document的基类, 然后用户的类都从这个基类继承而来。 具体做法如下: Ref: http://docs.mongoengine.org/guide/defining-documents.html?#abstract-classes """ class ExtendedDocument(Document): ...
3e480cb95ffe98ba483b4f3249c69e833f56917d
3,611,080
from typing import Dict def evaluate_conditional(string: str, fields: Dict[str, str]) -> bool: """ Evaluates a conditional from $string on a Anki card template using the field values $fields. """ field_name = get_field_name(string) if field_name not in fields: logger.warning("Field '{}' from c...
39a96ff101eee733ea7fe3cb976abb5ab55f0b25
3,611,081
def has_all_channels(stream, channels, starttime, endtime): """Check whether all channels have any data within time range. Parameters ---------- stream: obspy.core.Stream The input stream we want to make certain has data channels: array_like The list of channels that we want to have...
c6e658e6f0fc4816b9a2faeb4d129c951bb5749f
3,611,082
def world_xyzn_im_to_pts(world_xyz, world_n): """Makes a 10K long XYZN pointcloud from an XYZ image and a normal image.""" # world im + world normals -> world points+normals is_valid = np.logical_not(np.all(world_xyz == 0.0, axis=-1)) world_xyzn = np.concatenate([world_xyz, world_n], axis=-1) world_xyzn = wo...
307df640c9cbcc4d09241b0f2a34c4c9f2e99b1e
3,611,083
def clean_email_default(email, allowed_domains): """ Clean email address and check if it has allowed domain :param email: emailadress in string :param allowed_domains: FQDN of allowed domain of mail :return: cleaned lowercase email addresss string or ValidationError """ email = email.strip(...
46e2e38729b7d2e90659995066f886f599e8d952
3,611,084
import sys import os def GetSourceImages(local_dir, pro): """Downloads the various sources that we need. Of note: Because Express does not include ATL, there's an additional download of the 7.1 WDK which is the latest publically accessible source for ATL. When |pro| this is not necessary (and CHROME_HEADLESS...
afb7dd36c5bebf93499682c5b95bd595d0911b17
3,611,085
def add_binary_prefix(value: float) -> str: """ Function that converts a number to his version with Binary prefix @input value (an integer) @example: >>> add_binary_prefix(65536) '64.0 kilo' """ for prefix in BinaryUnit: numerical_part = value / (2**prefix.value) if numer...
ac938217c26be7032dd87fc060593b1155179157
3,611,086
def exhibit_type(elem): """Returns the exhibit type of the file.""" val = attr_val(elem, 'exhibitType') if val is None: return 'EX-101' return val
63078fa4fb75a757b00c9f32d68bd00caf9b432d
3,611,087
def get_mailboxes_v2(): """ Get all mailboxes - including unverified mailboxes Output: - mailboxes: list of mailbox dict """ user = g.user mailboxes = [] for mailbox in Mailbox.query.filter_by(user_id=user.id): mailboxes.append(mailbox) return ( jsonify(mailboxe...
d7a74e0a983ab8aa890e684c3e8e7d45e54096a8
3,611,088
def angle_to_direction(input_angle, full=False, level=3): """Convert the meteorological angle to directional text. Works for angles greater than or equal to 360 (360 -> N | 405 -> NE) and rounds to the nearest angle (355 -> N | 404 -> NNE) Parameters ---------- input_angle : numeric or array-l...
77e3ac983357741073b48dba958066e080ec4498
3,611,089
def asset(ses, ticker_sym): """ function that returns a single asset object given for a given ticker """ return _assets_response_handle(_get_assets_json( ses, ticker=ticker_sym), ticker=ticker_sym)
2a09e22995c50b1083f172d2003ac311a685c7a1
3,611,090
import time def multi_check_output(cmd_lst, stderr=None, env=None, num_retry=NUM_RETRY): """ This routine should always return a (unicode) string. NOTE: Under python3, sp.check_output returns bytes by default, so we set universal_newlines=True to guarantee strings. """ itry, cmd_retry = 1, True ...
2b137081dd75bda1f0b2623016257259819b2ebc
3,611,091
async def github_get_pr_reviews(client_session, owner, repo, pr_number): """ Get the reviews of a given pull-request. Args: client_session: aiohttp ClientSession. owner: owner of the repository at github. repo: repository name at github (without owner part). pr_number (int):...
b934628696534f6a33a5cee081b181b0700916d0
3,611,092
def read_array_objects(container, size, items, dkey, akey, obj): """Read data from the container. Args: container (DaosContainer): the container from which to read objects size (int): number of arrays to read items (int): number of items in each array to read dkey (str): dkey us...
acfc0ebf60008ee2f27108e4cb120e44938afb05
3,611,093
def get_nth_digit(N, n): """ return the nth digit from an N digit number >>> get_nth_digit(12345, 3) 4 >>> get_nth_digit(12345, 7) Traceback (most recent call last): ... IndexError: string index out of range """ return int(str(N)[n])
25c01c14589fb091154e8509a84f98811946938f
3,611,094
def check_device() -> str: """Check if there is an available remote :return: The name of the device """ cmd = adb_command_handler('devices').strip().split('\n') devices = [] device = '' del cmd[0] for line in cmd: if 'device' not in line: continue device = li...
2f86e6dbff6a5a07bb07789383ff6aaa2f65f8d8
3,611,095
def prints_ofp(msg): """ Args: msg: OpenFlow 1.3 message unpacked by python-openflow Returns: """ try: msg_types = {0: print_ofpt_hello, # ok 1: print_ofpt_error, # ok 2: print_ofpt_echo_request, # ok 3: print_ofpt_ec...
034bc765b2580eac2afd045aaab730e5470fe54d
3,611,096
import os def split_path(filepath): """Return filename and extension of file""" return os.path.splitext(filepath)
a949afd956f5c41e5a3f137383ae61da88b330b0
3,611,097
from typing import Optional from pathlib import Path import os def generate_tmp_file_path( tmpdir_factory, file_name_with_extension: str, tmp_dir_path: Optional[Path] = None ) -> Path: """Generate file path relative to a temporary directory. :param tmpdir_factory: py.test's `tmpdir_factory` fixture. ...
e922aa51f97ec8db4fa3181f4f8193038fc2f7ea
3,611,098
def unitTest(): """A simple unit test for the am_ribbon command""" curve = cmds.curve(d=3, p=[[-3,0,-5], [-2.75,0,-3.916667], [-2.25,0,-1.75], [0,0,0], [2.25,0,1.75], [2.75,0,3.916667], [3,0,5]], k=[0,0,0,1,2,3,4,4,4]) # test create mode print '---TESTING CREATE---' ribbon = cmds.am_ribbo...
601d24668442c529c8d7cad0d4d17dbc6697f781
3,611,099