content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def load_structure(query, reduce=True, strip='solvent&~@/pseudoBonds'): """ Load a structure in Chimera. It can be anything accepted by `open` command. Parameters ========== query : str Path to molecular file, or special query for Chimera's open (e.g. pdb:3pk2). reduce : bool Ad...
d91ceeba36eb04e33c238ab2ecb88ba2cc1928c7
3,657,342
from re import T def is_into_keyword(token): """ INTO判定 """ return token.match(T.Keyword, "INTO")
337fb0062dc4288aad8ac715efcca564ddfad113
3,657,343
from typing import Union def exp( value: Union[Tensor, MPCTensor, int, float], iterations: int = 8 ) -> Union[MPCTensor, float, Tensor]: """Approximates the exponential function using a limit approximation. exp(x) = lim_{n -> infty} (1 + x / n) ^ n Here we compute exp by choosing n = 2 ** d for some ...
9cfbb63d39d41e92b506366244ec6e77d52162b2
3,657,344
def isDllInCorrectPath(): """ Returns True if the BUFFY DLL is present and in the correct location (...\<BTS>\Mods\<BUFFY>\Assets\). """ return IS_DLL_IN_CORRECT_PATH
ea31391d41ba04b27df70124a65fdb48791cce57
3,657,346
import time def time_remaining(event_time): """ Args: event_time (time.struct_time): Time of the event. Returns: float: Time remaining between now and the event, in seconds since epoch. """ now = time.localtime() time_remaining = time.mktime(event_time) - time.mkti...
cb3dfcf916cffc3b45f215f7642aeac8a1d6fef7
3,657,347
def _repeat(values, count): """Produces a list of lists suitable for testing interleave. Args: values: for each element `x` the result contains `[x] * x` count: determines how many times to repeat `[x] * x` in the result Returns: A list of lists of values suitable for testing interleave. """ ret...
46aa7899e7ed536525b7a94675edf89958f6f37f
3,657,348
from functools import reduce def P2D_l_TAN(df, cond, attr): # P(attr | 'target', cond) """Calcule la probabilité d'un attribut sachant la classe et un autre attribut. Parameters ---------- df : pandas.DataFrame La base d'examples. cond : str Le nom de l'attribut conditionnant. ...
88affcaea0368c400ccd25356d97a25c9a88a15e
3,657,349
def has_no_jump(bigram, peaks_groundtruth): """ Tell if the two components of the bigram are same or successive in the sequence of valid peaks or not For exemple, if groundtruth = [1,2,3], [1,1] or [2,3] have no jump but [1,3] has a jump. bigram : the bigram to judge peaks_groundtruth : the lis...
e334c389436d5cda2642f8ac7629b64074dcd0e0
3,657,350
import base64 def Base64WSDecode(s): """ Return decoded version of given Base64 string. Ignore whitespace. Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type unicode to string type first. @param s: Base64 string to decode @type s: string @return: original string that was encod...
67db2d3f298e0220411f224299dcb20feeba5b3e
3,657,351
def make_window(): """create the window""" window = Tk() window.title("Pac-Man") window.geometry("%dx%d+%d+%d" % ( WINDOW_WIDTH, WINDOW_HEIGHT, X_WIN_POS, Y_WIN_POS ) ) window = window return window
1e9ecb5acf91e75797520c54be1087d24392f190
3,657,352
def hasf(e): """ Returns a function which if applied with `x` tests whether `x` has `e`. Examples -------- >>> filter(hasf("."), ['statement', 'A sentence.']) ['A sentence.'] """ return lambda x: e in x
ac9ce7cf2ed2ee8a050acf24a8d0a3b95b7f2d50
3,657,354
def borehole_model(x, theta): """Given x and theta, return matrix of [row x] times [row theta] of values.""" return f
9ccfd530ff162d5f2ec786757ec03917f3367635
3,657,355
def findNodesOnHostname(hostname): """Return the list of nodes name of a (non-dmgr) node on the given hostname, or None Function parameters: hostname - the hostname to check, with or without the domain suffix """ m = "findNodesOnHostname:" nodes = [] for nodename in listNodes():...
3a4f28d5fa8c72388cb81d40913e517d343834f0
3,657,356
def MakeControlClass( controlClass, name = None ): """Given a CoClass in a generated .py file, this function will return a Class object which can be used as an OCX control. This function is used when you do not want to handle any events from the OCX control. If you need events, then you should derive a class from...
634544543027b1870bb72544517511d4f7b08e39
3,657,357
def obtenTipoNom(linea): """ Obtiene por ahora la primera palabra del título, tendría que regresar de que se trata""" res = linea.split('\t') return res[6].partition(' ')[0]
73edc42c5203b7ebd0086876096cdd3b7c65a54c
3,657,358
def histogramfrom2Darray(array, nbins): """ Creates histogram of elements from 2 dimensional array :param array: input 2 dimensional array :param nbins: number of bins so that bin size = (maximum value in array - minimum value in array) / nbins the motivation for returning this array is for th...
2c377b926b4708b6a6b29d400ae82b8d2931b938
3,657,359
def build_pert_reg(unsupervised_regularizer, cut_backg_noise=1.0, cut_prob=1.0, box_reg_scale_mode='fixed', box_reg_scale=0.25, box_reg_random_aspect_ratio=False, cow_sigma_range=(4.0, 8.0), cow_prop_range=(0.0, 1.0),): """Build perturbation regularizer.""" i...
37d60049146c876d423fea6615cf43975f1ae389
3,657,360
def part_5b_avg_std_dev_of_replicates_analysis_completed(*jobs): """Check that the initial job data is written to the json files.""" file_written_bool_list = [] all_file_written_bool_pass = False for job in jobs: data_written_bool = False if job.isfile( f"../../src/engines/go...
f238382e18de32b86598d5daa13f92af01311d3d
3,657,361
def exportFlatClusterData(filename, root_dir, dataset_name, new_row_header,new_column_header,xt,ind1,ind2,display): """ Export the clustered results as a text file, only indicating the flat-clusters rather than the tree """ filename = string.replace(filename,'.pdf','.txt') export_text = export.ExportFi...
f9ade521b67c87518741fb56fb1c80df0961065a
3,657,362
def indent_multiline(s: str, indentation: str = " ", add_newlines: bool = True) -> str: """Indent the given string if it contains more than one line. Args: s: String to indent indentation: Indentation to prepend to each line. add_newlines: Whether to add newlines surrounding the result...
62eb2fc7c3f3b493a6edc009692f472e50e960f7
3,657,363
from typing import Optional def _get_property(self, key: str, *, offset: int = 0) -> Optional[int]: """Get a property from the location details. :param key: The key for the property :param offset: Any offset to apply to the value (if found) :returns: The property as an int value if found, None other...
8d2c35a88810db5255cfb0ca9d7bfa6345ff3276
3,657,364
def pca_normalization(points): """Projects points onto the directions of maximum variance.""" points = np.transpose(points) pca = PCA(n_components=len(np.transpose(points))) points = pca.fit_transform(points) return np.transpose(points)
753bea2546341fc0be3e7cf4fd444b3ee93378f9
3,657,365
def _reformTrend(percs, inits): """ Helper function to recreate original trend based on percent change data. """ trend = [] trend.append(percs[0]) for i in range(1, len(percs)): newLine = [] newLine.append(percs[i][0]) #append the date for j in range(1, len(percs[i])): #for each term on date level =...
1f6c8bbb4786b53ea2c06643108ff50691b6f89c
3,657,366
def PET_initialize_compression_structure(N_axial,N_azimuthal,N_u,N_v): """Obtain 'offsets' and 'locations' arrays for fully sampled PET compressed projection data. """ descriptor = [{'name':'N_axial','type':'uint','value':N_axial}, {'name':'N_azimuthal','type':'uint','value':N_azimuthal}, ...
1f879517182462d8b66886aa43a4103a05a5b6f9
3,657,367
def get_client_from_user_settings(settings_obj): """Same as get client, except its argument is a DropboxUserSettingsObject.""" return get_client(settings_obj.owner)
4b2c2e87310464807bf6f73d1ff8d7b7c21731ff
3,657,368
def train_student( model, dataset, test_data, test_labels, nb_labels, nb_teachers, stdnt_share, lap_scale, ): """This function trains a student using predictions made by an ensemble of teachers. The student and teacher models are trained using the same neural network architec...
de8db38bde151f5dd65b93a0c8a44c2289351f81
3,657,369
import numpy def create_transition_matrix_numeric(mu, d, v): """ Use numerical integration. This is not so compatible with algopy because it goes through fortran. Note that d = 2*h - 1 following Kimura 1957. The rate mu is a catch-all scaling factor. The finite distribution v is assumed to be ...
a60a3da34089fffe2a48cc282ea4cbb528454fd6
3,657,370
def channelmap(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#channelmap""" return filter(stream, channelmap.__name__, *args, **kwargs)
8293e9004fd4dfb7ff830e477dcee4de5d163a5d
3,657,372
def test_token(current_user: DBUser = Depends(get_current_user)): """ Test access-token """ return current_user
1ceb90c1321e358124520ab5b1b1ecb07de4619d
3,657,373
def process_label_imA(im): """Crop a label image so that the result contains all labels, then return separate images, one for each label. Returns a dictionary of images and corresponding labels (for choosing colours), also a scene bounding box. Need to run shape statistics to determine the n...
66e89e84d773d102c8fe7a6d10dd0604b52d9862
3,657,375
def render_graphs(csv_data, append_titles=""): """ Convenience function. Gets the aggregated `monthlies` data from `aggregate_monthly_data(csv_data)` and returns a dict of graph titles mapped to rendered SVGs from `monthly_total_precip_line()` and `monthly_avg_min_max_temp_line()` using the `monthli...
c2258faf759c2fd91e55fea06384d5f7ec030154
3,657,376
import traceback def _get_location(): """Return the location as a string, accounting for this function and the parent in the stack.""" return "".join(traceback.format_stack(limit=STACK_LIMIT + 2)[:-2])
f36037a440d2e8f3613beed217a758bc0cfa752d
3,657,377
def start_session(): """do nothing here """ return Response.failed_response('Error')
b8c58ec837c5a77c35cb6682c6c405489cf512c0
3,657,379
def _combine_keras_model_with_trill(embedding_tfhub_handle, aggregating_model): """Combines keras model with TRILL model.""" trill_layer = hub.KerasLayer( handle=embedding_tfhub_handle, trainable=False, arguments={'sample_rate': 16000}, output_key='embedding', output_shape=[None, 2048]...
97bf695e6b083dfefcad1d2c8ac24b54687047fd
3,657,380
def phases(times, names=[]): """ Creates named phases from a set of times defining the edges of hte intervals """ if not names: names = range(len(times)-1) return {names[i]:[times[i], times[i+1]] for (i, _) in enumerate(times) if i < len(times)-1}
0e56dcf57a736e4555cae02b8f79b827c17e1d38
3,657,381
def smesolve(H, rho0, times, c_ops=[], sc_ops=[], e_ops=[], _safe_mode=True, args={}, **kwargs): """ Solve stochastic master equation. Dispatch to specific solvers depending on the value of the `solver` keyword argument. Parameters ---------- H : :class:`qutip.Qobj`, or time depen...
4a27d54d2ca390bb3e4ac88ec2119633481df529
3,657,382
def harmonic_vector(n): """ create a vector in the form [1,1/2,1/3,...1/n] """ return np.array([[1.0 / i] for i in range(1, n + 1)], dtype='double')
6f2a94e0a54566db614bb3c4916e1a8538783862
3,657,383
import copy def get_install_task_flavor(job_config): """ Pokes through the install task's configuration (including its overrides) to figure out which flavor it will want to install. Only looks at the first instance of the install task in job_config. """ project, = job_config.get('project', 'c...
11fcefe3df17acfbce395949aa615d8292585fb6
3,657,384
def equalize_hist(image, nbins=256): """Return image after histogram equalization. Parameters ---------- image : array Image array. nbins : int Number of bins for image histogram. Returns ------- out : float array Image array after histogram equalization. N...
ea990cee9bef0e2edc41e2c5279f52b98d2a4d89
3,657,385
def add9336(rh): """ Adds a 9336 (FBA) disk to virtual machine's directory entry. Input: Request Handle with the following properties: function - 'CHANGEVM' subfunction - 'ADD9336' userid - userid of the virtual machine parms['diskPool'] - Disk pool ...
bb7168d5b0ee084b15e8ef91633d5554669cf83f
3,657,386
def get_related(user, kwargs): """ Get related model from user's input. """ for item in user.access_extra: if item[1] in kwargs: related_model = apps.get_model(item[0], item[1]) kwargs[item[1]] = related_model.objects.get(pk=get_id(kwargs[item[1]])) return kwargs
6b2ce081d1f61da734d26ef6f3c25e4da871b9ee
3,657,388
def make_logical(n_tiles=1): """ Make a toy dataset with three labels that represent the logical functions: OR, XOR, AND (functions of the 2D input). """ pat = np.array([ # X X Y Y Y [0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [1, 0, 1, 1, 0], [1, 1, 1, 0, ...
e2d936db7ae0d9ea8b0f1654e89a32b5b8c247cc
3,657,389
def get_idmap_etl( p_idmap: object, p_etl_id: str, p_source_table: object =None ): """ Генерирует скрипт ETL для таблицы Idmap :param p_idmap: объект класса Idmap :param p_etl_id: id etl процесса :param p_source_table: таблица источник, которую требуется загрузить в idmap ...
0e24b4cbb5ea935c871cae3338094292c9ebfd02
3,657,390
def gs_tie(men, women, preftie): """ Gale-shapley algorithm, modified to exclude unacceptable matches Inputs: men (list of men's names) women (list of women's names) pref (dictionary of preferences mapping names to list of sets of preferred names in sorted order) Output: dictiona...
b5dbe7047e3e6be7f0d288e49f8dae25a94db318
3,657,391
def is_iterable(value): """Return True if the object is an iterable type.""" return hasattr(value, '__iter__')
55e1ecc9b264d39aaf5cfcbe89fdc01264191d95
3,657,392
def get_search_app_by_model(model): """ :returns: a single search app (by django model) :param model: django model for the search app :raises LookupError: if it can't find the search app """ for search_app in get_search_apps(): if search_app.queryset.model is model: return se...
0670fe754df65b02d5dfc502ba3bd0a3a802370c
3,657,393
def prct_overlap(adata, key_1, key_2, norm=False, ax_norm="row", sort_index=False): """ % or cell count corresponding to the overlap of different cell types between 2 set of annotations/clusters. Parameters ---------- adata: AnnData objet key_1: observational key corresponding to one ce...
77a8382af77e8842a99211af58d6a6f85de6a50e
3,657,394
def keep_category(df, colname, pct=0.05, n=5): """ Keep a pct or number of every levels of a categorical variable Parameters ---------- pct : float Keep at least pct of the nb of observations having a specific category n : int Keep at least n of the variables having a specific categ...
3db00aa6bdea797827a693c8e12bbf942a55ec35
3,657,395
def remove_scope_from_name(name, scope): """ Args: name (str): full name of the tf variable with all the scopes Returns: (str): full name of the variable with the scope removed """ result = name.split(scope)[1] result = result[1:] if result[0] == '/' else result return resul...
aa70042a2f57185a0f5e401d182a02e5654eb2b0
3,657,396
async def get_timers_matching(ctx, name_str, channel_only=True, info=False): """ Interactively get a guild timer matching the given string. Parameters ---------- name_str: str Name or partial name of a group timer in the current guild or channel. channel_only: bool Whether to ma...
48e94d2930f48b47b033ec024246065206a2bebb
3,657,397
import random def comprehension_array(size=1000000): """Fills an array that is handled by Python via list comprehension.""" return [random() * i for i in range(size)]
e3ccdc992e5b741cf6f164c93d36f2e45d59a590
3,657,398
def alignment(alpha, p, treatment): """Alignment confounding function. Reference: Blackwell, Matthew. "A selection bias approach to sensitivity analysis for causal effects." Political Analysis 22.2 (2014): 169-182. https://www.mattblackwell.org/files/papers/causalsens.pdf Args: alpha (np.a...
8097dbcd62ba934b31b1f8a9e72fd906109b5181
3,657,399
def percentiles(a, pcts, axis=None): """Like scoreatpercentile but can take and return array of percentiles. Parameters ---------- a : array data pcts : sequence of percentile values percentile or percentiles to find score at axis : int or None if not None, computes scor...
0e7217ec3e36a361a6747729543cd694912a2874
3,657,400
import json def single_request(gh,kname='CVE exploit',page=1,per_page=50): """ 解析单页仓库数据,获取CVE和exp标记 :return cve_list:list, cve id in each page by searching github.com """ cve=dict() url="https://api.github.com/search/repositories?q={key_name}&sort=updated&order=desc&page={page}&per_page={per_p...
5fdd3fe28f0e973fb9d854e20b8ce77ed109d3c6
3,657,401
def stuff_context(sites, rup, dists): """ Function to fill a rupture context with the contents of all of the other contexts. Args: sites (SiteCollection): A SiteCollection object. rup (RuptureContext): A RuptureContext object. dists (DistanceContext): A DistanceContext object....
9c197a41414a875942a6df22c03899c3e936967f
3,657,403
def number_to_float(value): """The INDI spec allows a number of different number formats, given any, this returns a float :param value: A number string of a float, integer or sexagesimal :type value: String :return: The number as a float :rtype: Float """ # negative is True, if the value i...
8b754a32848b3e697e0f82dbee4a1c35c560f1be
3,657,404
def spg_line_search_step_length(current_step_length, delta, f_old, f_new, sigma_one=0.1, sigma_two=0.9): """Return next step length for line search.""" step_length_tmp = (-0.5 * current_step_length ** 2 * delta / (f_new - f_old - current_step_length * delt...
844cccdfe1ec3f9c2c287384284ceb2ac3530e8e
3,657,405
def calc_pv_invest(area, kw_to_area=0.125, method='EuPD'): """ Calculate PV investment cost in Euro Parameters ---------- area : float Photovoltaic area kw_to_area : float , optional Ratio of peak power to area (default: 0.125) For instance, 0.125 means 0.125 kWp / m2 ar...
2de9ee05580bc9d41522272a06cd97aaf3f5bc55
3,657,407
def samps2ms(samples: float, sr: int) -> float: """samples to milliseconds given a sampling rate""" return (samples / sr) * 1000.0
49e07ee02984bf0e9a0a54715ef6b6e5a3c87798
3,657,409
def nice_year(dt, lang=None, bc=False): """Format a datetime to a pronounceable year. For example, generate 'nineteen-hundred and eighty-four' for year 1984 Args: dt (datetime): date to format (assumes already in local timezone) lang (string): the language to use, use Mycroft default langua...
641195195023ecca030f6cd8d12ff9a3fc9c989c
3,657,410
def get_results(job_id): """ Get the result of the job based on its id """ try: job = Job.fetch(job_id, connection=conn) if job.is_finished: return jsonify({ "status": "finished", "data": job.result }), 200 elif job.is_f...
ada9042cd4d7961415ec274a68631f6e9af81fad
3,657,411
def get_clean_dict(obj: HikaruBase) -> dict: """ Turns an instance of a HikaruBase into a dict without values of None This function returns a Python dict object that represents the hierarchy of objects starting at ``obj`` and recusing into any nested objects. The returned dict **does not** include ...
3daca47b6d8c42fca8856221f39b635791eb0fce
3,657,412
def generate_html_frieze(type, value): """ Gets the data to be able to generate the frieze. Calls the function to actually generate HTML. Input: - Type (session or dataset) of the second input - A SQLAlchemy DB session or a dataset (list of mappings) Output: - The HTML to be...
ddf914d9d710e60af48a6dc687a9e3961ab0cf94
3,657,413
from typing import Optional import re def instantiate_model(model_to_train: str, dataset_directory: str, performance_directory: str, gpu: Optional[bool] = None): """ A function to create the instance of the imported Class, Classifier. Ar...
8053053b5e77f1c74404826e7335b05bece8b99f
3,657,415
def generate_hmac_key(): """ Generates a key for use in the :func:`~securitylib.advanced_crypto.hmac` function. :returns: :class:`str` -- The generated key, in byte string. """ return generate_secret_key(HMAC_KEY_MINIMUM_LENGTH)
877cf9fbe56b6715f1744839ce83ac1abf9d7da8
3,657,416
def uscensus(location, **kwargs): """US Census Provider Params ------ :param location: Your search location you want geocoded. :param benchmark: (default=4) Use the following: > Public_AR_Current or 4 > Public_AR_ACSYYYY or 8 > Public_AR_Census2010 or 9 :param vintage: (...
bd73acb87f27e3f14d0b1e22ebd06b91fcec9d85
3,657,418
def reco_source_position_sky(cog_x, cog_y, disp_dx, disp_dy, focal_length, pointing_alt, pointing_az): """ Compute the reconstructed source position in the sky Parameters ---------- cog_x: `astropy.units.Quantity` cog_y: `astropy.units.Quantity` disp: DispContainer focal_length: `astrop...
14b7fee325bc8a571a13d257f046cd0e7bf838db
3,657,420
def segment_annotations(table, num, length, step=None): """ Generate a segmented annotation table by stepping across the audio files, using a fixed step size (step) and fixed selection window size (length). Args: table: pandas DataFrame Annotation table. ...
4b1bb8298113b43716fcd5f7d2a27b244f63829c
3,657,421
def get_vdw_style(vdw_styles, cut_styles, cutoffs): """Get the VDW_Style section of the input file Parameters ---------- vdw_styles : list list of vdw_style for each box, one entry per box cut_styles : list list of cutoff_style for each box, one entry per box. For a box with...
5cd0825d73e11c4fcb8ecce0526493414842697c
3,657,422
def freduce(x, axis=None): """ Reduces a spectrum to positive frequencies only Works on the last dimension (contiguous in c-stored array) :param x: numpy.ndarray :param axis: axis along which to perform reduction (last axis by default) :return: numpy.ndarray """ if axis is None: ...
8d13e66a18ef950422af49a68012605cf0d03947
3,657,424
import json def sort_shipping_methods(request): """Sorts shipping methods after drag 'n drop. """ shipping_methods = request.POST.get("objs", "").split('&') assert (isinstance(shipping_methods, list)) if len(shipping_methods) > 0: priority = 10 for sm_str in shipping_methods: ...
307ecef020ac296982a7006ce1392cb807461546
3,657,426
def appendRecordData(record_df, record): """ Args: record_df (pd.DataFrame): record (vcf.model._Record): Returns: (pd.DataFrame): record_df with an additional row of record (SNP) data. """ # Alternate allele bases if len(record.ALT) == 0: alt0, alt1 = n...
0904b317e1925743ed9449e1fcb53aaafa2ffc81
3,657,427
def get_removed_channels_from_file(fn): """ Load a list of removed channels from a file. Raises ------ * NotImplementedError if the file format isn't supported. Parameters ---------- fn : str Filename Returns ------- to_remove : list of str List of channels...
ac3cbeb83c7f1305adf343ce26be3f70f8ae48e8
3,657,428
def invertHomogeneous(M, range_space_homogeneous=False, A_property=None): """ Return the inverse transformation of a homogeneous matrix. A homogenous matrix :math:`M` represents the transformation :math:`y = A x + b` in homogeneous coordinates. More precisely, ..math: M \tilde{x} = \left[ \begi...
ea9039c935c82686291145652f762eb79404e417
3,657,429
import requests def show_department(department_id): """ Returns rendered template to show department with its employees. :param department_id: department id :return: rendered template to show department with its employees """ url = f'{HOST}api/department/{department_id}' department = reque...
170318ea40a4f7355fab77f2aeaaad682b9fab2f
3,657,431
def archive_scan(): """ Returns converted to a dictionary of functions to apply to parameters of archive_scan.py """ # Dictionary of default values setter, type converters and other applied functions d_applied_functions = { 'favor': [bool_converter, favor_default], 'cnn': [bool_conve...
71aa3d2c17e880a152529de09b0614dfd619e7da
3,657,432
def esOperador(o): """"retorna true si 'o' es un operador""" return o == "+" or o == "-" or o == "/" or o == "*"
7e1088b641dee7cad2594159c4a34cf979362458
3,657,433
def valid_identity(identity): """Determines whether or not the provided identity is a valid value.""" valid = (identity == "homer") or (identity == "sherlock") return valid
9865d19802b596d1d5fdce6ff8d236678da29ee6
3,657,434
def is_align_flow(*args): """ is_align_flow(ea) -> bool """ return _ida_nalt.is_align_flow(*args)
40aa1fb7d86083bc3ace94c6913eb9b4b5ab200e
3,657,435
import time def avro_rdd(ctx, sqlContext, hdir, date=None, verbose=None): """ Parse avro-snappy files on HDFS :returns: a Spark RDD object """ if date == None: date = time.strftime("year=%Y/month=%-m/day=%-d", time.gmtime(time.time()-60*60*24)) path = '%s/%s' % (hdir, date) e...
caa923e4b6186e106a59764cbb61f908858acd70
3,657,436
import random def generate_gesture_trace(position): """ 生成手势验证码轨迹 :param position: :return: """ x = [] y = [] for i in position: x.append(int(i.split(',')[0])) y.append(int(i.split(',')[1])) trace_x = [] trace_y = [] for _ in range(0, 2): tepx = [x[...
3281cf9e99175190e2855ac98593f67473703c77
3,657,437
def mad_daub_noise_est(x, c=0.6744): """ Estimate the statistical dispersion of the noise with Median Absolute Deviation on the first order detail coefficients of the 1d-Daubechies wavelets transform. """ try: _, cD = pywt.wavedec(x, pywt.Wavelet('db3'), level=1) except ValueError: ...
3811d490e344cd4029e5b7f018823ad02c27e3dd
3,657,439
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's ...
3fc85ffec7faa3b4df2d1556dfd7b1d7c3e9920e
3,657,440
import json def get_categories() -> dict: """ :return: dictionary with a hirachy of all categories """ with open("../src/categories.json", "r", encoding="utf-8") as f: return json.load(f)
90a442840550f3251137b2f9ff8fb5581d8d49e5
3,657,441
def get_ax(rows=1, cols=1, size=16): """Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes. Adjust the size attribute to control how big to render images """ _, ax = plt.subplots(rows, cols, figsize=(size*cols, siz...
97acc81878076c030287840a0bbacccbde0e50a8
3,657,443
def createSynthModel(): """Return the modeling mesh, the porosity distribution and the parametric mesh for inversion. """ # Create the synthetic model world = mt.createCircle(boundaryMarker=-1, segments=64) tri = mt.createPolygon([[-0.8, -0], [-0.5, -0.7], [0.7, 0.5]], ...
aa63ce6c8b633530efb17add4d902da30c62689c
3,657,445
def edits_dir(): """ Return the directory for the editable files (used by the website). """ return _mkifnotexists("")
eb882c04e3269496a610103908453a73e4a7ae5f
3,657,446
def convolve_hrf(X, onsets, durations, n_vol, tr, ops=100): """ Convolve each X's column iteratively with HRF and align with the timeline of BOLD signal parameters: ---------- X[array]: [n_event, n_sample] onsets[array_like]: in sec. size = n_event durations[array_like]: in sec. size = n_ev...
d035b47ffafe0ac3d7e1446d4d36dc2f707363bd
3,657,448
def flatten(x, params): """ Plain ol' 2D flatten :param x: input tensor :param params: {dict} hyperparams (sub-selection) :return: output tensor """ return layers.Flatten()(x)
6db829641681ab48f75b23894f9a4a3250250cec
3,657,449
def xml_unescape(text): """ Do the inverse of `xml_escape`. Parameters ---------- text: str The text to be escaped. Returns ------- escaped_text: str """ return unescape(text, xml_unescape_table)
2e53d8bc617ad70fd22bb5dd82cd34db366b80a4
3,657,450
def tseb_pt(T_air, T_rad, u, p, z, Rs_1, Rs24, vza, zs, aleafv, aleafn, aleafl, adeadv, adeadn, adeadl, albedo, ndvi, lai, clump, hc, time, t_rise, t_end, leaf_width, a_PT_in=1.32, iterations=35): """Priestley-Taylor TSEB Calculates the Priestley Taylor TSEB fluxes using a s...
6851b00f27b1819e79ce7ed625074c37ac35298f
3,657,451
def GetPrivateIpv6GoogleAccessTypeMapper(messages, hidden=False): """Returns a mapper from text options to the PrivateIpv6GoogleAccess enum. Args: messages: The message module. hidden: Whether the flag should be hidden in the choice_arg """ help_text = """ Sets the type of private access to Google ser...
9aa87977be9d0888d572c70d07535c9ec0b9d8f4
3,657,452
def calc_director(moi): """ Calculate the director from a moment of inertia. The director is the dominant eigenvector of the MOI tensor Parameters: ----------- moi : list 3x3 array; MOItensor Returns: -------- director : list 3 element list of director vector """ ...
28f8b3446f83759704d426653dc8f7812e71e900
3,657,453
def _solve_upper_triangular(A, b): """ Solves Ax=b when A is upper triangular. """ return solve_triangular(A, b, lower=False)
5c33d5d10922172a133a478bdfdcb8cf7cd83120
3,657,454
def check_create_account_key(key): """ Returns the user_id if the reset key is valid (matches a user_id and that user does not already have an account). Otherwise returns None. """ query = sqlalchemy.text(""" SELECT user_id FROM members WHERE create_account_key = :k AND user_id NOT IN (SELEC...
b02a710d443410b5b60c31a030d056f3282a5747
3,657,455
def _crc16(data, start = _CRC16_START) : """Compute CRC16 for bytes/bytearray/memoryview data""" crc = start for b in data : crc ^= b << 8 for _ in range(8) : crc = ((crc << 1) & 0xFFFF) ^ _CRC16_POLY if crc & 0x8000 else (crc << 1) return crc
e6e33471601d3126ac7873b61e23f843349e8e90
3,657,457
import json def load_json(): """Load the translation dictionary.""" try: with open(JSON_FILENAME, "r", encoding="utf8") as file: known_names = json.load(file) if "version" in known_names: if known_names.get("version") < JSON_VERSION: print("U...
d263411d0c0aae7bba30f92c5af22dd7ff596542
3,657,458
def get_username() -> str: """ Prompts the user to enter a username and then returns it :return: The username entered by the user """ while True: print("Please enter your username (without spaces)") username = input().strip() if ' ' not in username: return usernam...
1a18a229908b86c32a0822c068b5b9081cc9fdc3
3,657,459
def condition(f): """ Decorator for conditions """ @wraps(f) def try_execute(*args, **kwargs): try: res, m = f(*args, **kwargs) m.conditions_results.append(res) return m except Exception as e: raise ConditionError(e) return try_ex...
fb05645861c7aa234f894cc8eee3689e1f1293c9
3,657,460
def get_spatial_anomalies( coarse_obs_path, fine_obs_rechunked_path, variable, connection_string ) -> xr.Dataset: """Calculate the seasonal cycle (12 timesteps) spatial anomaly associated with aggregating the fine_obs to a given coarsened scale and then reinterpolating it back to the original spatial re...
54dc830e9eb6b7440abf5857141ab369d8d45358
3,657,461