content
stringlengths
22
815k
id
int64
0
4.91M
def render_content(template, context={}, request=None): """Renderiza el contenido para un email a partir de la plantilla y el contexto. Deben existir las versiones ".html" y ".txt" de la plantilla. Adicionalmente, si se recibe el request, se utilizará para el renderizado. """ if request: context_class = Re...
22,300
def calculate_psi(expected, actual, buckettype="bins", breakpoints=None, buckets=10, axis=0): """Calculate the PSI (population stability index) across all variables Args: expected: numpy matrix of original values actual: numpy matrix of new values buckettype: type of strategy for creat...
22,301
def test_blur_effect_h_size(): """Test that the blur metric decreases with increasing size of the re-blurring filter. """ image = cp.array(astronaut()) B0 = blur_effect(image, h_size=3, channel_axis=-1) B1 = blur_effect(image, channel_axis=-1) # default h_size is 11 B2 = blur_effect(image, ...
22,302
async def test_report_state_instance(hass, aioclient_mock): """Test proactive state reports with instance.""" aioclient_mock.post(TEST_URL, text="", status=202) hass.states.async_set( "fan.test_fan", "off", { "friendly_name": "Test fan", "supported_features":...
22,303
def accsum(reports): """ Runs accsum, returning a ClassReport (the final section in the report). """ report_bytes = subprocess.check_output( [ACCSUM_BIN] + reports, stderr=subprocess.STDOUT ) contents = report_bytes.decode('UTF-8') return ClassReport.from_accuracy_report(con...
22,304
def test_target_status_processing( vws_client: VWS, high_quality_image: io.BytesIO, mock_database: VuforiaDatabase, ) -> None: """ An error is given when trying to delete a target which is processing. """ runner = CliRunner(mix_stderr=False) target_id = vws_client.add_target( na...
22,305
def get_sid(token): """ Obtain the sid from a given token, returns None if failed connection or other error preventing success Do not use manually """ r = requests.get(url=str(URL + "app"), headers={'Accept': 'text/plain', 'authorization': token, ...
22,306
def generer_lien(mots, commande="http://www.lextutor.ca/cgi-bin/conc/wwwassocwords.pl?lingo=French&KeyWordFormat=&Maximum=10003&LineWidth=100&Gaps=no_gaps&store_dic=&is_refire=true&Fam_or_Word=&Source=http%3A%2F%2Fwww.lextutor.ca%2Fconc%2Ffr%2F&unframed=true&SearchType=equals&SearchStr={0}&Corpus=Fr_le_monde.txt&ColloS...
22,307
def ring_forming_scission_grid(zrxn, zma, npoints=(7,)): """ Build forward WD grid for a ring forming scission reaction # the following allows for a 2-d grid search in the initial ts_search # for now try 1-d grid and see if it is effective """ # Obtain the scan coordinate scan_name = ri...
22,308
def parse_proj(lines): """ parse a project file, looking for section definitions """ section_regex_start = re.compile( '\s*([0-9A-F]+) /\* ([^*]+) \*/ = {$', re.I) section_regex_end = re.compile('\s*};$') children_regex = re.compile('\s*([0-9A-F]+) /\* ([^*]+) \*/,', re.I) children_regex_start = re.compile('...
22,309
def doctest_MongoDataManager_complex_sub_objects(): """MongoDataManager: Never store objects marked as _p_mongo_sub_object Let's construct comlpex object with several levels of containment. _p_mongo_doc_object will point to an object, that is subobject itself. >>> foo = Foo('one') >>> sup = Su...
22,310
def make_daemon(): """ Daemonize to run in background """ pid = os.fork() if pid > 0: # exit first parent sys.exit(0) pid = os.fork() if pid > 0: # exit second parent sys.exit(0) if STREAM: # Create sillystream server output = sillystream.s...
22,311
def print_exception(msg=None): """Print exceptions with/without traceback.""" manually_set_trace, show_trace = _get_manual_env_var("XONSH_SHOW_TRACEBACK", False) manually_set_logfile, log_file = _get_manual_env_var("XONSH_TRACEBACK_LOGFILE") if (not manually_set_trace) and (not manually_set_logfile): ...
22,312
def mot_decode(heat, wh, reg=None, cat_spec_wh=False, K=100): """ 多目标检测结果解析 """ batch, cat, height, width = heat.size() # N×C×H×W # heat = torch.sigmoid(heat) # perform nms on heatmaps heat = _nms(heat) # 默认应用3×3max pooling操作, 检测...
22,313
def create_database(path, host='localhost', port=8080): """For Tests purpose""" app.config.setdefault('host', host) app.config.setdefault('port', port) global db db = Database(path)
22,314
def raise_for_status_with_detail(resp): """ wrap raise_for_status and attempt give detailed reason for api failure re-raise HTTPError for normal flow :param resp: python request resp :return: """ try: resp.raise_for_status() except HTTPError as http_exception: try: ...
22,315
def realign_exons(args): """Entry point.""" memlim = float(args["memlim"]) if args["memlim"] != "Auto" else None os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE" # otherwise it could crash # read gene-related data bed_data = read_bed( args["gene"], args["bdb_bed_file"] ) # extract gene da...
22,316
def get_descriptors(smiles): """ Use RDkit to get molecular descriptors for the given smiles string """ mol = Chem.MolFromSmiles(smiles) return pd.Series({name: func(mol) for name, func in descList.items()})
22,317
def mro(*bases): """Calculate the Method Resolution Order of bases using the C3 algorithm. Suppose you intended creating a class K with the given base classes. This function returns the MRO which K would have, *excluding* K itself (since it doesn't yet exist), as if you had actually created the class. ...
22,318
def ends_with(s, suffix, ignore_case=False): """ suffix: str, list, or tuple """ if is_str(suffix): suffix = [suffix] suffix = list(suffix) if ignore_case: for idx, suf in enumerate(suffix): suffix[idx] = to_lowercase(suf) s = to_lowercase(s) suffix = tupl...
22,319
def compareVersion(self, version1, version2): """ :type version1: str :type version2: str :rtype: int """ # 学学 version1 = [int(val) for val in version1.split(".")] version2 = [int(val) for val in version2.split(".")] if len(version1) > len(version2): min_version = version2 ...
22,320
def test_set_device_id(): """ test_set_device_id """ with pytest.raises(TypeError): context.set_context(device_id=1) context.set_context(device_id="cpu") assert context.get_context("device_id") == 1
22,321
def imagined_reward_data(data,col,book,network): """ This function is a not a standalone function. An excel spreadsheet must be created with the appropriate sheet name. This exists to make the code in other functions more readable since there was a lot of repeat. """ imagined_sheet = book['Imag...
22,322
def create_capital(): """ Use fy and p-t-d capital sets and ref sets to make capital datasets """ adopted = glob.glob(conf['temp_data_dir'] \ + "/FY*_ADOPT_CIP_BUDGET.xlsx") proposed = glob.glob(conf['temp_data_dir'] \ + "/FY*_PROP_CIP_BUDGET.xlsx") todate = glob.glob(conf['...
22,323
def gen_gt_from_quadrilaterals(gt_quadrilaterals, input_gt_class_ids, image_shape, width_stride, box_min_size=3): """ 从gt 四边形生成,宽度固定的gt boxes :param gt_quadrilaterals: GT四边形坐标,[n,(x1,y1,x2,y2,x3,y3,x4,y4)] :param input_gt_class_ids: GT四边形类别,一般就是1 [n] :param image_shape: :param width_stride...
22,324
def monotonic(l: list): """Return True is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) True >>> monotonic([1, 20, 4, 10]) False >>> monotonic([4, 1, 0, -10]) True """ #[SOLUTION] if l == sorted(l) or l == sorted(l, reverse=True): retu...
22,325
def ploterror(ErrorArray,PSyndrome,paths,vertices,CorrectionArray): """Given an error array, this will graphically plot which qubits have error""" height = len(ErrorArray[:,0,0]) width = len(ErrorArray[0,0,:]) scale = 100 radius = 5 image = Image.new('RGB', (width*scale, height*scale )) draw...
22,326
def get_region_dimm_list(region): """ returns list of pmem dimms assocaited with pmem region """ name = 'get_region_dimm_list()' tic = time.perf_counter() global ndctl dimm_list = [] # if DEBUG: print("DEBUG: Function:", __name__, "Region:", region ) # if VERBOSE: print(' gett...
22,327
def readme(): """Get the long description from the README file.""" with open(path.join(project_path, 'README.rst'), encoding='utf-8') as f: return f.read()
22,328
def RFR_dict(input_date: str = None, cache: dict = {}) -> dict: """ Returns a dict with url and filenames from the EIOPA website based on the input_date >>> RFR_dict(datetime(2018,1,1)) {'input_date': datetime.datetime(2018, 1, 1, 0, 0), 'reference_date': '20171231', 'url': 'https://eiopa...
22,329
def get_weight(stats): """ Return a data point weight for the result. """ if stats is None or 'ci_99_a' not in stats or 'ci_99_b' not in stats: return None try: a = stats['ci_99_a'] b = stats['ci_99_b'] if math.isinf(a) or math.isinf(b): # Infinite inter...
22,330
def drop_table(): """as the name implies...""" print("WARNING: Dropping table") TBL_SRV.delete_table(TBL_NAME)
22,331
def get_true_posterior(X: Tensor, y: Tensor) -> (Tensor, Tensor, float, float, float): """ Get the parameters of the true posterior of a linear regression model fit to the given data. Args: X: The features, of shape (n_samples, n_features). y: The targets, of shape (n_samples,). Return...
22,332
def findmax(engine,user,measure,depth): """Returns a list of top (user,measure) pairs, sorted by measure, up to a given :depth""" neighbors = engine.neighbors(user) d = {v:measure(user,v) for v in neighbors} ranked = sorted(neighbors,key=lambda v:d[v],reverse=True) return list((v,d[v]) for v in rank...
22,333
def cart_update(request, pk): """ Add/Remove single product (possible multiple qty of product) to cart :param request: Django's HTTP Request object, pk: Primary key of products to be added to cart :return: Success message """ if request.method == '...
22,334
def hyperopt_cli( config: Union[str, dict], dataset: str = None, training_set: str = None, validation_set: str = None, test_set: str = None, training_set_metadata: str = None, data_format: str = None, experiment_name: str = "experiment", model_name: str = "run", # model_load_path...
22,335
def mlp_gradient(x, y, ws, bs, phis, alpha): """ Return a list containing the gradient of the cost with respect to z^(k)for each layer. :param x: a list of lists representing the x matrix. :param y: a list of lists of output values. :param ws: a list of weight matrices (one for each layer) ...
22,336
def test_tracks_changes_from_multiple_actions(): """Tests that it tracks the changes as a result of actions correctly""" agent = DQN_HER(config) agent.reset_game() for ix in range(4): previous_obs = agent.observation previous_desired_goal = agent.desired_goal previous_achieved_...
22,337
def src_one(y: torch.Tensor, D: torch.Tensor, *, k=None, device=None) -> torch.Tensor: """ y = Dx :param y: image (h*w) :param D: dict (class_sz, train_im_sz, h*w) :param k: :param device: pytorch device :return: predict tensor(int) """ assert y.dim() == 1 assert D.di...
22,338
def test_get_compliment_file(dummy_data): """Ensure Colony object is able to get the correct complimentary file.""" bam_files, vcf_files = dummy_data registry = Registry(bam_files, vcf_files) random_start = bam_files[0] test_colony = Colony(random_start, registry) assert os.path.splitext(test...
22,339
def average_false_positive_score( y_true: Union[Sequence[int], np.ndarray, pd.Series], y_pred: Union[Sequence[int], np.ndarray, pd.Series], ) -> float: """Calculates the average false positive score. Used for when we have more than 2 classes and want our models' average performance for each class P...
22,340
def display_text_paragraph(text: str): """Displays paragraph of text (e.g. explanation, plot interpretation) Args: text (str): Informational text Returns: html.Small: Wrapper for text paragraph """ return html.P(children=[text], style={'font-size': '14px', ...
22,341
def is_numeric(_type) -> bool: """ Check if sqlalchemy _type is derived from Numeric """ return issubclass(_type.__class__, Numeric)
22,342
def make_generic_time_plotter( retrieve_data, label, dt, time_unit=None, title=None, unit=None, ): """Factory function for creating plotters that can plot data over time. The function returns a function which can be called whenever the plot should be drawn. ...
22,343
def start(update: Update, context: CallbackContext) -> None: """Displays info on how to trigger an error.""" update.effective_message.reply_html( 'Use /bad_command to cause an error.\n' f'Your chat id is <code>{update.effective_chat.id}</code>.' )
22,344
def registration(request): """Registration product page """ if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # Se...
22,345
def error_measure(predictions, labels): """ calculate sum squared error of predictions """ return np.sum(np.power(predictions - labels, 2)) / (predictions.shape[0])
22,346
def add3(self, x, y): """Celery task: add numbers.""" return x + y
22,347
def assignMonitoringTo(owner, objName): """ Assign monitoring to an object """ obj = MonitoredEnviron(getattr(owner, objName)) setattr(owner, objName, obj)
22,348
def dummy_function(*args, **kwargs): """A dummy function that doesn't do anything and just returns. Used for making functions dryable. """ return
22,349
def zscore(dat, mean, sigma): """Calculates zscore of a data point in (or outside of) a dataset zscore: how many sigmas away is a value from the mean of a dataset? Parameters ---------- dat: float Data point mean: float Mean of dataset sigma: flaot Sigma of dataset ...
22,350
def _create_ast_bilinear_form(terminal_expr, atomic_expr_field, tests, d_tests, trials, d_trials, fields, d_fields, constants, nderiv, dim, mapping, d_mapping, is_rational_mapping, spaces, mapping_sp...
22,351
def get_package_for_module(module): """Get package name for a module. Helper calculates the package name of a module. Args: module: Module to get name for. If module is a string, try to find module in sys.modules. Returns: If module contains 'package' attribute, uses that as pack...
22,352
def asen(x): """ El arcoseno de un número. El resultado está expresado en radianes. .. math:: \\arcsin(x) Args: x (float): Argumento. Returns: El ángulo expresado en radianes. """ return math.asin(x)
22,353
def get_mock_response(status_code: int, reason: str, text: str): """ Return mock response. :param status_code: An int representing status_code. :param reason: A string to represent reason. :param text: A string to represent text. :return: MockResponse object. """ MockResponse = namedtup...
22,354
def get_user_stack_depth(tb: TracebackType, f: StackFilter) -> int: """Determines the depth of the stack within user-code. Takes a 'StackFilter' function that filters frames by whether they are in user code or not and returns the number of frames in the traceback that are within user code. The ret...
22,355
def unused(attr): """ This function check if an attribute is not set (has no value in it). """ if attr is None: return True else: return False
22,356
def compute_npipelines_xgbrf_5_6(): """Compute the total number of XGB/RF pipelines evaluated""" df = _load_pipelines_df() npipelines_rf = np.sum(df['pipeline'].str.contains('random_forest')) npipelines_xgb = np.sum(df['pipeline'].str.contains('xgb')) total = npipelines_rf + npipelines_xgb resul...
22,357
def get_evaluate_SLA(SLA_terms, topology, evaluate_individual): """Generate a function to evaluate if the flow reliability and latency requirements are met Args: SLA_terms {SLA} -- an SLA object containing latency and bandwidth requirements topology {Topology} -- the reference topology object f...
22,358
def extras(config: DictConfig) -> None: """Control flow by main config file. Args: config (DictConfig): [description] """ log = get_logger(__name__) # make it possible to add new keys to config OmegaConf.set_struct(config, False) # disable python warnings if <config.ignore_warning...
22,359
def main(): """Brute force test every network.""" dataset = 'cifar10_cnn' all_possible_genes = { 'nb_neurons': [16, 32, 64, 128], 'nb_layers': [1, 2, 3, 4, 5], 'activation': ['relu', 'elu', 'tanh', 'sigmoid', 'hard_sigmoid','softplus','linear'], 'optimizer': ['rmsprop', 'a...
22,360
def cloud_watch(tasks, name, log_name): """Real time speedometer in AWS CloudWatch.""" state['operators'][name] = CloudWatchOperator(log_name=log_name, name=name, verbose=state['verbose']) for task in tasks: ...
22,361
def latest_consent(user, research_study_id): """Lookup latest valid consent for user :param user: subject of query :param research_study_id: limit query to respective value If latest consent for user is 'suspended' or 'deleted', this function will return None. See ``consent_withdrawal_dates()`` f...
22,362
def microarray(): """ Fake microarray dataframe """ data = np.arange(9).reshape(3, 3) cols = pd.Series(range(3), name='sample_id') ind = pd.Series([1058685, 1058684, 1058683], name='probe_id') return pd.DataFrame(data, columns=cols, index=ind)
22,363
def find_next_tag(template: str, pointer: int, left_delimiter: str) -> Tuple[str, int]: """Find the next tag, and the literal between current pointer and that tag""" split_index = template.find(left_delimiter, pointer) if split_index == -1: return (template[pointer:], len(template)) return (t...
22,364
def hasNLines(N,filestr): """returns true if the filestr has at least N lines and N periods (~sentences)""" lines = 0 periods = 0 for line in filestr: lines = lines+1 periods = periods + len(line.split('.'))-1 if lines >= N and periods >= N: return True; return Fa...
22,365
def test_contains_true(): """Contain a banana.""" from trie import Trie t = Trie() t.insert('Banana') assert t.contains('Banana')
22,366
def CAMNS_LP(xs, N, lptol=1e-8, exttol=1e-8, verbose=True): """ Solve CAMNS problem via reduction to Linear Programming Arguments: ---------- xs : np.ndarray of shape (M, L) Observation matrix consisting of M observations N : int Number of observations lp...
22,367
def hamiltonian_c(n_max, in_w, e, d): """apply tridiagonal real Hamiltonian matrix to a complex vector Parameters ---------- n_max : int maximum n for cutoff in_w : np.array(complex) state in d : np.array(complex) diagonal elements of Hamiltonian e : np.array(com...
22,368
def unique_badge(): """ keep trying until a new random badge number has been found to return """ rando = str(randint(1000000000, 9999999999)) badge = User.query.filter_by(badge=rando).first() print("rando badge query = {}".format(badge)) if badge: unique_badge() return rando
22,369
def mid_price(high, low, timeperiod: int = 14): """Midpoint Price over period 期间中点价格 :param high: :param low: :param timeperiod: :return: """ return MIDPRICE(high, low, timeperiod)
22,370
def load_pyger_pickle(filename): """ Load pyger data from pickle file back into object compatible with pyger plotting methods :param filename: File name of pickled output from calc_constraints() This is only meant to be used to read in the initial constraints object produced by calc_constraints(), not...
22,371
def absPath(myPath): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS return os.path.join(base_path, os.path.basename(myPath)) except Exception: base_path = o...
22,372
def plot_mean_MQ_vs_derr(ax, xmv_mat): """Plot mean_MQ (y-axis) against d_err (x-axis) for given range of variant sizes :param xmv_mat: :param fig_prefix: :param plot_bin_size: :return: """ mq_mat = xmv_mat.sum(axis=2) data_cnt = mq_mat.sum(axis=1) mq_vector = np.arange(mq_mat.shape[1]) mean_mq = n...
22,373
def cart_item_pre_save_receiver(sender, instance, *args, **kwargs ): """ https://docs.djangoproject.com/en/1.9/ref/signals/#pre-save This works since as we create the cart item, it assumes qty is 1. :param sender: :param instance: :param args: :param kwargs: :return: """ qty = in...
22,374
def createitemdict(index, tf2info): """Take a TF2 item and return a custom dict with a limited number of keys that are used for search""" item = tf2info.items[index] name = item['item_name'] classes = tf2api.getitemclasses(item) attributes = tf2api.getitemattributes(item, ...
22,375
def port_list(request, board_id): """Get ports attached to a board.""" return iotronicclient(request).port.list()
22,376
def main(): """ main entrypoint """ parent_dir = sys.argv[1] parent_dir_ext = os.path.normpath(parent_dir).split(os.sep)[-2] ## strip trailing slashes and then grab second to last folder name; seed_list = get_dir_list(parent_dir) ## list of all seeds inner_dirs = [] ## get all th...
22,377
def _get_archive(url, mode='r', opts=None): """Get archive plugin for given URL.""" if opts is None: opts = {} logger.debug('readdata._get_archive: url %s' % url) url_tuple = urllib.parse.urlsplit(url, scheme="file") if os.name == 'nt' and \ url_tuple.scheme == 'file' and \ ...
22,378
def pure_python_npairs_per_object_3d(sample1, sample2, rbins, period=None): """ """ if period is None: xperiod, yperiod, zperiod = np.inf, np.inf, np.inf else: xperiod, yperiod, zperiod = period, period, period npts1, npts2, num_rbins = len(sample1), len(sample2), len(rbins) co...
22,379
def cal_aic(X, y_pred, centers, weight=None): """Ref: https://en.wikipedia.org/wiki/Akaike_information_criterion """ if weight is None: weight = np.ones(X.shape[0], dtype=X.dtype) para_num = centers.shape[0] * (X.shape[1] + 1) return cal_log_likelihood(X, y_pred, centers, weight) - para_num
22,380
def get_gid(cfg, groupname): """ [description] gets and returns the GID for a given groupname [parameter info] required: cfg: the config object. useful everywhere groupname: the name of the group we want to find the GID for [return value] returns an integer representing t...
22,381
def test_get_level_nonexistent_file(init_statick): """ Test searching for a level which doesn't have a corresponding file. Expected result: None is returned """ args = Args("Statick tool") args.parser.add_argument( "--profile", dest="profile", type=str, default="nonexistent.yaml" ) ...
22,382
def _elements_from_data( edge_length: float, edge_width: float, layers: Set[TemperatureName], logger: Logger, portion_covered: float, pvt_data: Dict[Any, Any], x_resolution: int, y_resolution: int, ) -> Any: """ Returns mapping from element coordinate to element based on the inpu...
22,383
def GetControllers(wing_serial): """Returns control gain matrices for any kite serial number.""" if wing_serial == m.kWingSerial01: airspeed_table = ( [30.0, 60.0, 90.0] ) flap_offsets = ( [-0.209, -0.209, 0.0, 0.0, 0.009, 0.009, -0.005, 0.017] ) longitudinal_gains_min_airspeed =...
22,384
def rotate(mat, degrees): """ Rotates the input image by a given number of degrees about its center. Border pixels are extrapolated by replication. :param mat: input image :param degrees: number of degrees to rotate (positive is counter-clockwise) :return: rotated image """ rot_mat = cv2...
22,385
def copy_budget(budget): """ Función para copiar un presupuesto y sus recursos y tareas Creado: 10 feb de 2019 Por: Carlos Maldonado """ pass
22,386
def spec_defaults(): """ Return a mapping with spec attribute defaults to ensure that the returned results are the same on RubyGems 1.8 and RubyGems 2.0 """ return { 'base_dir': None, 'bin_dir': None, 'cache_dir': None, 'doc_dir': None, 'gem_dir': None, ...
22,387
def rdict(x): """ recursive conversion to dictionary converts objects in list members to dictionary recursively """ if isinstance(x, list): l = [rdict(_) for _ in x] return l elif isinstance(x, dict): x2 = {} for k, v in x.items(): x2[k] = rdict(v) ...
22,388
def get_pid(part_no): """Extract the PID from the part number page""" url = 'https://product.tdk.com/en/search/capacitor/ceramic/mlcc/info?part_no=' + part_no page = requests.get(url) if (page.status_code != 200): print('Error getting page({}): {}'.format(page.status_code, url)) return N...
22,389
def verbatim_det_lcs_all(plags, psr, susp_text, src_text, susp_offsets, src_offsets, th_shortest): """ DESCRIPTION: Uses longest common substring algorithm to classify a pair of documents being compared as verbatim plagarism candidate (the pair of documents), and removing the none verbatim cases if positive ...
22,390
def autopooler(n, it, *a, chunksize=1, dummy=False, return_iter=False, unordered=False, **ka): """Uses multiprocessing.Pool or multiprocessing.dummy.Pool to run iterator in parallel. Parameters ------------ n: int Number of parallel processes. Set to 0 to use auto det...
22,391
def grow_population(initial, days_to_grow): """ Track the fish population growth from an initial population, growing over days_to_grow number of days. To make this efficient two optimizations have been made: 1. Instead of tracking individual fish (which doubles every approx. 8 days which will result O...
22,392
def get_QBrush(): """QBrush getter.""" try: import PySide.QtGui as QtGui return QtGui.QBrush except ImportError: import PyQt5.QtGui as QtGui return QtGui.QBrush
22,393
def apply_odata_query(query: ClauseElement, odata_query: str) -> ClauseElement: """ Shorthand for applying an OData query to a SQLAlchemy query. Args: query: SQLAlchemy query to apply the OData query to. odata_query: OData query string. Returns: ClauseElement: The modified query...
22,394
def get_sql(conn, data, did, tid, exid=None, template_path=None): """ This function will generate sql from model data. :param conn: Connection Object :param data: data :param did: Database ID :param tid: Table id :param exid: Exclusion Constraint ID :param template_path: Template Path ...
22,395
def bytes_base64(x): # type: (AnyStr) -> bytes """Turn bytes into base64""" if six.PY2: return base64.encodestring(x).replace('\n', '') # type: ignore return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'')
22,396
def fetcher(station, sts, ets): """Do fetching""" dbconn = get_dbconn('postgis') cursor = dbconn.cursor('raobstreamer') stations = [station, ] if station.startswith("_"): nt = NetworkTable("RAOB") stations = nt.sts[station]['name'].split("--")[1].strip().split(",") cursor.execut...
22,397
def is_planar_enforced(gdf): """Test if a geodataframe has any planar enforcement violations Parameters ---------- Returns ------- boolean """ if is_overlapping(gdf): return False if non_planar_edges(gdf): return False _holes = holes(gdf) if _holes.shape[...
22,398
def bson2uuid(bval: bytes) -> UUID: """Decode BSON Binary UUID as UUID.""" return UUID(bytes=bval)
22,399