content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def index(): """ Index page """ return render_template("index.html");
af92fa468122a41ed33d55a591735d400cf68e0d
3,651,300
def solve(in_array): """ Similar to 46442a0e, but where new quadrants are flips of the original array rather than rotations :param in_array: input array :return: expected output array """ array_edgelength = len(in_array[0]) # input array edge length opp_end = array_edgelength*2-1 # used...
0af23e82caf65bea64eeeae6da8400ef6ec03426
3,651,301
def trim_all(audio, rate, frame_duration, ambient_power=1e-4): """Trims ambient silence in the audio anywhere. params: audio: A numpy ndarray, which has 1 dimension and values within -1.0 to 1.0 (inclusive) rate: An integer, which is the rate at which samples are taken fra...
37d7ca77c9ab767c90fedf4008a7a28415c5ce3f
3,651,302
def guess_initializer(var, graph=None): """Helper function to guess the initializer of a variable. The function looks at the operations in the initializer name space for the variable (e.g. my_scope/my_var_name/Initializer/*). The TF core initializers have characteristic sets of operations that can be used to d...
5a1e4a99037e51d87a8d75bc5f33e105f86a4153
3,651,303
def get_all(ptype=vendor): """ returns a dict of all partners """ if ptype == vendor: d = get_dict_from_json_file( VENDORS_JSON_FILE ) # will create file if not exist if ptype == customer: d = get_dict_from_json_file( CUSTOMERS_JSON_FILE ) return d
eb285d9462f85daec9c8b176edc6eaa90a09ff4c
3,651,304
import logging from pathlib import Path def validate_read_parameters(file_path, output_path, encryption_key, scrypt_n, scrypt_r, scrypt_p, block_height_override, block_width_override, max_cpu_cores, save_statistics, bad_frame_strikes, stop_at_metadata_load, au...
40509a71967273154395b6fd847497f25b76a2dc
3,651,305
from catkin.find_in_workspaces import find_in_workspaces def FindCatkinResource(package, relative_path): """ Find a Catkin resource in the share directory or the package source directory. Raises IOError if resource is not found. @param relative_path Path relative to share or package source direct...
17fe7bf3fb6b04f031d1bd8e0dd6558312dca92a
3,651,306
from typing import Callable import urllib3 from typing import Dict from typing import Any from typing import Optional def send_udf_call( api_func: Callable[..., urllib3.HTTPResponse], api_kwargs: Dict[str, Any], decoder: decoders.AbstractDecoder, id_callback: Optional[IDCallback] = None, *, re...
d34323f1f276f14d0dc947835db490e78ca47691
3,651,307
import requests import json def migration_area_baidu(area="乌鲁木齐市", indicator="move_in", date="20200201"): """ 百度地图慧眼-百度迁徙-XXX迁入地详情 百度地图慧眼-百度迁徙-XXX迁出地详情 以上展示 top100 结果,如不够 100 则展示全部 迁入来源地比例: 从 xx 地迁入到当前区域的人数与当前区域迁入总人口的比值 迁出目的地比例: 从当前区域迁出到 xx 的人口与从当前区域迁出总人口的比值 https://qianxi.baidu.com/?from=...
4bb4afdde77c2b21222bde28a4f93e58cd8c6019
3,651,308
def ranges(locdata: LocData, loc_properties=None, special=None, epsilon=1): """ Provide data ranges for locdata.data property. If LocData is empty None is returned. If LocData carries a single value, the range will be (value, value + `epsilon`). Parameters ---------- locdata : LocData ...
28a23603dbb2abb52df4f7d2b35b6333050cfe43
3,651,309
def subnet_create(request, network_id, **kwargs): """Create a subnet on a specified network. :param request: request context :param network_id: network id a subnet is created on :param cidr: (optional) subnet IP address range :param ip_version: (optional) IP version (4 or 6) :param gateway_ip: ...
29fda0e08494869390cb5c30a2bb2609b56cf8d8
3,651,310
def evaluate_available(item, type_name, predicate): """ Run the check_available predicate and cache the result. If there is already a cached result, use that and don't run the predicate command. :param str item: name of the item to check the type for. i.e. 'server_types :param str type_name: nam...
872e81613c91141c81f6dafd27aee6e8642c1e59
3,651,311
def dB_transform(R, metadata=None, threshold=None, zerovalue=None, inverse=False): """Methods to transform precipitation intensities to/from dB units. Parameters ---------- R: array-like Array of any shape to be (back-)transformed. metadata: dict, optional Metadata dictionary contai...
d0b68c10290dd1cd95e7c08cca4e9ec7a4131ccc
3,651,312
import typing import os def cut( video: typing.Union[str, VideoObject], output_path: str = None, threshold: float = 0.95, frame_count: int = 5, compress_rate: float = 0.2, target_size: typing.Tuple[int, int] = None, offset: int = 3, limit: int = None, ) -> typing.Tuple[VideoCutResult, ...
892092075a79923933f73805ca09cbbed4f14fc8
3,651,313
def parse_args(): """ Parses command line arguments """ parser = ArgumentParser(description="A multi-threaded gemini server") parser.add_argument("-b", "--host", default=DEFAULT_HOST, help="Host to bind to") parser.add_argument("-p", "--port", default=DEFAULT_PORT, help="Port to bind to") pa...
05dec02ce0f243f46896917c2f25108e6f592bb5
3,651,314
def get_mapping_rules(): """ Get mappings rules as defined in business_object.js Special cases: Aduit has direct mapping to Program with program_id Request has a direct mapping to Audit with audit_id Response has a direct mapping to Request with request_id DocumentationResponse has a direct mapping...
59b94070d3fe35eca8c356162caf9969c9ea47d0
3,651,315
import os def get_src_hash(sls_config, path): """Get hash(es) of serverless source.""" funcs = sls_config['functions'] if sls_config.get('package', {}).get('individually'): hashes = {key: get_hash_of_files(os.path.join(path, os.path.dirname(fu...
0f2d0d98cb55f8d587119408b20caf1b6594ae2f
3,651,316
import os from pathlib import Path import zipfile def extract_zip(zip_path, ret_extracted_path=False): """Extract a zip and delete the .zip file.""" dir_parents = os.path.dirname(zip_path) dir_name = Path(zip_path).stem extracted_path = os.path.join(dir_parents, dir_name, '') if ret_extracted_path...
6ff7691ed54ce3941941b3e014f92ee362237b7c
3,651,317
async def get_pipeline(request: web.Request, organization, pipeline) -> web.Response: """get_pipeline Retrieve pipeline details for an organization :param organization: Name of the organization :type organization: str :param pipeline: Name of the pipeline :type pipeline: str """ retur...
0bbbe26111542173fda05fe8e3beccec99b6bfe8
3,651,318
def add_attachment(manager, issue, file): """ Replace jira's method 'add_attachment' while don't well fixed this issue https://github.com/shazow/urllib3/issues/303 And we need to set filename limit equaled 252 chars. :param manager: [jira.JIRA instance] :param issue: [jira.JIRA.resources.Issue i...
19d2fb57fbd116e27328c075a2899425243856b2
3,651,319
def _ols_iter(inv_design, sig, min_diffusivity): """ Helper function used by ols_fit_dki - Applies OLS fit of the diffusion kurtosis model to single voxel signals. Parameters ---------- inv_design : array (g, 22) Inverse of the design matrix holding the covariants used to solve for ...
da55a73fff02f2088b77d21a4b0a7a7308b0c855
3,651,320
from typing import Counter def unarchive_collector(collector): """ This code is copied from `Collector.delete` method """ # sort instance collections for model, instances in collector.data.items(): collector.data[model] = sorted(instances, key=attrgetter("pk")) # if possible, bring t...
3c0a05d31fafac34e0503bd5dd154c9201e7e94a
3,651,321
from typing import List from typing import Optional from typing import Union from typing import Dict def remove_tag_from_issues( issues: List[GitHubIssue], tag: str, scope: str = "all", ignore_list: Optional[Union[List[int], List[Dict[str, int]]]] = None, ) -> List[GitHubIssue]: """remove_tag_from...
c8709f7e9a01f4c5320748ca181a3a813a9e754f
3,651,322
from datetime import datetime def days_remaining_context_processor(request): """Context processor. Adds days_remaining to context of every view.""" now = datetime.now() return {'days_remaining' : (wedding_date - now).days}
1aa9deb40b54627044926820921c4e5550f2050c
3,651,323
from datetime import datetime import time def convert_time_range(trange, tz=None): """ Converts freeform time range into a tuple of localized timestamps (start, end). If `tz` is None, uses settings.TIME_ZONE for localizing time range. :param trange: - string representing time-range. The opti...
64c24c3011418e93111ec856acdd4b6a94abd425
3,651,324
def process_waiting_time(kernel_data, node_id, phase_id, norm_vehs=False): """Processes batched waiting time computation""" cycle_time = 60 def fn(x): if (x / 13.89) < 0.1: return 1.0 else: return 0.0 wait_times = [] for t in kernel_data: qt = defau...
4489205a8d3ba58601875a7dee1b086fd7b639af
3,651,325
def get_version(): """ Do this so we don't have to import lottery_ticket_pruner which requires keras which cannot be counted on to be installed when this package gets installed. """ with open('lottery_ticket_pruner/__init__.py', 'r') as f: for line in f.readlines(): if line.startswit...
0ab355110918e1c92b056932ba1d03768826c4f2
3,651,326
import time def train_model_regression(X, X_test, y, params, folds, model_type='lgb', eval_metric='mae', columns=None, plot_feature_importance=False, model=None, verbose=10000, early_stopping_rounds=200, n_estimators=50000): """ A function to train a varie...
586e82a1efa42e41b0d0dfdddaf9d6d0afdd7bb4
3,651,327
def extract(d, keys): """ Extract a key from a dict. :param d: The dict. :param keys: A list of keys, in order of priority. :return: The most important key with an value found. """ if not d: return for key in keys: tmp = d.get(key) if tmp: return tmp
9985e2f1079088251429fa26611fa6e15b920622
3,651,328
import os def create_file_list(files, suffices, file_type, logger, root_path=None): ############################################################################### """Create and return a master list of files from <files>. <files> is either a comma-separated string of pathnames or a list. If a pathname i...
b582d1d1bc2c02d5e68bffad88a082be607813a4
3,651,329
import os def get_raster(layer, bbox, path=None, update_cache=False, check_modified=False, mosaic=False): """downloads National Elevation Dataset raster tiles that cover the given bounding box for the specified data layer. Parameters ---------- layer : str dataset layer nam...
fa34ef0b6d07ba77b93c700cf89b8bd9f568b132
3,651,330
def edit_distance(y, y_hat): """Edit distance between two sequences. Parameters ---------- y : str The groundtruth. y_hat : str The recognition candidate. the minimum number of symbol edits (i.e. insertions, deletions or substitutions) required to change one word into th...
42e9ee4169848cd2fc491e6e99b67f96e59dd95b
3,651,331
def sort_predictions(classes, predictions, bboxes): """ Sorts predictions from most probable to least, generate extra metadata about them. """ results = [] for idx, pred in enumerate(predictions): results.append({ "class_idx": np.argmax(pred), "class": classes[np.argmax(pred)...
1938bb3c1b301d15425a6574e66e136cdd43a867
3,651,332
def task_bootstrap_for_adming(): """ """ return {'actions': [(clushUtils.exec_script, [targetNode, "bootstrap_for_adming.py"], { 'dependsFiles': [".passwords", f"{homeDir}/.ssh/id_rsa.pub"], 'user':"root", ...
91180c0b8b9a497488d7b4d1515088f133f5626b
3,651,333
from typing import List from typing import Tuple def reassign_clustered( knn: List[Tuple[npt.NDArray, npt.NDArray]], clusters: List[Tuple[str, int]], min_sim_threshold: float = 0.6, n_iter: int = 20, epsilon: float = 0.05, ) -> List[Tuple[str, int]]: """Reassigns companies to new clusters base...
e90c61459cfeb8d906f155219cd4b758f4b8b5fe
3,651,334
def boys(n,t): """Boys function for the calculation of coulombic integrals. Parameters ---------- n : int Order of boys function t : float Varible for boys function. Raises ------ TypeError If boys function order is not an integer. ValueError If bo...
1232d53898abfd032e570ad7697379f8359a566f
3,651,335
def get_diameter_by_sigma(sigma, proba): """ Get diameter of nodule given sigma of normal distribution and probability of diameter coverage area. Transforms sigma parameter of normal distribution corresponding to cancerous nodule to its diameter using probability of diameter coverage area. Parameters ...
0cd32d685b21b71cbae06a0cfb48f226209eff44
3,651,336
import termcolor def _colorize(val, color): """Colorize a string using termcolor or colorama. If any of them are available. """ if termcolor is not None: val = termcolor.colored(val, color) elif colorama is not None: val = "{}{}{}".format(TERMCOLOR2COLORAMA[color], val, colorama.S...
77743f99fd845b1f8450c4bd93a52563e7c4c313
3,651,337
from pathlib import Path def get_output_filename(output_folder: str, repository_type: str, repository_name: str, filename: str) -> Path: """Returns the output filename for the file fetched from a repository.""" return ( Path(output_folder) / Path(repository_type.lower()) ...
23b806f98265b45b799dbcc177760d5ceb8248fb
3,651,338
def get_data(cpe): """collect data from ser_dev single value of z-accel""" cpe.reset_input_buffer() next = cpe.readline() light = (float(next.decode("ascii"))) # TODO wrap in TRY? return light
7b736420ce5de98ad06d7196866097a7c370833f
3,651,339
def wave_exist_2d_full_v2(b=.8): """ plot zeros of -nu1 + G(nu1,nu2) and -nu2 + G(nu2,nu1) as a function of g use accurate fourier series """ # get data # nc1 bifurcation values bif = np.loadtxt('twod_wave_exist_br1.dat') #bif2 = np.loadtxt('twod_wave_exist_br2.dat') bif...
a471a8b510ed786080e2e5f1b3c8159cc211ff19
3,651,340
def _parse_variables(vars_list): """Transform the list of vars stored in module definition in dictionnary""" vars = {} for var in vars_list: key = var['name'] value = None for var_type in ATTRIBUTE_TYPE: if var_type in var: value = var[var_type] ...
59c88815abf08efe72dcca9efce4970bcd072b91
3,651,341
import logging def get_vertical_axes(nc_file): """ Scan input netCDF file and return a list of vertical axis variables, requiring specific axis names """ vertical_axes = [] for var_name, var in nc_file.variables.items(): if var_name in ('full_levels', 'half_levels'): verti...
f26b89d9d9839759f3b1ed7a990d548f996e29d2
3,651,342
def update_workload_volumes(workload,config,spec_config): """ Return True if some env is updated;otherwise return False """ volumemount_configs = get_property(spec_config,("containers",0,"volumeMounts")) if not volumemount_configs: del_objs = models.WorkloadVolume.objects.filter(workload=wor...
2887aaaf6223b1e548d0c35c8a9b300d4ec417d8
3,651,343
def b_2_d(x): """ Convert byte list to decimal :param x: byte list :return: decimal """ s = 0 for i in range(0, len(x)): s += x[i]*2**i return s
e865700ea30be535ad014908d6b6024186cc5ac6
3,651,344
def get(s, delimiter='', format="diacritical"): """Return pinyin of string, the string must be unicode """ return delimiter.join(_pinyin_generator(u(s), format=format))
7369e133f73e9517fc20f6b95809ba615172feae
3,651,345
def top_dist(g1, g2, name='weight', topology_type=0): """ :param g1: graph 1 :param g2: graph 2 :param name: compared edge attribute :param topology_type: topology distance normalization method :return: topology distance """ max_v = max_edge(g1, name, max_edge(g2, name, 0)) # find max ...
2abf2e74b3a715861389b75bfce8bc3c609a77c1
3,651,346
def refresh_track(): """ For now the interface isn't refreshed :return: """ try: url = request.form["url"] except KeyError: return "nok" with app.database_lock: Track.refresh_by_url(app.config["DATABASE_PATH"], url) return "ok"
47cf865ec01093735050e7abb15d65ef97d2e1ba
3,651,347
import pickle def get_weights(): """ Loads uni-modal text and image CNN model weights. Returns: tuple: text and image weights. """ text_weight_file = open("models/unimodal_text_CNN_weights.pickle", "rb") text_weights = pickle.load(text_weight_file) text_weight_file.close() image...
abff59a197130f5776fdb0cacc3f895ff5d7393e
3,651,348
def get_data(start_runno, start_fileno, hall, fields): # pylint: disable=too-many-locals,too-many-branches """Pull the data requested, starting from first VALID run/file after/including the specified one""" val_dict = lambda: {'values': []} ad_dict = lambda: {f'AD{det}': val_dict() ...
e740952bf5419956bb86f214b01e4a8deb8e6ebc
3,651,349
def timelength_label_to_seconds( timelength_label: spec.TimelengthLabel, ) -> spec.TimelengthSeconds: """convert TimelengthLabel to seconds""" number = int(timelength_label[:-1]) letter = timelength_label[-1] base_units = timelength_units.get_base_units() base_seconds = base_units['1' + letter] ...
d0494fd2fabe07d0cae2dbc7c8c142b7b478533c
3,651,350
from typing import List def getUrlsAlias()->List[str]: """获取所有urls.py的别名""" obj = getEnvXmlObj() return obj.get_childnode_lists('alias/file[name=urls]')
be0f5a2b423a4fa9a58d9e60e2cc0d91f1d66949
3,651,351
def project_xarray(run: BlueskyRun, *args, projection=None, projection_name=None): """Produces an xarray Dataset by projecting the provided run. EXPERIMENTAL: projection code is experimental and could change in the near future. Projections come with multiple types: linked, and caclulated. Calculated field...
8960b68090601c0a83da4ebb82c4b97f3751282f
3,651,352
def collect_users(): """Collect a list of all Santas from the user""" list_of_santas = [] while 1: item = input("Enter a name\n") if not item: break list_of_santas.append(item) return list_of_santas
d86ec360518fdb497b86b7f631fee0dc4464e2bb
3,651,353
def check_role_exists(role_name, access_key, secret_key): """ Check wheter the given IAM role already exists in the AWS Account Args: role_name (str): Role name access_key (str): AWS Access Key secret_key (str): AWS Secret Key Returns: Boolean: True if env exists else F...
cd6f118424ca17f6e65e28abefed39e89bd66b95
3,651,354
def group_delay(group_key, flights): """ Group the arrival delay flights based on keys. :param group_key: Group key to use for categorization. :param flights: List of flights matching from an origin airport. :return: Dictionary containing the list of flights grouped. """ dict_of_group_flight...
0ae760f7da7762b97d6d7a5d5503b280ed39f855
3,651,355
def create_matrix( score_same_brackets, score_other_brackets, score_reverse_brackets, score_brackets_dots, score_two_dots, add_score_for_seq_match, mode='simple'): """ Function that create matrix that can be used for further analysis, please take note, that mode must be the same in c...
7979a72b70ae2910051943c714676aec3d291dbc
3,651,356
def view_inv(inventory_list): """list -> None empty string that adds Rental attributes """ inventory_string = '' for item in inventory_list: inventory_string += ('\nRental: ' + str(item[0])+ '\nQuantity: '+ str(item[1])+ '\nDeposit: '+"$"+ str(item[2])+"\nPr...
540b6bb2597ba5686a070749c2526ad09be25d5f
3,651,357
def generate_smb_proto_payload(*protos): """Generate SMB Protocol. Pakcet protos in order. """ hexdata = [] for proto in protos: hexdata.extend(proto) return "".join(hexdata)
848fdad11941a6d917bd7969fb7ffb77025cd13d
3,651,358
def FeatureGrad_LogDet(grad_feature): """Part of the RegTerm inside the integral It calculates the logarithm of the determinant of the matrix [N_y x N_y] given by the scalar product of the gradients along the N_x axis. Args: grad_feature (array_like): [N_samples, N_y, N_x], where N_x is the input s...
a32b472c6c69b441be52911f5a2f82011c5cab00
3,651,359
def get_every_second_indexes(ser: pd.Series, even_index=True) -> pd.core.series.Series: """Return all rows where the index is either even or odd. If even_index is True return every index where idx % 2 == 0 If even_index is False return every index where idx % 2 != 0 Assume d...
eb8c3b3a377c34e047d7daa525226cac18e21b7b
3,651,360
def EVLAApplyCal(uv, err, SNver=0, CLin=0, CLout=0, maxInter=240.0, \ doSelf=False, logfile=None, check=False, debug=False): """ Applies an SN table to a CL table and writes another Returns task error code, 0=OK, else failed * uv = UV data object to clear ...
964cecc682aa85dde29c2cc8bf75f94e9a449da2
3,651,361
def preprocess_input(text): """ 정제된 텍스트를 토큰화합니다 :param text: 정제된 텍스트 :return: 문장과 단어로 토큰화하여 분석에 투입할 준비를 마친 텍스트 """ sentences = nltk.sent_tokenize(text) tokens = [nltk.word_tokenize(sentence) for sentence in sentences] return tokens
902c1aa5fc98ad5180ef7db670afbc972089a307
3,651,362
def create_count_dictionaries_for_letter_placements(all_words_list): """Returns a tuple of dictionaries where the index of the tuple is the counts for that index of each word >>> create_count_dictionaries_for_letter_placements(all_words_list) (dictPosition0, dictPosition1, dictPosition2, dictPosition3, dic...
4d45ddda36c64ccfb357367521aa1983d738ab7b
3,651,363
def parse_known(key, val) -> str: """ maps string from html to to function for parsing Args: key: string from html val: associated value in html Returns: str """ key_to_func = {} key_to_func["left"] = parse_number key_to_func["top"] = parse_number key_to_func...
680a38496c368e7bd13f5578f4312914ac63c7f7
3,651,364
def getRecordsPagination(page, filterRecords=''): """ get all the records created by users to list them in the backend welcome page """ newpage = int(page)-1 offset = str(0) if int(page) == 1 \ else str(( int(conf.pagination) *newpage)) queryRecordsPagination = """ PREFIX prov: <http://www.w3.org/ns/prov#> PR...
97221f9cfebe615744bc3ef488e8daf3ddc0dca4
3,651,365
import scipy.integrate def integrate_intensity(data_sets, id, nθ, iN, NCO2, color1, color2): """Integrate intensity ove angle theta Arguments: data_sets {[type]} -- [description] id {[type]} -- [description] nθ {[type]} -- [description] iN {[type]} -- [description] ...
8336347f8fbe9c690800ae3efec185ba1a0e610d
3,651,366
def new(request, pk=""): """ New CodeStand Entry When user presses 'Associate new project' there is a Project Container associated, then you need reuse this information in the form :param request: HttpResponse :param pk: int - Indicates which project must be loaded """ if re...
432949f5d7ae6869078c729d86bafabac0f17871
3,651,367
def sideral( date, longitude=0.0, model="mean", eop_correction=True, terms=106 ): # pragma: no cover """Sideral time as a rotation matrix """ theta = _sideral(date, longitude, model, eop_correction, terms) return rot3(np.deg2rad(-theta))
01f3209db8996ad1e11ded48da26d286253c5f7d
3,651,368
from splitgraph.core.output import conn_string_to_dict from typing import Type import click def _make_mount_handler_command( handler_name: str, handler: Type[ForeignDataWrapperDataSource] ) -> Command: """Turn the mount handler function into a Click subcommand with help text and kwarg/connection string pa...
0e8aa0cf3973c265e0df2b1815afd65042fa5d14
3,651,369
def test_load_settings_onto_instrument(tmp_test_data_dir): """ Test that we can successfully load the settings of a dummy instrument """ # Always set datadir before instruments set_datadir(tmp_test_data_dir) def get_func(): return 20 tuid = "20210319-094728-327-69b211" instr =...
96f3d96b7a83989c390bcc629f39df618c553056
3,651,370
import html def dashboard_3_update_graphs(n_intervals): """Update all the graphs.""" figures = load_data_make_graphs() main_page_layout = html.Div(children=[ html.Div(className='row', children=[ make_sub_plot(figures, LAYOUT_COLUMNS[0]), make_sub_plot(figures, LAYOUT_COLUM...
b0b67dd06540ffff3c09d2c0ce87d0e5edb44bdf
3,651,371
import numpy as np from mvpa2.datasets import Dataset import copy def fx(sl, dataset, roi_ids, results): """this requires the searchlight conditional attribute 'roi_feature_ids' to be enabled""" resmap = None probmap = None for resblock in results: for res in resblock: if res...
6b5e968882d0fe2e27c9302bc2b821509cfaafa1
3,651,372
import pathlib import stat def check_file(file_name): """ test if file: exists and is writable or can be created Args: file_name (str): the file name Returns: (pathlib.Path): the path or None if problems """ if not file_name: return None path = path...
5b8ff64795aa66d3be71444e158357c9b7a1b2c0
3,651,373
async def push(request): """Push handler. Authenticate, then return generator.""" if request.method != "POST": return 405, {}, "Invalid request" fingerprint = authenticate(request) if not fingerprint: return 403, {}, "Access denied" # Get given file payload = await request.get_...
aeedd0c0c336b756898a98460e15a24b3411c5c2
3,651,374
from urllib.request import urlretrieve from urllib import urlretrieve def getfile(url, outdir=None): """Function to fetch files using urllib Works with ftp """ fn = os.path.split(url)[-1] if outdir is not None: fn = os.path.join(outdir, fn) if not os.path.exists(fn): #Find ap...
9cf70384fd81f702c29316e51fed9ca80802f022
3,651,375
def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object))
386893f99c8cdd00c5523ef7ce052784e6ae9ca8
3,651,376
import json def account_upload_avatar(): """Admin Account Upload Avatar Action. *for Ajax only. Methods: POST Args: files: [name: 'userfile'] Returns: status: {success: true/false} """ if request.method == 'POST': re_helper = ReHelper() data = re...
c17f93eb7e5e750508aa34aedeaffb5b9410f15e
3,651,377
def get_front_end_url_expression(model_name, pk_expression, url_suffix=''): """ Gets an SQL expression that returns a front-end URL for an object. :param model_name: key in settings.DATAHUB_FRONTEND_URL_PREFIXES :param pk_expression: expression that resolves to the pk for the model :param ur...
c763f1d891f35c36823bb2fb7791a3d145f57164
3,651,378
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="KNX", domain=KNX_DOMAIN, data={ CONF_KNX_INDIVIDUAL_ADDRESS: XKNX.DEFAULT_ADDRESS, ConnectionSchema.CONF_KNX_MCAST_GRP: DEFAULT_MCAST_GRP, ...
e8585d7c0f793e0636f29bb91d5533fc22a14a4b
3,651,379
def load_escores(name_dataset, classifier, folds): """Excluir xxxxxxx Return escore in fold. """ escores=[] escores.append(load_dict_file("escores/"+name_dataset +"_"+classifier +"_escore_grid_train"+str(folds))) return escores for index in range(folds): escores.append(load_dict_file("escore...
6afa5b7db023bec903dbab26203edc5d7c162280
3,651,380
def get_devices(): """ will also get devices ready :return: a list of avaiable devices names, e.g., emulator-5556 """ ret = [] p = sub.Popen(settings.ADB + ' devices', stdout=sub.PIPE, stderr=sub.PIPE, shell=True) output, errors = p.communicate() print output segs = output.split("\n") for seg in segs: device...
b3b3a377483f694ecac7f57f6f76a40727be4eee
3,651,381
import logging import tqdm import multiprocessing def _proc_event_full(st, **kwargs): """ processings including :param st: :param kwargs: :return: """ # instrument response removal, spectral whitening, temporal normalization # autocorrelation and filter, then output results. def i...
cd069f684fba1a8d037aa8d08245859098b25c1f
3,651,382
import types def optional_is_none(context, builder, sig, args): """Check if an Optional value is invalid """ [lty, rty] = sig.args [lval, rval] = args # Make sure None is on the right if lty == types.none: lty, rty = rty, lty lval, rval = rval, lval opt_type = lty opt...
a00b6725b43e8d09e8261b228f58319a27b191f9
3,651,383
import logging def get_volume_disk_capacity(pod_name, namespace, volume_name): """ Find the container in the specified pod that has a volume named `volume_name` and run df -h or du -sb in that container to determine the available space in the volume. """ api = get_api("v1", "Pod") res = ap...
29d20c5dfb481be9a58dec85a23e20b9abd9cc5f
3,651,384
import re def is_valid_battlefy_id(battlefy_id: str) -> bool: """ Verify a str is a Battlefy Id (20 <= length < 30) and is alphanumeric. :param battlefy_id: :return: Validity true/false """ return 20 <= len(battlefy_id) < 30 and re.match("^[A-Fa-f0-9]*$", battlefy_id)
ba3f79f4897425b87962f04506fdff1da684c122
3,651,385
def echo(word:str, n:int, toupper:bool=False) -> str: """ Repeat a given word some number of times. :param word: word to repeat :type word: str :param n: number of repeats :type n: int :param toupper: return in all caps? :type toupper: bool :return: result :return type: str ...
62a68c1ff577781a84a58f124beec8d31b0b456c
3,651,386
def verify_package_info(package_info): """Check if package_info points to a valid package dir (i.e. contains at least an osg/ dir or an upstream/ dir). """ url = package_info['canon_url'] rev = package_info['revision'] command = ["svn", "ls", url, "-r", rev] out, err = utils.sbacktick(comma...
6a38e50c2ab121260cbaaa9c188f2470784e65fb
3,651,387
def add(a,b): """ This function adds two numbers together """ return a+b
96173657034d469ea43142179cd408e0c1f1e12d
3,651,388
def decode_ADCP(data): """ Decodes ADCP data read in over UDP. Returns two lists: header and current. input: Raw data string from ADCP UDP stream Output: header: [timestamp, nCells, nBeams, pressure] - timestamp in unix format - nBeams x nCells gives dimensions of current data ...
07c5b430ac2321e4e47124e71c83bf8a2440f43f
3,651,389
def RowToModelInput(row, kind): """ This converts a patient row into inputs for the SVR. In this model we use RNAseq values as inputs. """ SampleID = row[TissueSampleRow(kind)] TrueSampleIDs = [r for r in TissueSamples.columns if r.startswith(SampleID)] if not TrueSa...
1167a7c47be7893252820087098db6e416f6c9bc
3,651,390
from datetime import datetime def str_to_timedelta(td_str): """Parses a human-readable time delta string to a timedelta""" if "d" in td_str: day_str, time_str = td_str.split("d", 1) d = int(day_str.strip()) else: time_str = td_str d = 0 time_str = time_str.strip() i...
dc3449c708ef4fbe689a9c130745d7ada6ac8f78
3,651,391
import cgi def filter_safe_enter(s): """正文 换行替换""" return '<p>' + cgi.escape(s).replace("\n", "</p><p>") + '</p>'
6091abec0ff87361f1bbe4d146c64ddef3cc99f0
3,651,392
def _full_rank(X, cmax=1e15): """ This function possibly adds a scalar matrix to X to guarantee that the condition number is smaller than a given threshold. Parameters ---------- X: array of shape(nrows, ncols) cmax=1.e-15, float tolerance for condition number Returns ------- X...
8f24509fb921877c9f1bcff09fc035285beee69e
3,651,393
from typing import Optional def create( session: Session, instance: Instance, name: str, description: Optional[str] = None, external_id: Optional[str] = None, unified_dataset_name: Optional[str] = None, ) -> Project: """Create a Mastering project in Tamr. Args: instance: Tamr ...
aac88500ecd60df9a1496e38e33bc212f3e26701
3,651,394
import random import time def users_with_pending_lab(connection, **kwargs): """Define comma seperated emails in scope if you want to work on a subset of all the results""" check = CheckResult(connection, 'users_with_pending_lab') # add random wait wait = round(random.uniform(0.1, random_wait), 1) ...
6136531c523cf344405cda42bbfcae1e4719280d
3,651,395
import pandas import types def hpat_pandas_series_lt(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.lt` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_op8 Parameters ---------- ...
b22497f64b711f92bbdf472feba657bc9b49115a
3,651,396
import numbers from typing import Any def convert_kv( key: str, val: str | numbers.Number, attr_type: bool, attr: dict[str, Any] = {}, cdata: bool = False, ) -> str: """Converts a number or string into an XML element""" if DEBUGMODE: # pragma: no cover LOG.info( f'Insi...
944dd77b08ae995fabb1a829d07a064f4ea3859f
3,651,397
def getBanner(host, port): """ Connects to host:port and returns the banner. """ try: s = socket.socket() s.connect((host, port)) banner = s.recv(1024) return str(banner).strip() except Exception, e: error(str(host) + ':' + str(port) + ' ' + str(e))
46d497067790ef19521f84345adb8c8369ca8737
3,651,398
from typing import List def create_cmd_table(table_data: List[List[str]], width: int = 15) -> BorderedTable: """Create a bordered table for cmd2 output. Args: table_data: list of lists with the string data to display width: integer width of the columns. Default is 15 which generally works for...
044630072f9927262673d65e9cfeadbd49d44f31
3,651,399