content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def show_topics(A, vocabulary, topn=5): """ find the top N words for each of the latent dimensions (=rows) in a """ topic_words = ([[vocabulary[i] for i in np.argsort(t)[:-topn-1:-1]] for t in A]) return [', '.join(t) for t in topic_words]
886e4afcfa3594f352474ca54ce79d430f09e508
3,615,300
def parse( handle, sequences=None, query_file=None, query_ids=None, max_evalue=0.01, min_identity=30, min_coverage=50, ): """Parse Tabular results from remote BLAST search performed via API. Since the API provides no option for returning query coverage, which is a metric we want...
55ade045fa1f2828059036e55a474f80f129fd37
3,615,301
def read_graph(in_graph, in_graph_is_binary=True): """Reads input graph file as GraphDef. :param in_graph: input graph file. :param in_graph_is_binary: whether input graph is binary, default True. :return: input graphDef. """ assert gfile.Exists(in_graph), 'Input graph pb file %s does not exist...
ba235b503737f35284f85234ca82297775317e4f
3,615,302
import skimage # Defer slow imports import skimage.transform # Defer slow imports import scipy def _find_anomalies(cy_ims, iqr_bounds): """ Given a cy stack of images for a field, find the anomalies. Arguments: cy_ims: array (n_cycles, height, width) iqr_bounds: The inter-quartile-range...
4f38605fe8b80f8c37c4c0b80c9956aeb6908aed
3,615,303
from typing import Mapping from typing import Any import uuid from datetime import datetime def new_contract_from_user(data: Mapping[str, Any]) -> "SmartContractModel": """ Used in creating new contracts Input: SmartContract::L1::Create DTO Returns: SmartContractModel object """ if data.get("v...
e87485b7ebccaf4d6b4b2f4e869a674a047e2673
3,615,304
def mes_com_acentos(mes_a_mudar): """Retorna Mês com Maiúsculas e Acentos.""" meses_a_exibir = { 'janeiro': 'Janeiro', 'fevereiro': 'Fevereiro', 'marco': 'Março', 'abril': 'Abril', 'maio': 'Maio', 'junho': 'Junho', 'julho': 'Julho', 'agosto': 'Agos...
8361d7e747d524242eeb572b839305d58021b35d
3,615,305
def _load_glove(path): """ Loads GloVe pre-trained embedding model via gensim """ tmp_file = get_tmpfile('temp_glove_w2v_format.txt') glove2word2vec(path, tmp_file) return gensim.models.KeyedVectors.load_word2vec_format(tmp_file)
d3eb03153b65739dc5d991c4ca9984207dd81d6e
3,615,306
import logging def change_settings(settings: SettingsModel) -> bool: """ Change downloader settings by re-initializing the downloader. ### Arguments - settings: The settings to change. ### Returns - returns True if the settings were changed. """ settings_dict = settings.dict() ...
9f7d03933a6b86affabe881859ebbde099fb447f
3,615,307
def flip_chars(items): """Flip all chars in an input str of items.""" return ''.join([flip_char(x) for x in items])
f2e53101b66d625a8bb327699aa7216e48987bdd
3,615,308
def run_prog(code): """Meh """ mem = {} mask = None for line in code: op, args = parse_line(line) if op == "MASK": mask = args elif op == "MEMSET": for addr in apply_mask(mask, args["addr"]): mem[addr] = args["value"] return sum(m...
04d83fa510a0344bbaf354ef05792a62545ce39a
3,615,309
def get_best_k(use_saved_k, labvitals_time_series_list_val, labels_val, k_list): """gets the best_k either from the database or from finding it with the help of the method find_best_k Args: use_saved_k (Bool): should the value be taken from the databse? labvitals_time_series_list_val (Li...
88e13b52b34ac0c3ec22f786399bdc21fcad0392
3,615,310
def interp_operator_2d( dims_in, dims_out, pack_index_in=None, pack_index_out=None ): """Make one interpolation operator to work on a "flattened" 2D array Do this by tiling and repeat the separate interpolation operators Parameters ---------- di...
d316b47558643e03d436c6831253b8f205ab662f
3,615,311
def x2p(X = Math.array([]), tol = 1e-5, perplexity = 30.0): """Performs a binary search to get P-values in such a way that each conditional Gaussian has the same perplexity.""" # Initialize some variables print("Computing pairwise distances...") (n, d) = X.shape; sum_X = Math.sum(Math.square(X), 1); D = Math.add...
7e85e26a7dfd446abfe1546860c7676b4d44287d
3,615,312
import base64 def b64encode(value): """ Encode a value in base64 """ return base64.b64encode(value)
988abf5a9d2c0c1f38f16fbf8f80fd43aa115223
3,615,313
import os import pkgutil import importlib def load_module_attrs(pkg_path, func, recursive=False): """Get attributes from modules, use ``func`` to filter attributes, ``func`` must return a list. """ attrs = list() root_pkg = os.path.basename(ROOT_DIR) pkg_name = root_pkg + pkg_path.split(root_p...
386a62ae75dbb9f769c734fff980131983410b48
3,615,314
import os def get_audio_embedding_model_path(input_repr, content_type): """ Returns the local path to the model weights file for the model with the given characteristics Parameters ---------- input_repr : "linear", "mel128", or "mel256" Spectrogram representation used for model. c...
8a3d0a5d09896467b672e8dde47b1a6a500cdce8
3,615,315
import os import sys import subprocess def get_git_sha1(): """Try to get the git SHA1 with git rev-parse.""" git_dir = os.path.join(os.path.dirname(sys.argv[0]), '..', '.git') try: git_sha1 = subprocess.check_output([ 'git', '--git-dir=' + git_dir, 'rev-parse', ...
38e1bb662229939f5f1aeec396e4c9d11c93bb73
3,615,316
def update(profile_id): """ Update A Profile --- /api/profiles/edit/{profile_id}: put: summary: Update A Profile. security: - APIKeyHeader: [] tags: - Profile parameters: - in: path name: profile_id required: true schema: ...
1314df4f9b452423e995e35513d607fd13043160
3,615,317
def kornia_list(magn: int = 4): """ Returns standard list of kornia transforms, each with magnitude `magn`. Args: magn (int): Magnitude of each transform in the returned list. """ transform_list = [ # spatial K.RandomHorizontalFlip(p=1), K.RandomRotation(degrees=90.0...
fd6fa7a1214484bc0f7c1f6511fe4b525f7d15c5
3,615,318
def phrase_replacement(structured_phrases, short_phrases): """replaces phrases in structred_phrases with phrases from short_phrases if the short phrase is contained in the longer phrase""" short_set = set(short_phrases) return [_rewrite_doc(doc, short_set) for doc in structured_phrases]
6971ab9044ee43da9172dcf15845a8e52890bd64
3,615,319
from copy import copy def struct(typename, field_names, verbose=False): """Returns a new class with named fields. >>> Point = struct('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional ar...
74dcfd6e0a0c83a6679691e49f09a528eb8e6a4a
3,615,320
def zip_tasks_verbose_output(table, stdstreams): """Zip a list of strings (table) with a list of lists (stdstreams) :param table: a formatted list of tasks :param stdstreams: for each task, a list of lines from stdout/stderr tail """ if len(table) != len(stdstreams): raise ValueError('Can on...
33d74cd274ec39330cbc127a3088a430b80d234a
3,615,321
def stable_softmax(x, axis=2): """ Numerically stable softmax: softmax(x) = e^x /(sum(e^x)) = e^x / (e^max(x) * sum(e^x/e^max(x))) Args: x: An N-dimensional array of floats axis: The axis for normalizing over. Returns: output: softmax(x) along the specifi...
144e65a287591901316b29932ddbb1b989a1c199
3,615,322
from typing import Union def is_chinese(x: Union[int, str]) -> bool: """Recognizes whether the server/uid is chinese :param x: A server or a genshin uid """ return str(x).startswith(("cn", "1", "2", "5"))
e63d7e98a3dcdaeb9f9853715dcd8f466d9a293b
3,615,323
def add_edit_button(user_id): """Determines if home page requires an edit button Args: user_id: user_id being used to request home page Returns: list list of dictionaries containing buttons """ button_list = [ { "textButton": { "text": "START ...
0bcc8a9e81af2b809ef6e2cbab0bba9c7d188258
3,615,324
def not_found(error): """ error handler """ return make_response(jsonify({'error': 'Not found'}), 404)
b09e9c47df42a40c3c241d5b6631726b7bebb580
3,615,325
import resource def port(port_data): """Represents a view for a port object""" keys = ('id', 'network_id', 'mac_address', 'fixed_ips', 'device_id', 'admin_state_up', 'tenant_id', 'status') return resource(port_data, keys)
fc4d987aa75c7548f8f9a2edfb00e5ccbf3849ad
3,615,326
from matplotlib._pylab_helpers import Gcf def connection_info(): """ Return a string showing the figure and connection status for the backend. This is intended as a diagnostic tool, and not for general use. """ result = [] for manager in Gcf.get_all_fig_managers(): fig = manager.c...
e2b0fa877a02b19a2306269b1d8fac0901f7a0c4
3,615,327
def get_bridge(ip): """The name to be used for the bridge interface connecting the VMs and the host.""" return "spirebr%s" % ip.packed.hex().upper()
898347580052cce492bb12d60668fc7661a7f811
3,615,328
def test1(): """test case 1 Returns: matrix: np.array vector b: np.array vector c: np.array vector j: np.array """ A = np.array([ [-2, -1, -4, 1, 0], [-2, -2, -2, 0, 1] ]) b = np.array([-1, -1.5]) c = np.array([-4, -3, -7, 0, 0]) J = np.ar...
ca1836d985fef266aeb67d7b74ddfbfa2f20f053
3,615,329
import os def read_text_file(file_path): """ Read text file utility Read the text file from the given path if file is not present, exit params: file_path - string returns: file_data - list """ logger.debug("<<<< 'Current Executing Function' >>>>") if os.path.exists(file_pat...
4f5afc570b969bd3f0e7f0382c015298fb677244
3,615,330
import pickle def try_deserialize_handler(serialized_handler): """Reverse function of try_serialize_handler. Args: serialized_handler: serialized handler str or None. Returns: handler instance or None. """ if serialized_handler: return pickle.loads(serialized_handler)
bc91e26c65add4e74affd148b8ed550fe923c925
3,615,331
from typing import Optional async def load_from_server( component_builder: Optional[ComponentBuilder] = None, project: Optional[Text] = None, project_dir: Optional[Text] = None, remote_storage: Optional[Text] = None, model_server: Optional[EndpointConfig] = None, wait_time_between_pulls: Optio...
94e2e8a477af31761756c1ed1d887c75b0177a9a
3,615,332
def unravel_index(ind, tensor_shape): """no official tensorflow implementation for this yet; this is based on one proposed in https://github.com/tensorflow/tensorflow/issues/2075 """ ind = tf.expand_dims(tf.cast(ind, tf.int64), 0) tensor_shape = tf.expand_dims(tf.cast(tensor_shape, tf.int64), 1) ...
64070c8a832843884436bbc1107ea5be946dd7be
3,615,333
def write_tfrecord_from_tensorrec_dataset(tfrecord_path, dataset): """ Writes the contents of a TensorRec Dataset to a TFRecord file. :param tfrecord_path: str :param dataset: tf.data.Dataset :return: str The tfrecord path """ session = get_session() iterator = create_tensorrec_itera...
6108e384cdb1ecefa3b87ee1d11f78c3dbc56b26
3,615,334
def _convert_universal_format(format): """Converts Universal Date Time Format to Python strftime format string""" i = 0 token_string = format python_format = format token_map = sorted(_DATETIME_FORMAT_MAP, key=lambda t: t[0], reverse=True) calculated_tokens = {} for f in token_map: i...
d9b747c044e37317352ab402da080845ef39b2df
3,615,335
from typing import Tuple def get_loader(dataset: str, batch_size: int) -> Tuple: """ :param dataset: The name of the dataset we want to use. Either JSB_Chorales, MuseData, Nottingham, or Piano_midi. :param batch_size: how many sequences to train on at once. :return: DataLoaders for training, testing, ...
bc900e42f7d1523dbc1a629d27f4668caa6e0a10
3,615,336
def hardwareVersionToString (hwversion): """ Converts a raw integer value into a human readable string a.b.c.d. :param int hwversion: raw value as received from the generator :return str: a human readable string 'a.b.c.d'. """ if ((hwversion >> 30) & 1) != 0: # new format 30-22 + 21-16 # mask here with 0xFF ...
1f1fab23706e05fa593ef4cf56f3ec4e1a6f4c6f
3,615,337
def pareto_mtl_search(ref_vecs,i,t_iter = 100, n_dim = 20, step_size = 1): """ Pareto MTL """ # randomly generate one solution x = np.random.uniform(-0.5,0.5,n_dim) # find the initial solution for t in range(int(t_iter * 0.2)): f, f_dx = concave_fun_eval(x) weights...
245a9358ea64db0c667025f18599a6f1fd996229
3,615,338
def get_region_stats_np(im: np.ndarray, region: Box) -> Stat: """Get array region stats using Numpy. Parameters ---------- im : np.ndarray Input image to analyze region : Box Coordinates for region Returns ------- Stat Stat object containing various statistics o...
bc7fcad29c8638123d7b2d0bb7a0408e794d6dec
3,615,339
def _create_pipeline( pipeline_root: str, csv_input_location: str, taxi_module_file: tfx.dsl.experimental.RuntimeParameter, push_destination: tfx.dsl.experimental.RuntimeParameter, enable_cache: bool ): """Creates a simple Kubeflow-based Chicago Taxi TFX pipeline. Args: pipeline_root: The r...
c483ba700d2c4b0a2386cad997424ac4b10c6ee1
3,615,340
import numpy def gz(tesseroid, lons, lats, radii, nodes, weights): """ Integrate gz using the Gauss-Legendre Quadrature """ order = len(nodes) lonc, latc, rc, scale = _scale_nodes(tesseroid, nodes) # Pre-compute sines, cossines and powers sinlatc = numpy.sin(latc) coslatc = numpy.cos(l...
0e3878fa24fb00f810be03502f19c712b59044f9
3,615,341
def polynomial_coefficients_fast(r,s,alpha,beta,_=None): """ Return the coefficients of the Farey polynomial of slope r/s. The method used is the recursion algorithm. Arguments: r,s -- coprime integers representing the slope of the desired polynomial alpha, beta -- parameters o...
82ad772a4ae192b84b7cd2b2052315038d7dde9d
3,615,342
def get_light_threshold(response): """Get light from response.""" light_threshold = response.get("highlight") return light_threshold
602d3b11fbabfa6c8b0d284a21b4b1ebb816d327
3,615,343
def variant_ids( locus: hl.expr.LocusExpression, alleles: hl.expr.ArrayExpression, max_length: int = None ) -> hl.expr.ArrayExpression: """ Return a list of variant ids - one for each alt allele in the variant """ def compute_variant_id(alt): return hl.rbind( hl.min_rep(locus, [...
0ecf119ddf9d4a97e99987afc69444a2179cc1dd
3,615,344
def normalize_img_to_rgb(img_1_, img_h_, img_w_): """ Normalize the given image """ rgb_img_1 = cv2.imread(img_1_, 1)[:, :, ::-1] rgb_img_1 = cv2.resize(rgb_img_1, (img_h_, img_w_)) rgb_img_1 = np.float32(rgb_img_1) / 255. return rgb_img_1
b3b385fd30e956f47b2648ed8dc71f5ecb552839
3,615,345
def getonts(): """get the list of ont terms""" return Ontterms.objects.all().filter(to_remove__isnull=True).order_by('title')
b69e6e59774d323113b2d21a3f75be5c8cedc347
3,615,346
def load_frame_building_sample_data(): """ Sample data for the BuildingFrame object """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg n_bays = 3 fb = models.FrameBuilding(number_of_storeys, n_bays) fb.interstorey_heights = interstorey_height * np.ones(num...
3d87d3e8a949fb1344ea13780cb529be427e1409
3,615,347
def analyze_group(group, verbosity, error_level): """analyze AD group object group -- group object to be analyzed verbosity - NAGIOS verbosity level - ignored error_level - ignored Returns the Nagios error code (always 0) and error message (group defn) """ return 0, '{name:%s, description:%...
868746cedd1815df1b9188b02671c3d5431bf83b
3,615,348
from typing import Sequence import signal def discount_rewards(x: Sequence, gamma: float) -> np.ndarray: """ Given vector x, computes a vector y such that y[i] = x[i] + gamma * x[i+1] + gamma^2 x[i+2] + ... """ return signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1]
7b5f3cf4f40f5b1dc127aa6c850456dbd7bccaa1
3,615,349
def type_for_objcclass(objcclass): """Look up the :class:`ObjCInstance` subclass used to represent instances of the given Objective-C class in Python. If the exact Objective-C class is not registered, each superclass is also checked, defaulting to :class:`ObjCInstance` if none of the classes in the supercl...
9dff18d82efdb780749dc57c0a6e0e0d587977c4
3,615,350
def command(name=None, descr=None, long_descr=None, examples=None, free_form=False, kind='command'): """Define a model command. :param name: An optional name of the command. Defaults to the name of the function. :param descr: A short description of the command :param long_descr: A long de...
9df0a43cbcefa3ba722f5fb7faa4a11e574eb39b
3,615,351
def bilinearUpsample2Don3D(input_tensor): """ Using tf.image.resize for bilinear interpolation """ """ ATTENTION: bilinear seems only works on 2D image """ ##### NOTE: this bilinaer upsampling works on axies [1,2] in [0,1,2,3,4] ##### input_shape = input_tensor.shape switch_axes = [0,3,1,2,4] re...
f9df49c2cbfc0d19896aa7bb1edff1c8ff067bbc
3,615,352
def fromhaeberlen(diso, delta, eta): """ Converts from the haeberlen convention to the PAS CSA tensor. Parameters ---------- diso : float diso == 1/3(d11 + d22 + d33) delta : flaot dzz - diso eta : float (dyy - dxx)/delta (0 <= eta <= 1) Returns ---------- ...
9d01a784384ca7f0aaebbb59eebc5cab68ffe994
3,615,353
def gst00b(uta, utb): """ Greenwich apparent sidereal time, consistent with IAU 2000 resolutions, using truncated nutation model IAU 2000B. :param uta, utb: UT1 as a two-part Julian date. :type uta, utb: float :returns: Greenwich apparent sidereal time in radians (float). .. seealso:: |MANUAL...
532b5967dd64e416ab16a0777cb26a9406788e2d
3,615,354
import re def search_bad_symbols_and_username(username): """Поиск зарезервированных слов и запрещенных символов""" search_bad_symbols_result = 'No' bad_username = ['root', 'admin', 'moderator', 'support', 'supports', 'helpdesk'] bad_symbols = ['&', ' ', '=', '+', '<', '>', ',', '.', '\"', '\'', '?', ...
79beccff28ce3c319698e47e05353e1c8354522c
3,615,355
def synthesize_edge_selector(sel_data,): """ Synthesizes an edge selector string based on what edges were selected. """ selector_str = '.edges("{filter}{axis}")' # {index}")' axis_index = -1 axis_str = "" filter_str = "" index_str = "" axis_str = None axis_filter = None # ...
a3ac7f30a77d6ec3747bdde30c11eb77ac1ba6ec
3,615,356
import fnmatch def FilterMatchesTest(filter_string, test_string): """Does something close enough to base/strings/pattern.h's MatchPattern() for our purposes here.""" return fnmatch.fnmatch(test_string, filter_string)
9f4cca026e60fe1b3fb0c2858477090fdf03c44e
3,615,357
def make_path(components): """Build a path from a list of components.""" return '/{}'.format( '/'.join([quote(str(c), '') for c in components if c]))
fc7cbf848e3c3ad8fd2a30ee1c01992c77d3be35
3,615,358
def price_task(request): """ Lista de nomes, datas e VALORES das tarefas""" context = {} cliente = request.user try: cliente = Cliente.objects.get(usuario=cliente) # filter mostra como está a saida em __str__ # do models da classe # cronograma = Cronograma.objects.filter(...
3c2021770ff6a7396880321a69470398e580fcb4
3,615,359
def quotation_detail(request, quotation_id): """ View to show all record detail for a particular quotation """ try: quotation = get_object_or_404(Quotation, pk=quotation_id) except Exception as e: messages.error(request, f'ERROR: {e}') return redirect(reverse('quotations')) co...
2fe9bf09a6a21d7e6e80c7dcd57fa5f1d163561d
3,615,360
def li(content, value: str="", accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: st...
732af5f05c942d1f60d3a575b64922140c2748bf
3,615,361
from typing import List from typing import Dict def get_relations() -> List[Dict[str, str]]: """ Get the relations used for annotation for this app. """ return configuration.relations
4f55f1ad9545305ccb20e329b2ad573d8f97aeea
3,615,362
import sysconfig def sem(): """Create and return SEM (base class) instance with default config.""" return SEM(config, sysconfig)
55fa3c510189e301d4603f00aba32ec32b4d9f57
3,615,363
from typing import Dict def sort_by_color(e: Dict) -> float: """Sorting function, using a globally-declared color variable.""" return e[color]
9748e621798ff8cd9a41a57b657bac78b3105536
3,615,364
def get_texts_from_url_and_selector(url: str, selector: str) -> t.List[str]: """Get the texts of the elements found at the url and selector""" elements = get_elements_from_url_and_selector(url=url, selector=selector) texts = [element.text for element in elements] return texts
898b6d461db94b143edfb4a73e0747635033ab76
3,615,365
def concrete_post(update, state, expr = None): """ Apply an update concretely (compute concrete post). ". """ # TODO: axioms could change as scope changes axioms = state.domain.background_theory(state.in_scope) # print "concrete post: axioms = {}".format(axioms) cons = compose_state_action(s...
e5f6856671e8dc8b1810895dfef50be3af141358
3,615,366
import random def flat_monte_carlo(func, z_min, z_max, epsilon): """ Operate Monte Carlo integration on specified function. Random numbers are generated with a flat distribution function. ---------- Input: func: the function of integrand z_min: lower limit of the integration z_...
9f4fdb0a3f75ee9e0af2b6d3d0e6f439720d1fe9
3,615,367
def hbp_fn(): """Create a 2d convolution layer with HBP functionality.""" set_seeds(0) return HBPConv2d( in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias, )
ccfae6f3b41a508cbe9e8124587b65f90356603e
3,615,368
from typing import List import ctypes def GetMonitorsRect() -> List[Rect]: """Return monitors rect""" SM_CMONITORS = 80 monitorsCount = ctypes.windll.user32.GetSystemMetrics(SM_CMONITORS) arrayType = ctypes.c_int * (monitorsCount * 4) values = arrayType() monitorsCount = _DllClient.instance()....
5780f1af36c323fb9447619e30eb068870fa994d
3,615,369
def _get_model_maker(complete_conf, cache=True): """Locate and instantiate class of data-scientist-provided ModelMaker (which the data scientist inherited from ModelMakerInterface). For this to work, your model module (.py file) needs to be in python's sys.path (usually the case). Also set the confi...
5e33d9faf6260fcf16ae720bf66efc967a1ad693
3,615,370
import code def main(_): """Run an interactive console.""" code.interact() return 0
e85a21c0197a599378c3f25022ec99cb557d6017
3,615,371
import mkl import numpy import scipy def fit_r_mdv_scipy(configure, experiments, numbers, vectors, matrixinv, func, flux, method = "SLSQP"): """Low level function for model fitting using scipy.optimize.minimize Args: configures (dict): "model.configures" including various configulatoins of the model...
5e4ffe4ec7fff423409ad019333585b0c3c04712
3,615,372
import heapq def heapmerge(*inputs): """Like heapq.merge(), merges multiple sorted inputs (any iterables) into a single sorted output, but provides more convenient API: each input is a pair of (iterable, label) and each yielded result is a pair of (item, label of the input) - so that it's known what input a g...
580ec9f2f0793f8907390f5c7f8eebf4ac539b59
3,615,373
def histograma(img): """Calcula y representa el histograma de una imagen RGB. Args: img (Numpy array 3d): Un imagen RGB Returns: List: Devuelve una lista con el array del histograma de cada canal RGB. Cada canal contendra un array de dos dimensiones, la primera contendra la...
782f69002220ad744efab496f7d71e0bff811957
3,615,374
from datetime import datetime def get_all_data(start=datetime.date(1970, 1, 1), end=datetime.date(2099, 12, 31)) -> pd.DataFrame: """得到一段日期内的全部信息""" return _calendar.get_all_data(str(start), str(end))
714bb182bbc4dbe3dc2a07378f7ce0c140d03a6b
3,615,375
def tb_extent(table, db='main'): """Get the extent of the table""" data = [] try: conn = psycopg2.connect(conn_str(db)) cur = conn.cursor() sql = f""" SELECT ST_AsText(ST_SetSRID(ST_Extent(st_transform(wkb_geometry, 4326)), 4326)) As bextent FROM {table};"...
c096fb8924379494e6c6a1475fdac47207f61eb0
3,615,376
from typing import Iterable def _avro_pfb_schema(azul_avro_schema: Iterable[JSON]) -> JSON: """ The boilerplate Avro schema that comprises a PFB's schema is returned in this JSON literal below. This schema was copied from https://github.com/uc-cdis/pypfb/blob/1497bf50e5c85201f6bad9ca69616138b17b8c77/s...
3019f3ae3005f625953eb8cdf0e9539d58ab5dd0
3,615,377
def _extend_job_info(connection, info): """Extends job info with connection/API related data.""" info['path'] = '/jobs/%s/%s' % (connection.id, info['uid']) info['agent'] = { 'platform': connection.handshake_data[pagent.identity.KEY_PLATFORM], 'properties': connection.handshake_data[pagent.i...
6865f76e5c0ea23e7c6910ca723c7d5c08f391bd
3,615,378
def get_timeseries_data_as_df(quantum:object, entity:object, attribute:str=None): """ :param quantum: An instance of quantumleap where the timeseries data should be obtained from :param entity: The entity of which the data should be obtained :param attribute: The attribute of which the data should be ...
505e2f2ea58c0e3681dd4eed3ed0437f81c9b5f3
3,615,379
async def login_for_access_token( form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db_session), ): """Generate and return a token""" user = await crud.backend_user.authenticate(db=db, user_name=form_data.username, password=form_data.password) # check if OK if us...
636db7af85f0fb2e951bc6dfb1c3fb53b0213a89
3,615,380
from datetime import datetime import pytz def utc_float_to_pretty(utc_float=None, fmt=None, timezone=None): """Return the formatted version of utc_float - fmt: a strftime format - timezone: a timezone If no utc_float is provided, a utc_float for "right now" will be used. If no fmt is provided an...
a419d41818e2fbd5682f0dfc8b453f85da2b85a4
3,615,381
def find_teacher(req: str): """ Find teacher :param req: Request :return: Search result as string """ if len(req) < 3: return r_teacher_find_symbols req_f = f"%{req.lower()}%" res = cur.execute("SELECT * FROM teachers WHERE teacherClassSearchable LIKE ? LIMIT 5", (req_f,)).fetch...
0158f1cccf816d03b6cc4bc107096384ccbf38a7
3,615,382
def pause_synchronization(): """ Pauses synchronization of files from Artella server """ client = get_artella_client() return client.pause_downloads()
9eff1128e4e80809ca0a96b86f64835489519cff
3,615,383
def shortest_common_super_sequence(a, b): """ get the shortest common string for a and b This cannot solve complex case like the one in the test case, when same char repeats before the next common substring letter. """ def separate_by_char(letter, seq): idx_seq = seq.find(letter) ...
3a989f342269b1319c4fc3af48f894ef1bcb53fb
3,615,384
def contains_carriage_return(text): """Check if carriage return is present.""" return "↵" in clean_string(text)
13f470e652a231b43cfd890e5a9f444f466b3215
3,615,385
from datetime import datetime def timestamp_to_datetime( timestamp: float, tzinfo: timezone = timezone.utc, ) -> datetime: """ Convert a given UNIX timestamp to a Python datetime object. Args: timestamp: A UNIX timestamp (as a float). tzinfo: A timezone object. Usually, everything...
041b43383d68565086eb817379ba341dd2ce6883
3,615,386
import os import statistics def read_list_from_file( files_list_path: str = FILES_LIST_PATH, files_list_filename: str = FILES_LIST_FILENAME, ) -> list: """ Import list from file """ if os.path.exists(f"{files_list_path}/{files_list_filename}"): try: with open(f"{files_list_path}/{...
02e6b26f88a06f9ddbd8c93fe3b93d89fd175061
3,615,387
def handle_get(key): """Return a tuple containing True if the key exists and the message to send back to the client.""" try: return_value = DATABASE_DICT[key] operation_status = True except KeyError: operation_status = False return_value = None return (operation_statu...
8da98332545f97996294fdaea05684da6dfbe4f0
3,615,388
def preprocess_document(text): """Wrapper of the above.""" return create_tokens(lowercase_text(text))
bae1e0d5789caaac3a9254037aa604f43b49dee3
3,615,389
def analizar_propuesta(propuesta, codigo): """Determina aciertos y coincidencias""" aciertos = 0 coincidencias = 0 for i in range(DIGITOS): if propuesta[i] == codigo[i]: aciertos += 1 elif propuesta[i] in codigo: coincidencias += 1 return aciertos,coincidencias
dd86380a1afb044ff922f8de64c4892976f17c6c
3,615,390
def conditions_gen(conditions, safe=True): """ Generate comma separated conditions. Args: conditions: An iterator that yields ConditionClause tuples. Returns: The string of the query. """ conditions_str = '' connector = None for index, condition in e...
6a00557004ce4a3080df3d6d477df2014c681c7b
3,615,391
def as_type(val, types): """Try converting `val`to each of `types` in turn, returning the first one that succeeds.""" errs = [] for type in make_seq(types): try: return type(val) except Exception as e: errs.append(e) pass raise TypeError('Could not con...
da30769367f6f295fde983ad637610ace14f2b6a
3,615,392
import json def cjson_parser(cjsonfile, trajfile=None): """Parse CJSON files Parameters ---------- cjsonfile : str Path to the CJSON file. trajfile : str, optional Name of trajectory file to be saved, by default None. Returns ------- atoms A list of Atoms obje...
caf4b21b8a887408dc59c80672d39f5787a04bfa
3,615,393
import ast def get_version_from_module(content: str) -> str: """Get the __version__ value from a module.""" # adapted from setuptools/config.py try: module = ast.parse(content) except SyntaxError as exc: raise IOError(f'Unable to parse module: {exc}') try: return next( ...
bce0932d487bb778fd9dba5cbd0ae15c5f888fa6
3,615,394
def tableHeaders(): """ tableHeaders table model headers Returns: list: header definitions """ data = [ [ "jobID", { "Type": "int", "CastFunction": int, "Label": " " + _(Text.txt0131) + " ", "A...
2b10d139efc5d3965cf8a636b9ad80c7cfbecaf3
3,615,395
import unicodedata import re def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. From Django 2....
c36a9c383f537ace0d7113994d36eae79f631073
3,615,396
import yaml def cfg_to_algorithm(config_file): """ Return instance of classification algorithm helper from config file Args: config_file (str): location of configuration file for algorithm Returns: tuple: scikit-learn estimator (object) and configuration file (dict) Raises: ...
f8dde9cbb47e59e994e5ae688b7f432b89c46d3b
3,615,397
import os def _parse_instance_info(node): """Gets the instance specific Node deployment info. This method validates whether the 'instance_info' property of the supplied node contains the required or optional information properly for this driver to deploy images to the node. :param node: a target...
58e97b86c2fd3b6fa4b97bb0a94b5c36fa95c8f4
3,615,398
def get_pdf_form(): """ 1. Call the envelope get method """ # import pdb; pdb.set_trace() args = { "account_id": session["ds_account_id"], "document_id": 1, "envelope_id": session["envelope_id"], "envelope_documents": session["envelope_documents"], "base_path"...
ddbcaff85e4424a8c7509c47a69f25428f942c94
3,615,399