content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _get_posterior_merge_prob(clusti: Cluster, clustj: Cluster, params: dict): """ calculate posterior merge probability for clusters i and j given prior params `params` :param clusti: cluster i :param clustj: cluster j :param params: dictionary of prior parameters :return: posterior probabilit...
15cff4438d8b8b92cbd3c9eaf45395e1e082226b
3,617,509
def multiplyMyNumbers(a, b): """ multiply_my_numbers == PEP8 (forced mixedCase by CodeWars) """ return str(convert_num(a) * convert_num(b))
a7d4eef808a42753b42d0b62a34922bf664a760c
3,617,510
def retrieve_cnv_data(store, solution, chromosome=''): """ Retrieve copy number data for a specific solution """ cnv = store['solutions/solution_{0}/cn'.format(solution)] if chromosome != '': cnv = cnv[cnv['chromosome'] == chromosome].copy() cnv['segment_idx'] = cnv.index return cnv
2c77415909ff27a3b3fd00e7abb8d25b67b6ea8f
3,617,511
def max_drawdown(returns): """ Determines the maximum drawdown of a strategy. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. Returns ------- float Maximum drawdown....
3a133bd9bb129f8b7a1c6510ba938a41a5e45ebd
3,617,512
def macys(macys_url : str) -> dict: """Scrape product information from macys.com Keyword arguments: macys_url -- a product url from macys.com """ macys_product = _macys._macys(macys_url) return macys_product
db2ff495d9d54edf069bdb93933b8249a6232246
3,617,513
def square_root_mod_prime(a, p): """Modular square root of a, mod p, p prime.""" # Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39. # This module has been tested for all values in [0,p-1] for # every prime p from 3 to 1229. assert 0 <= a < p assert 1 < p if a == 0:...
788dc4d73bcc6a8467b7ee57c14aa5059975c0dd
3,617,514
def parse_export_request(): """ Check if request contains all required fields """ required_headers = { "X-Requested-By": ["GGRC"], "Content-Type": ["application/json"], "X-export-view": ["blocks", "grid"], } check_required_headers(required_headers) return request.json
a16ab2fddec46a0bbaffce83efc3ddaa6c05a241
3,617,516
def row_count(data): """ Return the # of rows/features in the provided data (feature class, table, feature layer or table view) """ return int(arcpy.GetCount_management(data).getOutput(0))
53ee9b06b8a6fcce50384549fc4ef846dedd892e
3,617,518
def banner(text: str, *, borderChar: str = '='): """Print 'text' as banner, optionally customise 'borderChar'.""" border = borderChar * len(text) return '\n'.join([border, text, border])
76d27b762173e35a15e0e445eccea85cdef3b327
3,617,520
import site def add_new_obj_btn(form_obj ,field): """put a add btn for foreignkey and m2m field""" #print("add_new_obj_btn site enabled ",site.enabled_admins) field_obj = form_obj.instance._meta.get_field(field.name) field_type = field_obj.get_internal_type() if field_type in ("ForeignKey", "Many...
0b76dda1b3e2eb9b1954fcee9ff60b457a791391
3,617,521
def commit_candidate(self, config): """ Commit the candidate configuration. :param self: object from class :param config: :return: """ url = self.connection.config["api_url"] + "system/config/cfg_restore" data = {"server_type": "ST_FLASH", "file_name": config, "is_oobm": False} cmd_...
90a89ce11b26b21969f364bd49cfd3c3e6eb15b0
3,617,522
def parse_turn(turn): """Parse the input from the user for valid player strings and play positions Args: turn (string): Input string from the user that contains the played position (0-8) Returns: (int/None): Returns interger on success or None on failure """ t...
90abe0050ed6413931f8b50e622e4083c2fa4d87
3,617,523
def phonenumber(anon, obj, field, val): """ Generates a random US-style phone number """ return anon.faker.phone_number(field=field)
8d19ba96b805fd117e2ceb9a926bb1f8a9966e0b
3,617,524
def noop(obs): """ Transform that does absolutely nothing! """ return obs
95ad1168d804c1021f328090068c7d6a260b7ca4
3,617,525
import numpy as np def RectangularGrid(dX, iMax, dY=None, jMax=None): """Return a rectangular uniform rectangular mesh. X and/or Y grid point locations are computed in a cartesian coordinate system using the grid step size and grid points. Call Signature: RectangularGrid(dX, iMax, dY=No...
15445a2e700d3e0989a47e198732582a51c30d5f
3,617,526
import torch def make_2d_link_active_stripes(shape, mu, off): """ Stripes mask looks like in the `mu` channel (mu-oriented links):: 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 where vertical is the `mu` direction, and the pattern is off...
61afa81c826514adbf11293e3b1e4912ff6b4757
3,617,527
def get_job_uri(uuid): """ Queries the database for SchemaAnalysisJob objects that have the uuid as specified by "uuid". """ job_query = """ PREFIX ext: <http://mu.semte.ch/vocabularies/ext/> PREFIX mu: <http://mu.semte.ch/vocabularies/core/> PREFIX dct: <http://purl.org/dc/t...
384dbdc892ad281c57bffcf408e5c17dfff68fe2
3,617,528
import functools import time def build_access_required(function_or_param_name): """Decorator ensures user has access to the build ID in the request. May be used in two ways: @build_access_required def my_func(build): ... @build_access_required('custom_build_id_param') ...
2802c2204214e3a475d4ef53a99ebac7314ea42f
3,617,529
def add(a,b): """ This function returns the sum of the given numbers """ return a + b
9998c4a350973839aeb8f64fe0ba555297f35ccc
3,617,530
from typing import Iterable from typing import Mapping def schema( pairs: Iterable[tuple[str, dt.DataType]] | Mapping[str, dt.DataType] | None = None, names: Iterable[str] | None = None, types: Iterable[str | dt.DataType] | None = None, ) -> sch.Schema: """Validate and return an Schema object....
635cc9d0cac1af42ffd167bf36e4ad3c62ee7c37
3,617,531
def command_sync(command: str = None): """Executes a synchronous command.""" return runner.execute(asynchronous=False).flask_serialize()
60ccbf6109eb3647615dc552908606bc5bb0dc08
3,617,532
import random def _is_prime(number, attempts=10): """ Miller-Rabin primality test. A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. """ if number != int(number): return False number = int(number) if atte...
05fa3b4a8c9266b491449cc908392c535f5b2196
3,617,533
def get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units='m', comments='#', skiprows=0, shape0=2): """ Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units Useful for :meth:`tofu.plugins.AUG.Ves._create()` Parameters ---------- PolyFileO...
402da52eba8408a99d869e423ebee3053b88d0fe
3,617,535
def Calc(start,end,data,vsk): """Calculates angles and joint values for marker data in a given range This function is a wrapper around `calcFrames`. It calls `calcFrames` with the given `data` and `vsk` inputs starting at index `start` and ending at index `end` in `data`. Parameters ----------...
beda0cc105227b2c69c6ad41fedf2fc35ed11abd
3,617,537
def flags_to_release(is_minor=False, is_major=False): """Convert flags to release type.""" if is_minor and is_major: raise ValueError("Both `is_minor` and `is_major` are set to 'True'.") if is_minor: return "minor" if is_major: return "major" return "normal"
e4f80774b72da544f20fe6ead5816dbed2a3755c
3,617,538
import copy def _recursive_gf(energy, mat_l_list, mat_d_list, mat_u_list, s_in=0, s_out=0, damp=0.000001j): """The recursive Green's function algorithm is taken from M. P. Anantram, M. S. Lundstrom and D. E. Nikonov, Proceedings of the IEEE, 96, 1511 - 1550 (2008) DOI: 10.1109/JPROC.2008.927355 I...
69b26fd2cf0f78287661af82c1b7a0a8492ede19
3,617,539
import tempfile from datetime import datetime def query_saio(instrument="EIT", begindate=(TODAY - timedelta(days=1)), enddate=TODAY, min_wave=171.0, max_wave=171.0, resolution=1024, return_type="VOTABLE"): """ Method to query the SAIO...
6f788bd1bf815781d05ae1b4befd0b9dc20a698e
3,617,540
from typing import Union import yaml def read_yaml(path: str) -> Union[dict, list]: """Loads yaml at given path Args: path (str): path to yaml file Returns: Union[dict, list]: dictionary or list loaded from yaml depending on the yaml """ with open(path, encoding="UTF-8") as yaml_...
66138b8968865d8951ae366ab3adb0c342bbfabe
3,617,542
def is_legal(x, y, img): """ Check if (x, y) is a valid coordinate in img Args: x (int): x-coordinate y (int): y-coordinate img (numpy.array): Image Returns: bool -> True if valid, False otherwise """ if 0 <= x < img.shape[1] and 0 <= y < img.shape[0]: ...
bc86f6b032932e4fb33b3d1983fc2a8586176e5f
3,617,543
import html def scrape_results_page(page_str, xpath_list): """Scrapes HTML page and returns dictionary of URL => document title Args: page_str -- the entire HTML page as a string xpath_list -- list of xpath expressions (section and link element) Returns: document_ids -- a dictionary of relat...
2713eec65f0ddbd23c3beb19c7969b333a9fca8a
3,617,544
import re def find_special_vertex_groups(special_vertex_group_pattern, bg_name=None): """ While ordinary vertex groups may have little semantic information, we accept annotated models with special vertex groups, prefixed with a keyword. This function finds all such verte...
150740c0486100f0b97f18bea324aaad6173212f
3,617,545
def get_posts(): """Return all posts from the 'database', most recent first.""" db = psycopg2.connect(database=DBNAME) c = db.cursor() query = 'SELECT content,time FROM posts ORDER BY time DESC' c.execute(query) posts = c.fetchall() db.close() return posts
1b441db72ac6e35149dae6715be9aa0754f11cf9
3,617,546
def gaussian_image_pyramid(img): """Computes image gaussian pyramid from frame or image.""" gaussian = img.copy() #needs better name pyramid = [gaussian] for i in range(6): gaussian = cv.pyrDown(gaussian) pyramid.append(gaussian) return pyramid
915ea5b5a3ebca35a28e3c41da5cf0458f8aa703
3,617,547
def validation_errors(record, schema): """Return a dict of errors upon validating the record against the schema. """ v = AutaValidator(schema, allow_unknown=True) v.validate(record) return v.errors
14b7c51a04b8fdd2988b4851d833295856de0fe1
3,617,549
from typing import Tuple from typing import Optional def get_javac_version() -> Tuple[Optional[str], Optional[int]]: """ A function that shells out to the ``javac`` tool to determine the installed version. We use ``javac`` as we want to make sure that the JDK is installed and not just the JRE. :...
e7261e0d8157502fc0bb83736dfc6ac8ecb6786b
3,617,550
def split_by_type(activity_references): """Given a list of activity references, returns two lists: the first list contains the exploration ids, and the second contains the collection ids. The elements in each of the returned lists are in the same order as those in the input list. Args: acti...
25df9ab3a07a7c99692eab70cd1f0a18329a06d5
3,617,551
def get_nodes_by_namespace(graph, namespaces): """Get all nodes in the namespace or namespaces. :param pybel.BELGraph graph: A BEL graph :param namespaces: namespaces to be filtered :type namespaces: str or iter[str] :rtype: set[BaseEntity] """ return get_nodes(graph, namespace_inclusion_bu...
1cd96b13b9941aadfe63f6a8956814c76e3b3201
3,617,552
def prepare_playlists(user,labelled_data): """ prepares the user's playlists for upload and display Args: user (SpotifyUser) labelled_data (DataFrame or array-like) Returns: Dictionary: uploadable playlists in JSON format """ return user.generate_uploadable_playlists(la...
85a7843997cb759b866e30d6d70f8fdecfc95dc5
3,617,553
def add(i): """得到114个add函数对应的的字符串""" return ".add(user_id_list[" + str(i) + "][0], \n" \ "\tpeople[" + str(i) + "], \n" \ "\txaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_='dataMax'), \n" \ "\tyaxis3d_opts=opts.Axis3DOpts(type_='value', min_='dataMin', max_=...
5ba345b2e6ed224f06fffab47aef44c01328fe80
3,617,554
def is_structured_array(array: np.ndarray) -> bool: """ Determines whether a numpy array-like object is a structured array. Parameters ---------- array : numpy.ndarray The array to be checked. Raises ------ TypeError The input array is not a numpy array-like object. ...
cc6bcead1478f00397dd0617839180b092117498
3,617,555
def find_path(path, topdir): """Find a file in a top to bottom search through the repository hierarchy. For all repositories/directories from `topdir` down to the core repository in BASE_DIR, check whether the relative `path` exists and, if yes, return its absolute path. `path` can be any file system o...
087b4fc56fdcf5e6fb71cca8557b329958bcab09
3,617,556
from typing import List def filter_representative_sites_patient( df: pd.DataFrame, representative_sites: List[str]) -> pd.DataFrame: """ Filters out representative sites from the given data frame for a single patient. Args: df: The data frame to filter. representative_sites: R...
4dde55e654564ba2c66b77498dfb55df099c5bf8
3,617,557
from datetime import datetime import json def do(huc12, mode): """Do work""" pgconn = get_dbconn("idep") cursor = pgconn.cursor() utcnow = datetime.datetime.utcnow() if mode == "daily": cursor.execute( """ SELECT valid, avg_loss * 4.463, avg_delivery * 4.463, ...
fa3be701bd06c28d9d902f293d80c042702df957
3,617,558
from datetime import datetime def get_recent_assets(): """ Returns the last created assets """ assets_list = [] assets = list() for group_id in settings.LIST_GROUP_ID: assetgroup = PATROWL_API.get_assetgroup_by_id(group_id) assets += sorted(assetgroup['assets'], key=lambda k: k...
463d0601ea717924711be9acf2a9c176ff567e49
3,617,560
def rates_for_yr(rates_all_years, sim_year): """ Filter specific rates for a given year Parameters ---------- rates_all_years : pandas DataFrame rates, to be filtered by year sim_year : int year being simulated Returns ------- pop_w_rates : pandas DataFrame ...
616cec13b0a686c2c7504c187c31dafaa7f88b6f
3,617,561
def _check_areas_and_format(areas, grid_model="usa_tamu"): """Ensure that areas are valid. Duplicates are removed and state abbreviations are converted to their actual name. :param str/list/tuple/set areas: areas(s) to check. Could be load zone name(s), state name(s)/abbreviation(s) or interconnect...
e111bcc678156cdc5c320d74f1767ba9fd92d0d4
3,617,562
def add_handover_volunteer(full_name, phone_number, languages): """ add a volunteer to the handover list :param full_name: volunteer's first name and last name :param phone_number: volunteer's phone number :param languages: language(s) the person can speak (answer users' queries) - used for matching...
d57297cce684c6745a35d43b492342fc56aa8d21
3,617,563
def list_key_pairs(profile, **libcloud_kwargs): """ List all the available key pair objects. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_key_pairs method :type libcloud_kwargs: ``dict`` CLI Example: .. code-bl...
60b41b2c493b96300017e4f319d04d1129f1f3b0
3,617,564
def randint(low, high, m=1, n=1): """ :param low: Lower bound on possible random ints :param high: Max possible random int (INCLUSIVE) :param m: number of rows in output :param n: number of cols in output Generates an ``m x n`` whose elements are integers selected uniform random in the rang...
da1ccf94e840678531b46bc7afa95f3ab6a654aa
3,617,565
from pathlib import Path def path_xy(port1, port2, directions = 'xxyx'): """ Creates a Path that travels only in x and y directions (manhattan) from one point (or Port) to another. The `directions` string determines the order of the x/y steps. Example: `directions = 'xyx'` will travel 1/2 the dist...
c1a0f3289f0a38a9bfd8f64d98668edfc491839b
3,617,566
def _get_initializer( initialization_method: str, initialization_range: float, initialization_std: float) -> tf.keras.initializers.Initializer: """Gets variable initializer.""" if initialization_method == 'uniform': initializer = tf.keras.initializers.RandomUniform( minval=-initialization_ra...
ad5ce56d8b68ab03a2c3f222b99682798da4c035
3,617,567
def topic_matches_sub(sub, topic): """Check whether a topic matches a subscription. For example: foo/bar would match the subscription foo/# or +/bar non/matching would not match the subscription non/+/+ """ result = True local_sub = _fix_sub_topic(sub) local_topic = _fix_sub_to...
0230cd8e1ba6524c578f3e2e8066e2912454296c
3,617,568
from typing import List from typing import Optional import re def absent_downstream_subtypes(subtype: str, subtypes: pd.Series, scheme_subtypes: List[str]) -> Optional[List[str]]: """Find the downstream subtypes that are not present in the results ...
678774ec7a1561f559bc12699e30933573b8f2e9
3,617,573
def get_estimated_prob(key): """ Gets estimated probability which is the sum of worst NRR probability and only-NRR-based probability. """ return get_worst_prob(key) + get_nrr_prob(key)
4240a318a29f1e347100ac0b3b1856accdf90ed6
3,617,574
def _build_score_dict(pitches, onsets, durations, melody, vel_trend, vel_dev, log_bpr, timing, log_art, pedal=None): """Helper method to build a dictionary with score and performance information for each score position. Parameters ---------- pitches : ...
f0ee0584e4f1837e1f56e478912728bfa0d10043
3,617,575
def create(request): """ create command, called from the djangy command line client.""" email = request.POST.get('email') application_name = request.POST.get('application_name') # check for that application name if not name_available(application_name): return HttpResponseBadRequest('Error: ...
30f8497ec07e08924cc1131264351b5ff1dc1100
3,617,576
def getGraphComponents(model: str, scalable_components: list = []): """ Gets the list of component and their instances, as well as the list of conflicts between components. Args: model (str): The name of the minizinc model. scalable_components (list, optional): A list of scalable compon...
b4a483e4deff71b9d63791aae0395e32de69835b
3,617,577
def get_BIC(gwr): """ Get BIC value Gaussian: p61 (2.34), Fotheringham, Brunsdon and Charlton (2002) BIC = -2log(L)+klog(n) GWGLM: BIC = dev + tr_S * log(n) """ n = gwr.n # (scalar) number of observations k = gwr.tr_S y = gwr.y mu = gwr.mu if isinstance(gwr.family, ...
a0ae8adcd584f0929aba0115e39dd3330fc2429e
3,617,578
def precmd(cmdMethod, before = None, after = None): """ Decorator to declare method to call 'pre' command method from wscript """ def decorator(func): return _hookDecorator(func, _hooks[cmdMethod].pre, before, after) return decorator
830567d6d269b6494d88c266aa896a11a98464fb
3,617,579
def create_service(): """Creates the service object for calling the Cloud Storage API.""" # Construct the service object for interacting with the Cloud Storage API - # the 'storage' service, at version 'v1'. # You can browse other available api services and versions here: # https://developers.go...
1c237c44801d40ea7fc82f99c431361461415ea5
3,617,580
import json def read_file_json(json_file_path) -> any: """ Accepts a Path object to a JSON file and read it into a dict or array structure """ if not json_file_path.exists(): raise FileNotFoundError(json_file_path, "File with path '{}' does not exist!".format( json_file_path.absolu...
e9ddaf7fcc4e4bc46034bb150a04b9a2dc661d55
3,617,581
def snmp_list(snmpstring=None, hostfilter=None, host=None): """Returns a list of SNMP information for a host or hostfilter :param snmpstring: A specific SNMP string to list :param hostfilter: Valid hostfilter or None :param host: t_hosts.id or t_hosts.f_ipaddr :return: [ [ record_id, ipaddr, hostna...
51cbf1b9088b266904be59601432398fc3ec7c4a
3,617,582
def func5(X, pth, v0, a, b, c, d): """ Function that represents the curve to fit error rates to in order to determine the threshold. (see: arXiv:quant-ph/0207088) Probabilities are fine as long as p > 1/(4*distance). See paper by Watson and Barrett (arXiv:1312.5213). Args: X: a: ...
b3664b5592ec0aba43290ac64e1098f056f03b88
3,617,583
def login(app_name='spotify'): """Start the OAuth login process. Query Parameters ---------------- complete : {yes, no}, default=yes Direct the OAuth login process to complete; must be 'no' in order to allow commandline interfaces to successfully authenticate. """ app_name = app...
650d38c076d5ce9bdd8b1077c01a33cc4c0d1c3b
3,617,584
def ACV_A7(T, Hz=50): """ Generate a growing sine wave, where the wave starts at 0 and reaches 0.9 of full amplitude at 250 cycles. Thereafter it will linearly increase to full amplitude at 500 cycles and terminate to 0 Frequency locked to 50Hz and = 0 at t>10 keyword arguments: T ...
64ef61bc2e713c08027a8efdaa50bdb922ac3400
3,617,585
def parse_output(output_file): """Parse output file for void fraction data. Args: output_file (str): path to simulation output file. Returns: results (dict): total unit cell, gravimetric, and volumetric surface areas. """ results = {} with open(output_file) as orig...
4659c2014861f8467d9c2e1b1dc69c0bbef34cda
3,617,586
def find_max_risk_player_pair(play): """ Finds the maximum risk for each player pair in the play """ play_max_risk = play.groupby(['gsisid','gsisid_partner'])[['risk_factor']].max().reset_index() max_risk_partner = pd.merge(play, play_max_risk) return max_risk_partner
d8e765d54c17bf56b48943876330ea60d7a8c1da
3,617,587
def my_mixup_cutmix(batch): """Apply mixup to half the batch, and cutmix to the other.""" batch = dict(**batch) bs = tf.shape(batch['images'])[0] // 4 mixup_ratio = batch['mixup_ratio'][:bs, None, None, None] mixup_images = (mixup_ratio * batch['images'][:bs] + (1.0 - mixup_ratio) * batch['i...
b357be0c21952627fd7f2400e93b4e31952610bb
3,617,589
def lambda_handler(event, context): """Lambda function for recursive Fibonacci""" return fibonacci(event["n"])
6de4cedafe47eea17332a3ee8f36be4ae25fe1eb
3,617,590
def unpack_allhits(res, explain=False, es_id='es_id', es_score='es_score', suffix_score='es', es_rank='es_rank'): """ Args: res (dict): raw output of the search engine explain (bool): if the results have the _explain field from the explain func of ES es_id (str): 'es_id' name of the key ...
81c98279eec329996c67195d8a3c4c2dd89d27cd
3,617,591
import time def mssql_service(docker_ip, docker_services): """Ensure that Docker service is up and responsive.""" port = docker_services.port_for("sqlserver", 1433) print("Mssql is running on port {}".format(port)) url = "http://localhost:8585" time.sleep(180) docker_services.wait_until_respon...
b0006906c10b824bdd175baff1e7633b058e965d
3,617,592
def fit(ncomp, samples): """esitmate gmm model""" # init and fit model init_prec = np.eye(2)[np.newaxis,:].repeat(ncomp, axis=0) * 4 est_model = GaussianMixture(ncomp, weights_init=np.ones(ncomp) / ncomp, precisions_init=init_prec) est_model.fit(samples) print '=...
3f06fb76cdf86c2cec154def29bcc4ab8ae7361d
3,617,593
def image_extraction_fn(data_record, min_dim): """Parses a tf.Example from the tfrecord data""" features = { 'image/encoded': tf.FixedLenFeature([], tf.string), 'image/object/class/label': tf.FixedLenFeature([], tf.int64), } sample = tf.parse_single_example(data_record, features) ...
9fc13d618a98256498bc4f4afed2d3244e023754
3,617,595
from datetime import datetime def combine_cases_t_thresh(cases, gap=datetime.timedelta(hours=12)): """Combine cases with echo gaps less than threshold.""" cc = multicase.MultiCase.by_combining(cases) grpr_orig = grouper_orig(cc) egaps = echo_gaps(cc) grouper_new = (egaps>gap).cumsum()+10000 gr...
ab9f158ef8e92a49c33bfd4af6b4722aeab57bec
3,617,596
def get_r(request): """ Prepare the reddit variable handle 'r' for use. Called mainly as a helper function by view methods proper. """ consumer_key = get_global_option('reddit-consumer-key') consumer_secret = get_global_option('reddit-consumer-secret') r = praw.Reddit(REDDIT_BOT_DESCRIPTION) # ...
afcfea870376ad3058524dcdcff9faf7563de0c1
3,617,598
def get_phase_correction_periodic(times, freq_hz): """ Calculate phase correction for the frequencies in the case of moving frequencies, or otherwise the resulting tone will rise or fall much faster due to the various frequencies being out of phase with each other. https://stackoverflow.com/questions/30...
349385c7fb4d95581c613d8ea790c08df01a04d4
3,617,599
def enum(*sequential, **named): """ Handy way to fake an enumerated type in python. Example ------- >>> Numbers = enum(ONE=1, TWO=2, THREE='three') >>> Numbers.ONE 1 >>> Numbers.TWO 2 >>> Numbers.THREE 'three' Source ------ "http://stackoverflow.com/questions/36...
3bcce013c8111fccda6e3dd08d40a0128fcdb3d8
3,617,602
def get_granted_queue_consumer_config(group_id, topic, version, cluster_type, is_pattern): """ 获取已经授权的producer记录 :param group_id: 需要授权的topic :param topic: queue队列 topic :param version 版本号 :param cluster_type 集群类型 :param is_pattern 是否为正则表示的topic :return: {list} db中对应的完整记录列表 """ if...
954b392f5b8c75b286ef771434c2d28c5df7afa8
3,617,603
def get_account_history(): """ get_account_history """ account = request.args.get('account', None) if account is None: return jsonify({}) token = request.args.get('token', None) limit = request.args.get('limit', 100) offset = request.args.get('offset', 0) hist_type = request...
5b386c8c7eb1fe5943f8a04c7b81b97f33b507d6
3,617,605
def token_view(request, token): """Show form to let user set password. """ i = get_object_or_404(Invitation, token=token) if i.is_expired(): raise Http404 if request.method == 'GET': try: user = User.objects.get(email=i.accepter) if user.is_active is True: ...
998ced088759d44974c6275861b174e147df7f9e
3,617,606
def _match_by_tag(inp, params): """Match joints by tags. Use Munkres algorithm to calculate the best match for keypoints grouping. Note: number of keypoints: K max number of a image: M L: 2 if use flip test else 1 Args: inp(tuple): tag_k (np.ndarray[KxMxL]):...
f04dcf485d2b24b8cda4395d45ff6a03337aa96b
3,617,607
def mean_(x, dimension, track_types = True, **kwargs): """Calculate the mean of a set of values. Parameters ---------- x : :obj:`xarray.DataArray` The data cube to be reduced. dimension : :obj:`str` Name of the dimension to apply the reduction function to. track_types : :obj:`bool` ...
f5c76000736139eb5ff71b54fffede14e0b62760
3,617,608
import six import yaml def UpdateThresholdRules(ref, args, req): """Add threshold rule to budget.""" messages = GetMessagesModule() client = apis.GetClientInstance('billingbudgets', 'v1beta1') budgets = client.billingAccounts_budgets get_request_type = messages.BillingbudgetsBillingAccountsBudgetsGetRequest...
9f4bde1b600719f454a66d7d0f3b400c3e4d2fbe
3,617,609
from typing import Callable import json def synonym( string: str, threshold: float = 0.5, top_n=5, cleaning=augmentation_textcleaning, **kwargs ): """ augmenting a string using synonym, https://github.com/huseinzol05/Malaya-Dataset#90k-synonym Parameters ---------- string: str...
225dbefe6fa1e39a2bf8141f2167d0c13d49f590
3,617,610
from pathlib import Path from typing import Tuple def get_path(dir_path: Path, dir_name: str = "movie", counting_format: str = "%03d", file_pattern: str = "") -> Tuple[Path, int, str, str]: """ Looks up all directories with matching dir_name and counting format in di...
4e508e52ebb7768bbdad9f849ffff55ce476ac74
3,617,611
import typing import textwrap import yaml def _update_yaml_write_lines( lines: typing.List[str], configs: typing.Dict[str, typing.Any], block: YamlBlock, parent: YamlBlock, ) -> typing.List[str]: """ Replace the specified block within the YAML file lines object with the new configs. This ...
f9e70015c2622cf09ef07b185836ec8fec237df9
3,617,612
import random def get_manufacturerid() -> str: """ Get manufacturer id from MANUFACTURER_ID list :return: id """ return MANUFACTURER_ID["manufacturer_" + str(random.randint(0, N_MANUFACTURERS - 1))]
cef941f409cbdadd168c03ea542331ebf2d7f803
3,617,613
import copy def _get_args_for_wrapping(wrapped, new_sig, func_name, doc, qualname, module_name, attrs): """ Internal method used by @wraps and create_wrapper :param wrapped: :param new_sig: :param func_name: :param doc: :param qualname: :param module_name: :param attrs: :retur...
600794f744c2afe123656f82f66fba5645590ccf
3,617,614
def build_train_op(loss): """Sets up the training Ops. Args: loss: Loss tensor, from build_loss(). Returns: train_op, global_step, learning_rate. """ global_step = tf.Variable(0, name='global_step', trainable=False) learning_rate = tf.train.exponential_decay(INIT_LEARNING_RATE, glo...
a6dff882ff455732ff9fff1756ef1407a44997af
3,617,616
def logistic_sigmoid(x, a): """Computes so-called logistic curve, a sigmoidal function used in modelling population growth etc. In this implementation, the parameter a regulates the slope or 'growth rate' of the sigmoid's rising portion. When a=0, the function collapses to the identity function y=x. ...
5984767c317cb40629097fd8941eb54d0e8c4717
3,617,619
def first_deriv_partials(dts, q, n_segments=1, n_simpson_intervals_per_segment=2, order=4): """ This method provides the Jacobian of a temporal first derivative A "segment" is defined as a portion of the quantity vector q with a constant delta t (or delta x, etc). This routine is designed to be use...
a107994d5496de3c53072ffab720be88fd269ab3
3,617,620
def zoom(scale, center, group): """zoom(scale, center, group) -> float Change the zoom and pan of a group's display. The scale argument is the new zoom factor. If the scale is given, but not the center, the zoom is set to that factor and the view is positioned so the cursor is pointing at the same place it was bef...
fe6c5cafed738d5e53a043fa86e66b22cab0a6af
3,617,622
def _border_type(player, tile, adj_tile): """ Used by map drawing routine. Checks if 'adj_tile' is connected to and can be seen from 'tile' :param text_game_maker.player.player.Player player: player object :param text_game_maker.tile.tile.Tile tile: first tile :param text_game_maker.tile.tile.T...
b8f27e11d02f134a42b1eacc45164fa9602ffddc
3,617,623
def partion(arr, start, end): """ 将元素以基准元素进行分区,基准元素左边都小于等于它,右边都大于等于他 :param arr: :param start: :param end: :return: """ key = arr[start] while start < end: while start < end and arr[end] >= key: end -= 1 swap(arr, start, end) while start < end ...
d71b568fd2d07edbdb836267040e718a6dba239f
3,617,626
def map_fbs_flows(fbs, from_fba_source, v, **kwargs): """ Identifies the mapping file and applies mapping to fbs flows :param fbs: flow-by-sector dataframe :param from_fba_source: str Source name of fba list to look for mappings :param v: dictionary, The datasource parameters :param kwargs: incl...
4995566bb1538b5c6b706850075b99d3b0563442
3,617,627
from pathlib import Path def _parse_collection_dir(directory: Path) -> list: """ Parse Ansible collection :param directory: Collection directory :return: List of parsed Ansible tasks that are prepared for scanning """ parsed_collection = [] for role in (list((directory / "roles").rglob("*"...
4238848fd6856efcbd1cd8a722567c4b11490475
3,617,628
def adda_hyperparams(lr_target=1e-5, lr_discriminator=1e-4, wd=5e-5, scheduler=False): """ Return a dictionary of hyperparameters for the ADDA algorithm. Default parameters are the best ones as found through a hyperparameter search. Arguments: ---------- lr_target: float Learning rate f...
af7cf7402485f4af4fd7c6a1a2ffb5fcd753cf93
3,617,629
import numpy def get_topic_terms(model, topicid, topn, id2token): """ Return a list of `(word_id, probability)` 2-tuples for the most probable words in topic `topicid`. Only return 2-tuples for the topn most probable words (ignore the rest). """ topic = model.state.get_lambda()[topicid] to...
b0ca1fd35fb7e8ce89a497c37bfd82b9dd884027
3,617,633
def gmv(cov): """ Returns the weights of the Global Minimum Vol portfolio given covariace matrix """ n = cov.shape[0] return msr(0, np.repeat(1, n), cov)
24b1362dad13be80e13d6caecc470907f4d685a6
3,617,634
import json def placement_rest_api(): """Perform placement optimization after validating the request and fetching policies Make a call to the call-back URL with the output of the placement request. Note: Call to Conductor for placement optimization may have redirects, so account for them """ reque...
dd850c802d86dcfa343abfded8b109b881fecde2
3,617,635