content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parse(address): """Parses an address into its components""" for _, addresser in ADDRESSERS.items(): result = addresser.parse(address=address) if result: return result raise ValueError("parse error, no addresser found for address {}".format(address))
0ee6ca4c14727e9e29da4afe4cd7d4aa9c737e64
3,617,500
def create_app(object_name): """ An flask application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ Arguments: object_name: the python path of the config object, e.g. gordon_cole_gen.settings.ProdConfig """ app = Flask(__name__) ...
5e8c02b4846a22431796e7f197e8cd4752e2a039
3,617,501
def num_added_features(include_am, include_lm): """ Determine the number of added word-level features (specifically AM and LM) """ added_feature_count = 0 if include_am: added_feature_count += 1 if include_lm: added_feature_count += 1 return added_feature_count
83f344ad693f846f7a6dda0bcef429565d96870b
3,617,502
from typing import Union import torch from typing import Set from typing import List from typing import Dict import operator def split_const_subgraphs( module: Union[torch.nn.Module, torch.fx.GraphModule] ) -> FoldedGraphModule: """ Looks through `module` for any nodes that have all constant attribute inp...
6a4e88df5319e66b27ba83be8e346495c4f2d242
3,617,503
import re def validate_CNPJ(value): """ Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a group of 14 characters. :type value: object """ value = str(value) if value in EMPTY_VALUES: return u'' if not value.isdigit(): value = re.sub("[-/\.]", "", value)...
5ee18981bbaba30bdf68cbe63658a27a23a3a284
3,617,504
def _get_mudata_autodetect_options_and_encoding_modes( identifier: str, autodetect: dict, encodings: dict[str, dict[str, list[str]]] ) -> tuple[bool, dict | None]: """ Extract the index column (if any) and the columns, for obs only (if any) from the given user input. This function is only called when d...
1b763bba23957e71897bc40acaf020088f75feb3
3,617,505
import os def load_model(path, run_id=None): """ Load an H2O model from a local file (if ``run_id`` is ``None``) or a run. This function expects there is an H2O instance initialised with ``h2o.init``. :param path: Local filesystem path or run-relative artifact path to the model saved ...
bfea8ed8e0b079d7c0eb0c3383dd9fe4fc017346
3,617,506
def multishells(): """Resolve the path of the "rst_operators/multishells.rst" result file.""" return resolve_test_file("model_with_ns.rst", "", "multishells_rst")
470cb8874712493f6e33723723d77235bcdb5529
3,617,507
from .prompts import ( prompt_str, prompt_int, prompt_float, prompt_bool, prompt_datetime, prompt_enum, ) from typing import Type from typing import Dict from re import T from datetime import datetime from enum import Enum def _get_validator( cls: Type, attr_nam...
ae093e35030afac4574fb3ce2081bcaf96df3ad3
3,617,508
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
import os def go_term_dict(): """Parses the Gene Ontology file and returns GO lookup dictionary, version, and date. The go.obo.gz file is included in the GFFtk package, it can be updated in site-packages/gfftk/data/go.obo.gz Returns ------- go : dict of dict dictionary of go_term: { "nam...
b4308e9d3c214edc854eed2849d3d15c993f56d1
3,617,515
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
import sys def parse_cmdline(args): """ Parses command line arguments and returns query and request_options """ if not args: show_usage() sys.exit(0) query_string = " ".join(args) parsed = urlparse.urlparse("https://srv:0/%s" % query_string) request_options = options....
8b19fe0f3ce26da2a6919d638c25bfe16b961269
3,617,517
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
import uuid import os def recipe_image_file_path(instance, file_name): """ generate file path for new recipe image """ extension = file_name.split('.')[-1] # return tthe last item after spliting file_name = f'{uuid.uuid4()}.{extension}' return os.path.join('uploads/recipe/',file_name)
9bc1626d432b0137caf921dfdf2d5d98537b3665
3,617,519
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
import os def touch(filename, mtime): """ doc me """ with open(filename, 'a+'): pass os.utime(filename, (mtime, mtime)) return 0
aaa272ba33ff25b2e83cfa7aa308cc115bd8fb6a
3,617,534
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
import json import typing import urllib import functools async def create_server(conf: json.Data, adapters: typing.Dict[str, common.Adapter], views: hat.gui.view.ViewManager ) -> 'Server': """Create server""" addr = urllib.parse.urlparse(...
48d5e5baf37ff9b559ab0d08d27660bf84ea51ce
3,617,536
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
import json import torch from typing import Generator import os def init_training(args): """Initialize networks, optimizers and the data pipeline.""" # create dataset dataset = { 'cats': Catfaces64Dataset.create_from_scratch, 'flowers': Flowers64Dataset.create_from_scratch }[args.datas...
e0fce4ba6be82a6785af681ecb3f0f24c0a9e15b
3,617,541
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
import os def find_endpoint(method, handler, parameters, url_parameters, ids_parameters, dir_to_list, endpoint): """Find the route from endpoint and call the correct method when found""" if not endpoint: return do_method(method, handler, parameters, url_parameters, ids_parameters, dir_to_list, ".all")...
61e494220538cdc482c2a5eea6843cbd0ce49366
3,617,548
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
import configparser import os import sys def read_config(config_file): """Read configuration file infomation :config_file: Configuration file :type config_file: string """ cfg = configparser.ConfigParser() try: cur_dir = os.path.dirname(os.path.abspath(__file__)) if os.sep...
3c8fffbad9eb95e59b4cceda01824f726440b1c4
3,617,559
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 torch.onnx import unregister_custom_op_symbolic as _unregister_custom_op_symbolic import torch.onnx.symbolic_registry as sym_registry from torch.onnx.symbolic_helper import _onnx_main_opset, _onnx_stable_opsets from torch.onnx.utils import get_ns_op_name_from_custom_op def unregister_custom_op_onnx_export(opname...
c20945ec8dc84e08a625eed63ab9bf9451a18d48
3,617,569
import json import os def lambda_handler(event, context): """lambda entry""" LOGGER.info(f'REQUEST RECEIVED: {json.dumps(event, default=str)}') # get current account execution_account_id = context.invoked_function_arn.split(':')[4] # check if lambda call by AWS CloudWatch Event in response to cr...
75c6cf39f0ce8cdaaae61995690e231256a6d34d
3,617,570
from typing import List from typing import Union def draw_fancy_table( data: List[List[Union[Number, str]]], rows: bool = True, lines: str = "│─", corners: str = "┌┐┘└", crossings: str = "┼├┤┬┴", align: str = "<", ) -> List[str]: """ TODO (2021-01-18): Add documentation """ if ...
00c65b78fbc5f58198eb212f108cce3d53525e3e
3,617,571
import os def joinPath(path: str, cwd: str = os.getcwd()): """ Helper function to make using os.path.join(os.gecwd()) a lot easier Ex: joinPath(["modules", "modules.py"]) joinPath("modules/modules.py") Returns: a string path """ if type(path) != list: path = path.split("/")...
5fb1557ac6189d1a8cda50cca58fb691701add22
3,617,572
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 replace_import_names( source_store, from_to_dict, target_store=None, dryrun=True, verbose=True, replacer_factory=mk_import_root_replacer, add_comment_at_the_end_of_lines_replaced=False, ): """Replace import names. Use case: You've renamed something or moved some modules (remembe...
3067ea71a87579f69209a2db268cf65ea103c7c6
3,617,588
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
import os import time import tarfile import tqdm def load(path=None, n_processes=6): """10-class image classification form imagenet Imagenette is a subset of 10 easily classified classes from Imagenet (tench, English springer, cassette player, chain saw, church, French horn, garbage truck, gas pump, g...
31abc1839dab9bb5930f7bf368d1b101d5b7a147
3,617,594
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
from typing import Optional from typing import Sequence import logging import os import contextlib import time import functools def train_and_evaluate_pmap(model_p: InstantiableParams, train_input_p: InstantiableParams, job_log_dir: Optional[str], ...
31fef13ffc74b0822789645dd35d690ffa88cff1
3,617,597
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