content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def project_file_read(request): """ get content of project file :param request: request object :return: file content """ if request.method == 'POST': data = json.loads(request.body) path = join(data['path'], data['label']) # binary file with open(pat...
854dcd4bb8475e84f020e10229f1729dcd8980ec
3,629,500
from typing import Final def ast_to_graph(root: Node) -> nx.DiGraph: """ You will create your regular expression with a specific syntax which is transformed into an AST, however the regular expression engine expects to navigate in a graph. As it is too complicated to navigate inside the AST direct...
c57178bae24655f29c1fdd36002551a16cd07f0b
3,629,501
def transform(record): """ Transforms (maps) a record. Parameters ---------- record : dict The record to transform. Returns ------- dict The transformed record. """ return { record["stakeholder_approach"]: { record["stakeholder_id"]: { ...
cc9e378c96ee78c46f52184051c3d69568807e0b
3,629,502
def easeInQuart(n): """A quartic tween function that begins slow and then accelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). """ _checkRange...
50f075b8ce1ffd0a1b6dcbf02995275c3b8dff0d
3,629,503
def apply(dataframe, parameters=None, variant=CLASSIC): """ Discover a StarStar model from an ad-hoc built dataframe Parameters ------------- df Dataframe parameters Possible parameters of the algorithm variant Variant of the algorithm, possible values: classic ...
615671920f2a60e356cf79b64da70e383bff4248
3,629,504
import os def create_win_scite(folders): """ create a batch file to start scite @param folders see @see fn create_win_batches @return operations (list of what was done) """ text = ['@echo off', 'set CURRENT2=%~dp0', 'call "%CURRENT2%env.bat"', ...
a0c4065509e4edbbdde362d2f0a1fcba3f2a0ec2
3,629,505
def invoke_cli(cli_runner): """ invoking cli commands with options""" return partial(cli_runner.invoke, cli)
e8811d3e5d640cd41b8f7de71cf190f9f7a72621
3,629,506
import uuid def create_launch_template(client, name, image_ami_id, iam_instance_profile_arn, user_data): """Create a launch template for provisioning instances Args: client (EC2.Client): boto3 ec2 client name (str): the name of the launch template image_ami_...
fc918d436500a04b854571ac4fcb699aa9edf623
3,629,507
def FlowGradedComplex(complex, discrete_flow): """ Overview: Given a complex and a graph on its top dimensional cells, produce a GradedComplex such that the preimage of a down set is the collection of cells in the closure of all the associated top cells Inputs: complex : a complex flow...
90ecf9cce9a3814037099bfec049220d37c52673
3,629,508
from relevanceai.utils import make_id import random import string from typing import List from typing import Dict def mock_documents(number_of_documents: int = 100, vector_length=5): """ Utility function to mock documents. Aimed at helping users reproduce errors if required. The schema for the documen...
83ffbac02725b2f46f8308af01184e0bb46c7f4b
3,629,509
import numpy def rearrange(blist, flist): """Alligns the number of evaluations taken from the blist with the correpsning flist""" final_b=[] final_f=[] for i in range(0,len(blist)): #runs over dimensions erg_b = numpy.empty((0), float) erg_f = [numpy.empty ((0), float), numpy.empty ((0...
1c8865ab3f65bc4fea34098fa1c718b134a2dfc0
3,629,510
def change_password_fields(): """Return Change Password Fields""" return f.Fields([ f.PasswordField('Old Password', v.required), f.PasswordField('New Password', v.required), f.PasswordField('Confirm New Password', v.required), ])
249b380da4b7b538456162b2049d9abcc80574c5
3,629,511
from dateutil import tz def montage_stream(ims, montage_order=None, channel_order=[0, 1, 2], clear_none=True): """From a sequence of single-channel field images, montage multichannels. Suppose the input is a list: ``` ims = [green1a, blue1a, red1a, green1b, blue1b, red1b, ...
0e2bc0307740ff673b2aeaa1a8e8bef32a75921f
3,629,512
def load_and_prepare_cmd(filename,verbose=False): # (g, gr) = load_and_prepare_cmd('fieldA.csv') """ Loads in data. Returns pandas Series of g-r and r respectively. """ FIELD = pd.read_csv("fieldA.csv") g = FIELD["g"] # probs slower than inital idea gr = g - FIELD["r"] mask = (g>14) & (g<24...
995099663179c6d813f32117c9514011201df00a
3,629,513
def make_rows(cngrs_prsn): """Output a list of dicitonaries for each JSON object representing a congressperson. Each individaul dictionary will contain information about the congressperson as well as info about their term. """ name = cngrs_prsn["name"]["first"] + " " + cngrs_prsn["name"]["last"] birthd...
a80c55c3db1261a339ec08814c0f532efd35e45a
3,629,514
def getNumProfileArgs(device): """ Get the number of Power Profile fields for a specific device Parameters: device -- DRM device identifier This varies per ASIC, so ensure that we get the right number of arguments """ profile = getSysfsValue(device, 'profile') numHiddenFields = 0 if n...
d4baa9936bc1d89a4fd3aca8f7aec4796d407bb7
3,629,515
def singlePass(A,Omega,k,s=1,check=False): """ The single pass algorithm for the Hermitian Eigenvalues Problems (HEP) as presented in [1]. Inputs: - :code:`A`: the operator for which we need to estimate the dominant eigenpairs. - :code:`Omega`: a random gassian matrix with :math:`m \\geq k` co...
888f4337a7317a22c32bdb20b06d13f0aad4eb95
3,629,516
def _cons6_77(m6, L66, L67, d_byp, k, Cp, h_byp, dw1, kw1, dw2, kw2, adiabatic_duct=False, conv_approx=False): """dz constrant for edge bypass sc touching 2 corner bypass sc""" term1_out = 0.0 if not adiabatic_duct: if conv_approx: R2 = 1 / h_byp + dw2 / 2 / kw2 ...
cedeaf3125454f4b73f082d43eeb7078a4b71412
3,629,517
def load_user(username): """Load user by usename.""" return User.get_by_username(username)
e037dc226ffff9bc900bc08e2fd323816b3eb7f3
3,629,518
def num_to_hex_string(num, size=1, little_endian=False): """Convert a given number to hex string. Converts a number to a big endian hexstring of a suitable size, optionally little endian Args: num (int) : Input int for which we need to get the hex string size (int) : The required size i...
44093d7b7372998398c360e66b2c2a9115f197de
3,629,519
def validate(number, table=None): """Checks to see if the number provided passes the Damm algorithm.""" if not bool(number): raise InvalidFormat() try: valid = checksum(number, table=table) == 0 except Exception: raise InvalidFormat() if not valid: raise InvalidChecks...
7d516863b2858a5ee922be5046a5ac3add3c7854
3,629,520
from typing import Optional from typing import Sequence def get_saliva_example(sample_times: Optional[Sequence[int]] = None) -> SalivaRawDataFrame: """Return saliva example data. Parameters ---------- sample_times : list of int, optional sample times of saliva samples in minutes Returns ...
004724f81e3bec47bc8a3846567e2da41e27130b
3,629,521
from typing import List from typing import Union def process_json_content(input_type: str, content_array: List[str], json_content_array: Union[List[str], None]): """ Process the array of json_contents """ if json_content_array is None: return [...
be7567f34d31790307c4db9e71e1ef4890bf080e
3,629,522
from typing import Set from typing import Tuple from typing import FrozenSet def knapsack( items: Set[Tuple[float, float]], max_weight: float ) -> FrozenSet[Tuple[float, float]]: """Given a set of (value, weight) pairs and a maximum weight, return the most valuable subset of items whose total weig...
f0bd51643da1f1cea24116e95fb4ea25e3d6dde0
3,629,523
import json def get_json(query_parsed): """Call taskwarrior, returning objects from json""" result, err = call_taskwarrior( 'export %s rc.json.array=on rc.verbose=nothing' % query_parsed) return json.loads(result)
c0537b3a7ca70839543e7867049bee8926f1da2c
3,629,524
def get_list_of_results(results): """Modify the outputs so that they are returned in a list format where it is sometimes easier to be used by other functions. Parameters ---------- results : list A list of named tuples for each iteration Returns ------- list, list, list ...
b5903e3b99aeb37ce90190e86a7cd6e2408ad35b
3,629,525
def get_dagger_of_native(gate: Gate) -> Gate: """ :param gate: A gate from native gate set :return: the conjugated and transposed gate """ if isinstance(gate, Gate): if gate.name == "RZ": return RZ(-gate.params[0], gate.qubits[0]) if gate.name == "RX": ...
4cc765c9deda05b7bec2811614d801b9cbd50836
3,629,526
from typing import List def get_movies_list(request_params: dict) -> List[ShortMovie]: """ :param request_params: Get request query params :return: List of movies, grabed with ElasticSearch """ sort_value = request_params.get('sort') sort_order = request_params.get('sort_order') limit = int(req...
f0704aee0b29f661bb4c7f820db6c500d633aefb
3,629,527
def statUniq(passwords, status): """produce data about unicity stats""" unicity = {"empty":0, "non empty": 0, "unique": 0} unicity['empty'] = passwords[status].count('') unicity['non empty'] = len( passwords[status] ) - unicity['empty'] unicity['unique'] = len( set( passwords[status] )) return u...
645e20c4dceeb1ee7dee028776709ec739e8a6e0
3,629,528
import re def _read_logo(content): """ Read info from logo in file header. """ def _read_logo(pat): pattern = pat + r":\s+\S+" data_str = re.compile(pattern).search(content).group() return data_str.split(':')[1].strip() info = {} for pat in ['Version', 'Website']: info...
e5ed2adb67c42854a3889dd823de6a3517cf1bad
3,629,529
def modulate_position(timestamp): """ counts the position in time-sorted log of IP activity as based on the timestamp attached to the particular log in rdd timestamp: attached timestamp """ result = (INCREMENT - timestamp) % time_dimension return result
f123acb1dd4924151a293789f3a3432f9000541e
3,629,530
def resnet50(mask_init='1s', mask_scale=1e-2, threshold_fn='binarizer', **kwargs): """Constructs a ResNet-50 model.""" #print('resnet50 get in') #print('resnet50 mask_init', mask_init) model = ResNet(Bottleneck, [3, 4, 6, 3], mask_init, mask_scale, threshold_fn, **kwargs) return m...
4713b7b27408e8a80d5603db3b4875cb88321248
3,629,531
import ctypes def create_channel(pvname, connect=False, auto_cb=True, callback=None): """ create a Channel for a given pvname creates a channel, returning the Channel ID ``chid`` used by other functions to identify this channel. Parameters ---------- pvname : string the name of the ...
efc02a366873b5a912e951c73aa864b59f999b77
3,629,532
import subprocess def fetch_profiles(db_path, keys_ls): """Fetch hmm profiles from db and save in a file Args: db_path: String, path where db are stored keys_ls: String, Path to file with acc-nr Return: ls_keys: List, strings with acc-numbers """ LOG.info("Fetching profile...
89ded6a60b46247587180d151caeb66987cb5156
3,629,533
import sys def get_w_cmd_args(): """Either -his or -wnh depending on system.""" try: if (str(sys.platform).lower().startswith(str("""darwin""")) is True): return str("""-hi""") else: return str("""-his""") except Exception as someErr: logs.log(str(type(someErr)), "Error") logs.log(str(someErr), "Erro...
783e832df273d7204bed10c78e24c2d8923eed60
3,629,534
def prep_for_graph(data_frame, series=None, delta_series=None, smoothing=None, outlier_stddev=None): """Prepare a dataframe for graphing by calculating deltas for series that need them, resampling, and removing outliers. """ series = series or [] delta_series = delta_series or [] ...
409fa6b806ce2c6546390e41ae88226b5000a8d8
3,629,535
def vigenere_decryption(text: str, key: str) -> str: """Декодирование шифра Виженера :param text: расшифровываемый текст :type text: str :param key: ключ :type key: str :return: исходный текст :rtype: str """ result = ''.join( [chr((ord(m) - ord(key[i % len(key)]) + 26) % 26...
6ad2277d1060eab48481749023e40e11eb3590ea
3,629,536
def remove_diacritics(string): """Removes diacritics from the given string Parameters ---------- string : str The string from which diacritics should be removed Returns ------- string : str The string with its diacritics removed """ uni = unidecode(string) # r =...
bc6330b32f583b888bfebdeb29993d0a79cae44a
3,629,537
def eval_chip_generalized(theta1, theta2, deltaphi, q, chi1, chi2): """ Generalized definition of the effective precessing spin chip, see arxiv:2011.11948. This definition retains all variations on the precession timescale. Call ---- chip = eval_chip_generalized(theta1,theta2,deltaphi,q,chi1,chi2) ...
bb359afb843d921d216dac69524e43e2ac5807a2
3,629,538
import re def strip_emails(s): """ Remove digits from `s` using RE_EMAILS`. """ RE_EMAILS = re.compile(r"\S*@\S*\s?", re.UNICODE) return RE_EMAILS.sub("", s)
7c9a705023f1d5d821d002815f629bd7ebff8602
3,629,539
def get_hf(sigma_val=0.8228, boxRedshift=0., delta_wrt='mean'): """ Halo mass function model for the MultiDark simulation. """ #hf0 = MassFunction(cosmo_model=cosmo, sigma_8=sigma_val, z=boxRedshift) omega = lambda zz: cosmoMD.Om0*(1+zz)**3. / cosmoMD.efunc(zz)**2 DeltaVir_bn98 = lambda zz : (18.*n.pi**2. + 82.*(...
d90af3c653b62e44c21203ad9c1c48a98abed195
3,629,540
def reverse_one_hot(image): """ Transform a 2D array in one-hot format (depth is num_classes), to a 2D array with only 1 channel, where each pixel value is the classified class key. # Arguments image: The one-hot format image # Returns A 2D array with the same width and...
f4d1f06ad44926ae09a9ecce03dd1e55b4e798f0
3,629,541
def individual_utilities( persons, cdap_indiv_spec, locals_d, trace_hh_id=None, trace_label=None): """ Calculate CDAP utilities for all individuals. Parameters ---------- persons : pandas.DataFrame DataFrame of individual persons data. cdap_indiv_spec : p...
593e4b102755218476651101fa82c47f648e2cf1
3,629,542
def _create_pd_obj(frame, res, RATIO, mode): """Creates a prediction objects file.""" objs = [] # This is only needed for 2D detection or tracking tasks. # Set it to the camera name the prediction is for. if len(res) > 0: for re in res: # import ipdb; ipdb.set_trace() re = re.split(",") obj = metrics_pb...
6effd5af9f4e0da364623eb46a88896dae6ba2a4
3,629,543
import numbers def check_random_state(seed): """Turn `seed` into a `np.random.RandomState` instance. Parameters ---------- seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` ...
31d9435a277174dc6bc033bc1f37b0b5de02078b
3,629,544
import argparse def init_argument_parser(): """ Creates an argument parser and adds specifications for command-line arguments for the expression code generation program. Returns: arg_parser : An initialized ArgumentParser object with properties lang, dest, cname, exprfile ...
baf96d3cb3aebcba00102b46c6e6d5d2345a91b4
3,629,545
import typing def serialize(message: typing.Union[structure.Call, structure.CallResult, structure.CallError]) -> typing.List: """Serializes an 'OCPPMessage'. Args: - message: 'OCPPMessage', the message to serialize Returns: list, an equivalent to the message, based only on JSON compatibl...
a1cc6f966528fb156f825bd87b9c765b9b8783a0
3,629,546
from typing import Sequence def sequence_plot(units: Sequence[Unit]): """Plot the temperatures of all profiles""" fig, ax = utils.create_sequence_plot(units) ax.set_ylabel(r"temperature $T$") ax.set_title("Mean Profile Temperatures") units = list(units) if len(units) > 0: def gen_seq(...
73b7d5b7a0653deb5108b75398102b2e4ae44e84
3,629,547
def format_data(data): """ :param data: :return: str : this str can print to web page. """ return "<pre>" + change_to_str(data, rowstr="<br/>") + "</pre>"
312cf4a1aaece4cc4921f06ed6b85bdde7ad6955
3,629,548
def DAYS(date1, date2): """Given two strings of dates, calculate the difference in days between the two. Parameters ---------- date1 : string start date in the form of a string: 'YYYY-MM-DD' date2 : string end date in the form of a string: 'YYYY-MM-DD' Returns ------- i...
a7401fe0230f49ec864a0e3549f823e19c9879c0
3,629,549
from typing import List def __get_column_names_from_worksheet(worksheet: Worksheet) -> List[NumberOrString]: """Returns list of column names (headers) from worksheet object (i.e; the values from row #1)""" column_names = [ column.value for column in next(worksheet.iter_rows(min_row=1, max_row=1)) ...
3653091b303a0daa512ca3fc3e2bd4aebe4342f6
3,629,550
import os import math def plot_set(fig_num: int, to_goal_arr: list, legend_names: list, max_len: float, max_non_init_rmsd: float, init_metr: float, bsf_arr: list, common_point: float, max_trav: float, trav_arr: list, full_cut: str, metric: str, metr_units: str, same: str, custom_path: str, s...
3108509ec0929cf41686e615da7c2aa25844c43c
3,629,551
def get_fractal_patterns_NtoS_WtoE(fractal_portrait, width, height): """ get all fractal patterns from fractal portrait, from North to South, from West to East """ fractal_patterns = [] for y in range(height): # single fractal pattern f_p = get_fractal_patterns_zero_amounts() for x i...
a19668d5d1f8ae7cb24e79c1e17030cde25c1821
3,629,552
import os def lookup_dir(root, name): """Find a directory """ top = root while osp.exists(root): content = os.listdir(root) for subdir in content: if subdir == name: return osp.join(root, subdir) if len(content) > 1: raise EnvironmentErro...
5efc080384e1fc7f477f40d5f26bf567c756108b
3,629,553
def single_stat_request(player, code, stat): """Actually retrieves the stat and returns the stat info in an embed""" session = Session() message = "" if code == 1: (table, col, message) = stat_dict[stat] columns = [col] res = session.query(*(getattr(table, column) for column in c...
b7eef445b3580eff93768394a0f0632a6174e1a8
3,629,554
import os def download_uniprot(myid, path=".TPSdownloader_cache" + os.path.sep + 'uniprot' + os.path.sep): """Download a page like https://www.uniprot.org/uniprot/A0A2K9RFZ2.xml https://www.uniprot.org/uniprot/D8R8K9.xml Some entries have multiple Accessions, like <accession>Q6XDB5</accession> ...
76dbb05f72cf22b191bd0d2c355ecd854e83e8ec
3,629,555
from typing import List def random_string_list(num: int = 10) -> List[str]: """ Generate list of random strings >>> type(random_string_list()) <class 'list'> >>> all([True if type(obj) is str else False for obj in random_string_list()]) True >>> len(random_string_list()) 10 >>> le...
f13ee6e837d78b631ece65370c15bc1a69e8c7dc
3,629,556
def get_entity_description(entity): """ Realiza o mapeamento de uma entidade padrão da extracão de entidades (named entity) retornando de forma explícita o equivalente em português para a entidade extraída. param : entity : <str> return : <str> """ ent_map = { 'PERSON': 'pessoa'...
21fe671419ba00436070ec49cc0433fabfb0c597
3,629,557
def duration(utter: Utterance) -> int: """Get the duration of an utterance in milliseconds Args: utter: The utterance we are finding the duration of """ return utter.end_time - utter.start_time
bfa1cc9139134a435b9ab39bc7dad9e504abef2d
3,629,558
import more_itertools as mit def label_sequential_regions(inlist): """Input a list of labeled tuples and return a dictionary of sequentially labeled regions. Args: inlist (list): A list of tuples with the first number representing the index and the second the index label. Returns: dict: ...
f258310bd672be41828405f8cab772358991e1c0
3,629,559
def lines_edit_renderer(widget, data): """Renders text area with list value as lines. """ tag = data.tag area_attrs = textarea_attributes(widget, data) value = fetch_value(widget, data) if value is None: value = u'' else: value = u'\n'.join(value) return tag('textarea', v...
600f1b1c5952bd39b56112208ef61dd08e2887d3
3,629,560
def variantsFromAlignment(refWindow, refSeq, cssSeq, cssQV=None, refCoverage=None): """ Extract the variants implied by a pairwise alignment of cssSeq to refSeq reference. If cssQV, refCoverage are provided, they will be used to decorate the variants with those attributes. ...
a49fd077db6043fbf23dc6a9d88c51143195d928
3,629,561
import os def _read_cookie(cookie_path, is_safecookie): """ Provides the contents of a given cookie file. :param str cookie_path: absolute path of the cookie file :param bool is_safecookie: **True** if this was for SAFECOOKIE authentication, **False** if for COOKIE :raises: * :class:`stem.connecti...
fa97c4aab128245809e0459f4cb50c188fe97ef5
3,629,562
from datetime import datetime def exception_guard(f): """ Middleware (guard): checks if the current authorized user can created an exception request """ @wraps(f) def decorated_function(*args, **kwargs): if 'eid' not in kwargs.keys(): return F.abort(404) election =...
850c9818516de666082fbfcc19e7bc281c876b30
3,629,563
def return_last(responses): """Return last item of a list.""" return responses[-1]
f4aedfe0b10adcdb859ac1d0f5809ca666abac80
3,629,564
from typing import List from typing import Tuple def autolink_replacements(what: str) -> List[Tuple[str, str, str]]: """ Create a list containing replacement tuples of the form: (``regex``, ``replacement``, ``obj``) for all classes and methods which are imported in ``KEDRO_MODULES`` ``__init__.py`` fi...
4ff706f19b2f3a4ede71f7bd1307f129fce53660
3,629,565
def flattenDict(dictionary, init = ()): """ Converts nested dicts with numeric or str keys to flat dict with tuple keys. For example, x[1][0][2] becomes xx[(1, 0, 2)]. Based on:: http://stackoverflow.com/questions/6027558/\ flatten-nested-python-dictionaries-compressing-keys """ def _tuple(x): "...
1e78c6041fc015f0019166a74c264b3303f7cc9f
3,629,566
def get_boundary_cell_count(plate_dims, exclude_outer=1): """Get number of wells in outer or inner edges Parameters ---------- plate_dims : array dimensions of plate Returns ------- boundary_cell_count : int number of wells in the edges """ boundary_cell_count =...
8e5056af647f893854bab3de3e6e5038c0d703e1
3,629,567
def _is_false(x): """Evaluates false for bool(False) and str("false")/str("False"). The function is vectorized over numpy arrays or pandas Series. Everything that is NA as defined in `is_na()` evaluates to False. but also works for single values. """ x = np.array(x).astype(object) ret...
200c43dcd60821642cb18a2ac82b1fd592bdaa9e
3,629,568
def compute_border_indices(log2_T, J, i0, i1): """ Computes border indices at all scales which correspond to the original signal boundaries after padding. At the finest resolution, original_signal = padded_signal[..., i0:i1]. This function finds the integers i0, i1 for all temporal subsamplings...
09d29c4de2c808a1947d513580817bda16a6bfe7
3,629,569
def get(data_ids): """ Get a object(s) associated with `data_ids` from the shared object storage. Parameters ---------- data_ids : unidist.core.backends.common.data_id.DataID or list An ID(s) to object(s) to get data from. Returns ------- object A Python object. """...
2f42a45abd56428d1b0087cd9b78460430bed18e
3,629,570
def pass_time(grid, minutes): """Pass number of minutes on grid.""" cur_grid = copy_grid(grid) grid_set = get_grid_for_set(cur_grid) grid_set_to_minute = {grid_set: 0} minute_to_grid_set = {0: grid_set} for minute in range(1, minutes + 1): cur_grid = pass_minute(cur_grid) cur_gri...
6929989d647c46a9c66bb1cee0e545ba621a72cc
3,629,571
import os def njoin(n): """Join with newlines.""" return join(os.linesep, n)
2b0d16fa85ddfc47381976bfa635081b1e57f909
3,629,572
def error_rate(predictions, labels): """Return the error rate based on dense predictions and sparse labels.""" return 100.0 - (100.0 * np.sum(np.argmax(predictions, 1) == labels) / predictions.shape[0])
c2e3ce21e799cf0368523fbcb3fab603642e9c7d
3,629,573
import tqdm def run_question_generation(trainer, dset, model, tokenizer, device, num_beams): """ Generate a set of questions from a source text and list of answers (named entities) :param trainer: HuggingFace trainer :param dset: The dataset to generate questions from :param model: Question genera...
aff16d397b908eae0ab8ada273392e59ea444b68
3,629,574
def get_queue_ids(client: Client) -> list: """ Creating a list of all queue ids that are in the system. Args: client: Client for the api. Returns: list of queue ids. """ queues = client.queues_list_request() queues = queues.get('Queues', []) queues_id = [] for q in qu...
e9455f8a30db543c44241c75ab86b4be7db9715e
3,629,575
def get_image_palette(img, nclusters): """ Extract tuple of (Image, Palette) in LAB space """ lab = rgb2lab(np.array(img)) palette = kmeans_get_palette(lab, nclusters) return lab, palette
a6570d08dd2a76bd8dae7ffdcf34ca271c09c7c6
3,629,576
from .model_store import get_model_file import os def get_diaresnet_cifar(classes, blocks, bottleneck, model_name=None, pretrained=False, ctx=cpu(), root=os.path.join("~", "....
fee6a341cf86bea2a11a51d948035fecc652e901
3,629,577
def isbuffer(obj) -> bool: """ Test whether `obj` is an object that supports the buffer API, like a bytes or bytearray object. """ try: with memoryview(obj): return True except TypeError: return False
bede4ffeb154e765c7c2f4dea3bfa77281b313f2
3,629,578
import csv import json import distutils def _get_mqtt_data(file_name): """ Reads mqtt fake data and expected results from file """ mqtt_data = [] with open(file_name, newline='') as mqtt_data_csv: csv_reader = csv.DictReader(mqtt_data_csv, quotechar="'", delimiter=';') for row in c...
0bc8aed18e406a3ed4098fb319b42f5df466adbc
3,629,579
def yes_maybe_condition_true(x: dict) -> bool: """ The yes maybe condition is true if 35% or 2 (or more) out of 3 users 2 (or more) out of 4 users 2 (or more) out of 5 users have classified as 'yes' or 'maybe' """ if x["yes_share"] + x["maybe_share"] > 0.35: return True else...
3009f2fdb6bdec69ab7f7530d47d40e1f493f8ba
3,629,580
def load_texture(filename): """ This fuctions will return the id for the texture""" textureSurface = pygame.image.load(filename) textureData = pygame.image.tostring(textureSurface,"RGBA",1) width = textureSurface.get_width() height = textureSurface.get_height() ID = glGenTextures(1) glBindTe...
223ce31249589ed2db690add01fc0c00449ef211
3,629,581
import string def search(pattern, doc, flags=0): """Scan through string looking for a match to the pattern, returning a match object, or None if no match was found.""" return _compile(pattern, flags).search(string)
d13be664aa3c279fc46c798c757acb80130a4f29
3,629,582
from typing import Concatenate def yolo4_mobilenetv3small_body(inputs, num_anchors, num_classes, alpha=1.0): """Create YOLO_V4 MobileNetV3Small model CNN body in Keras.""" mobilenetv3small = MobileNetV3Small(input_tensor=inputs, weights='imagenet', include_top=False, alpha=alpha) # input: 416 x 416 x 3 ...
586e6f7b88ca785fe93b0cccda41291ccd4dec0f
3,629,583
import cgi from io import StringIO import os def main(): """ Go do something """ form = cgi.FieldStorage() include_latlon = (form.getfirst('gis', 'no').lower() == 'yes') myvars = form.getlist('vars') myvars.insert(0, 'station') myvars.insert(1, 'obtime') delimiter = DELIMITERS.get(form.get...
8011b4460067ea08982fa4d2655af04133669013
3,629,584
def get_all_effects(fname): """ Give fname from a direct effect file """ # Step 1: Load results for current file print(fname) indirect_result_df = pd.read_csv(fname) analyze_effect_results( results_df=indirect_result_df, effect="indirect" ) fname = fname.replace("_indirect_"...
e032b963a2ccb98b2d824ddc870fa661f38ad8f6
3,629,585
def cart_key(user_id=DEFAULT_USER_ID): """Sub model for representing an author.""" return ndb.Key('addSong2Cart', user_id)
749ba650ed7ce7301ac1d152efcbd3da24cc6b2b
3,629,586
from contextlib import suppress from datetime import datetime def format_datetime(date_str): """ Convert Twitter's date time format ("Thu Jul 20 19:34:20 +0000 2017") to ISO 8601 International Standard Date and Time format. :param date_str: :return: """ with suppress(TypeError, Val...
fe926659acd095090a37c2cc8fd320d73e30c446
3,629,587
from pathlib import Path from typing import Dict def git_named_refs(git_hash: str, git_dir: Path) -> Dict[str, str]: """ Returns all named tag or reference for the provided hash and the hash. This method does not need nor uses a git client installation. """ refs = dict(hash=git_hash) ref_dir ...
0ad9f07c2885785a39f3918c43b0c795d4a864e7
3,629,588
def check_string(seq): """Checks if seq is a string""" if not isinstance(seq, str): assert False, "Input is not a string." else: pass return None
c56ce486fae2e1335b0b191b1804b19ab121f1c9
3,629,589
from typing import Sized def shift_right(sized: Sized, n: int) -> Sized: """Return a copy of sized with it's elements shifted n places to the left but keeping the same size. sized: A sized object which's elements to shift n: How many places to shift sized's items to the left """ return [None] * n...
39ac29ba835d0ea68971d331b235c17c6f98f56a
3,629,590
import io def backport_makefile( self, mode="r", buffering=None, encoding=None, errors=None, newline=None ): """ Backport of ``socket.makefile`` from Python 3.5. """ if not set(mode) <= {"r", "w", "b"}: raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) writing = "w" ...
d19d6ffdd8fcf41e39d021b071bada5bb9c1ea29
3,629,591
from datetime import datetime def epoch_seconds(d: datetime = None) -> int: """ Return the number of seconds for given date. If no date, return current. :param d: timestamp datetime object :return: timestamp in epoch """ if not d: d = datetime.utcnow() return int((d - datetime.utcf...
b9a4671b0904d148248231a1e1eabfa062a5d1d2
3,629,592
import json def parse_json(json_file): """JSON poem parser for 'Gongocorpus'. We read the data and find elements like title, author, year, etc. Then we iterate over the poem text and we look for each stanza, line, word and syllable data. :param json_file: Path for the json file :return: Dict ...
e1944bd5cf18e913c22a8d910aafee608a654e0e
3,629,593
def chou_pseudo_aa_composition(*sequences): """ M.K. Gupta , R. Niyogi & M. Misra (2013) An alignment-free method to find similarity among protein sequences via the general form of Chou’s pseudo amino acid composition, SAR and QSAR in Environmental Research, 24:7, 597-609, DOI: 10.1080/1062936X.20...
95ce5b0ee082a899ea487a910280233fc892430a
3,629,594
def calculate_wire_sweeping_const(h_over_d): """Calculate the wire-sweeping constant for the Upgraded Cheng-Todreas friction factor constant calculation""" ws = {} if h_over_d == 0.0: ws['turbulent'] = 0.0 ws['laminar'] = 0.0 else: ws['turbulent'] = -11.0 * np.log10(h_over_d)...
ae3247de9ff14eb5f14065906f7c6fc0e2a4dc34
3,629,595
import json def create_subscription_definition(subscription_definition_dict): """Create a subscription definition.""" cli_input = json.dumps(subscription_definition_dict) cmd = [ "aws", "greengrass", "create-subscription-definition", "--cli-input-json", cli_input ...
30c51f6f6b905390574b839ec6363716c619c48f
3,629,596
def compile(element, compiler, **_kw): # pylint: disable=function-redefined """ Get length of array defined in a JSONB column """ return "jsonb_typeof(%s)" % compiler.process(element.clauses)
917706c5aa05305c6d2930673d23194665b8c6ed
3,629,597
def guid(fn): """Server mock; grab the object guid from the url""" @wraps(fn) def wrapper(self, request, context, *args, **kwargs): guid = uuid_url_matcher('.+').match(request.path).group(1) return fn(self, request=request, context=context, guid=guid, *args, **kwargs) return wrapper
87dd8b645117e6df5977d72e4f4309a735d00c83
3,629,598
def pil_to_numpy(img: Image.Image) -> np.ndarray: """ Args: img: an Image.Image from `read_img()` Returns: np.ndarray, RGB-style, with shape: [3, H, W], scale: [0, 255], dtype: float32 """ return np.asarray(img.convert('RGB'), dtype='float32').transpose((2, 0, 1))
924b4ad93204b6f2716b316c79b43bc1f83de156
3,629,599