content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parse_styles(node, source): """Return the Styles represented by node.""" styles = [] for style_type, value in node.items(): if style_type == 'opacity': amount = value opacity = Opacity(amount) styles.append(opacity) elif style_type == 'fill': ...
fabc31affab80001cd5310a2c33396a74607aeee
51,474
def moveYaxis(board, way): """ Function used to move in list on y axis a.k.a. vertical axis. """ if(way == "up"): new_board = turn(sanitizey(board, "up")) for i in range(len(new_board)): for j in range(len(new_board)): if(new_board[i][j] in powers_of_two and...
6c6fddea84f6b7ecda5b5ec330dd6d2b1b4b5a77
51,475
import numpy def calculate_idf(list_books): """ IDF = ln((total_numbers of docs)/(number of docs in which the word is present)) :param list_books: list of the all the books :return: IDF of all the books """ total_documents = len(list_books) # total number of documents master_map = {} ...
294d4a437b2899c601f6269b4a6837595c73f83c
51,476
def _PreprocessComponentCond( cnxn, cond, project_ids, services, harmonized_config): """Preprocess a component= or component:name cond into component_id=IDs.""" exact = _IsEqualityOp(cond.op) component_ids = [] if project_ids: # We are searching within specific projects, so harmonized_config # holds...
a3f069bb052526981e864b4d37668817fd9c22fd
51,477
import math def attention_layer(input_tensor, attention_mask, num_attention_heads, size_per_head, query_act, key_act, value_act, attention_dropout_prob, initi...
6b895ac068291fded7a89bf5fe6ce934f0640e2d
51,478
import re def _GetAssetName(args): """Prepares asset relative path using organization and asset.""" resource_pattern = re.compile("organizations/[0-9]+/assets/[0-9]+") id_pattern = re.compile("[0-9]+") assert resource_pattern.match(args.asset) or id_pattern.match(args.asset), ( "Asset must match either ...
3963454569a63426d49ff81735cfd9243f1c4976
51,479
import math def get_antithetic_slices(shape: tp.Sequence[int], antithetic_dimension: int) \ -> tp.Tuple[slice, ...]: """ This function generates a tuple of slices to index the original array of random numbers to take either half or one less than half of the the original ...
d2668b0edbc7c45b1b586065712f5b07d1a69e2f
51,481
import unicodedata def unquote(string, charset="utf-8"): """Unquote and normalize unicode string. Params: string : string to be unquoted charset : string : optional : output encoding Returns: string : an unquoted and normalized string """ string = unquote_orig(string) ...
03f79e0a960d582541bb9ee22d25f3b5c2783c31
51,482
from typing import List from typing import Dict from typing import OrderedDict def calculate_panelist_losing_streaks(panelists: List[Dict], database_connection: mysql.connector.connect): """Retrieve panelist stats and calculate their losing streaks""" losing_streaks = []...
459cd3836116bf71825a1934b2ae0082241513e3
51,483
def find_corresponding_basins(pfaf_id_level6,gdf_level7): """ Using a pfaf_id from level 6, find all hydrobasins in level 7 that make up the hydrobasin level 6 polygon. """ pfaf_id_level7_min = pfaf_id_level6*10 pfaf_id_level7_max = pfaf_id_level7_min + 9 gdf_level7_selection = gd...
d8952abfb681fc2b1c33d53b930fff6c56f6bc0a
51,484
def downsize_storm_images( storm_image_matrix, radar_field_name, num_rows_to_keep=None, num_columns_to_keep=None): """Downsizes storm-centered radar images. :param storm_image_matrix: See doc for `_check_storm_images`. :param radar_field_name: Same. :param num_rows_to_keep: Number of ro...
fc064eb55f793dfa09071b406c601c67ee2a0442
51,485
def apply_tile_blur(tile, circle_blur): """ Blur the classification tile by radial distance from robot. (Less confident in pixels "further" away) Inputs: tile: Classification tile (nparray 3 chan RGB) circle_blur: "kernel" tile of same shape, with circular gradient (1 in center, fades...
ebd628592bd1c86c0c795b87f279c3a667d9e6ab
51,486
from .simul.ngNRC import slope_to_ramp import traceback def gen_fits(args): """ Helper function for generating FITs integrations from a slope image """ # Must call np.random.seed() for multiprocessing, otherwise # random numbers for parallel processes start in the same seed state! np.random....
f48b74d8447f57d7c4e059f7356e80dd439afb6f
51,487
def gaussian_kernel(y,sigma=7): """ gaussian_kernel: Gaussian filter. Arguments: y (numpy array): input 2D map. sigma (float) (default=7): effective length of Gaussian smoothing. -------- Returns: kerneled image. """ return gaussian_filter(y, sigma)
0eb17843b9c4545ae59e48b01528c9c25961904a
51,488
from typing import Tuple from typing import List def header(buffer: bytes, offset: int = 0) -> Tuple[bytes, str, List[int], int]: """ Unpack a Starbound header structure from the buffer at a given offset. :param buffer: buffer to read :param offset: offset in buffer :return: Starbound header ...
88e2c0392cda55941d100dbdaf26c26774f6b35f
51,490
import warnings def create_setting_analyzer_ranking( optimizer_path, mode="final", metric="valid_accuracies" ): """Reads in all settings in ``optimizer_path`` and sets up a ranking by returning an ordered list of SettingAnalyzers. Args: optimizer_path (str): The path to the optimizer to analyse. ...
c08f3aa310bfda1c77ed514d5affb5a3922231af
51,491
async def async_setup_entry(opp, entry): """Set up a smarttub config entry.""" controller = SmartTubController(opp) opp.data.setdefault(DOMAIN, {}) opp.data[DOMAIN][entry.entry_id] = { SMARTTUB_CONTROLLER: controller, } if not await controller.async_setup_entry(entry): return F...
d15d5a768b165a17382fbaf00ceb66751550f47d
51,492
def merge_dicts(idx, *args): """ Merges lists of dictionaries, by adding each other the values of corresponding dictionaries `args` can contain `None` values (except for the first one); in such case, that argument will be skipped; this is useful if a dataset contains annotations not for all the...
f51eb7a4e71d4cacacf3920189170df5f3a546a6
51,493
import torch from typing import List from typing import Optional from typing import Dict def fp_fn_eval(query_features: torch.Tensor, query_labels: torch.LongTensor, ks: List[int], gallery_features: Optional[torch.Tensor] = None, gallery_labels: Opti...
5d9ab37b7ed3d2573f8242bf44a55ae9b8522208
51,495
import urllib import csv def backupFromGoogleSheet(fileUri): """Reads google spreadsheet file from given path and make sures backup is stored for listed reposities in the given fileUri. """ cloneCount = fetchCount = failCount = 0 sheetResponse = urllib.request.urlopen(fileUri) sheetLines = [l....
54823ae00b9b6c3492668bbb9f8973b67620ecda
51,496
import csv import codecs def get_row_iterator(iterable, options=None): """Accepts an interable, options and returns a csv.DictReader object which can be used to yield CSV rows.""" options = options or {} def get_csv_quoting(options): quoting = str(options.get('quoting', "MINIMAL")).upper() ...
256606bcda86e040602c8bdbe838a3fbf78fe018
51,497
def get_content_function_ratio(content, function): """ Calculate the content-function word ratio. """ ratio = float(len(content)) / float(len(function)) if len(function) != 0 else 0 return round(ratio, 4)
e82109ed1fd2a3f3136945c4598358efdc0985e9
51,498
def AdVm(context, machine_type, zone, image): """Creates a VM definition for the AD VM. This VM only has a single boot disk because it will not be a part of the cluster. Args: context: context of the deployment. machine_type: full path of the machine type. zone: The zone where the VM will reside. ...
6f3f10aba6f4417a4c0a12cb422011c8013d249d
51,499
def calc_diarization_error(pred, label, label_delay=0): """ Calculates diarization error stats for reporting. Args: pred (ndarray): (T,C)-shaped pre-activation values label (ndarray): (T,C)-shaped labels in {0,1} label_delay: if label_delay == 5: pred: 0 1 2 3 4 | 5 6 ... 99 10...
8149d872ccf25998ae4f352cfd78504a150ad83c
51,500
def lineage_proof_for_coin_spend(coin_spend: CoinSpend) -> Program: """Take a coin solution, return a lineage proof for their child to use in spends""" coin = coin_spend.coin parent_name = coin.parent_coin_info amount = coin.amount inner_puzzle_hash = None if coin.puzzle_hash == LAUNCHER_PUZZLE...
15dd1febbec472a6a59ed72722745f67b7961d6f
51,501
import sqlalchemy.orm def literalquery(statement): """NOTE: This is entirely insecure. DO NOT execute the resulting strings.""" if isinstance(statement, sqlalchemy.orm.Query): statement = statement.statement return statement.compile( dialect=LiteralDialect(), compile_kwargs={'liter...
a0a4b63c235e790015940f6bc449b8ee1ab692f4
51,502
def filter_nb(nb): """Returns the parts of nb tagged for export and a list of question metadata.""" new_cells = [] for i, cell in enumerate(nb['cells']): if is_question_cell(cell): src = str(cell["source"]) assert len(nb['cells']) > i + 1, 'A response cell must follow questio...
111214b1f1f8e408ffea7ea9a9baceee20000e99
51,503
def status_embed(ctx, member: Member) -> Embed: """ Construct status embed for certain member. Status will have info such as member device, online status, activity, roles etc. :param ctx: context variable to get the member :param member: member to get data from :return: discord.Embed """ ...
572edc0be0326c397e25b146a9de5e1a0fd6099d
51,504
def sequentially_resolve_permutation( blocks: tf.Tensor, window: tf.Tensor, loss_fn: LossType = _mag_stft_mse_loss) -> tf.Tensor: """Resolves permutation between overlapping blocks. Args: blocks: Waveform in blocks (blocks, sources, samples) window: Window function used to obtain the blocks. ...
48305c140e8698600a8292fb880ac3f74fcb2387
51,506
async def invalid_content_length_and_chunking(request: HttpRequest) -> HttpResponse: """A response handler which sends it's body in chunks with an invalid content length""" headers = [ (b'content-type', b'text/plain'), (b'content-length', str(int(len(request.info['text']) / 2)).encode('...
f65b7f793201bacbe810ed2a8aab20b045b04f70
51,508
def linear_increasing_velocity(model_param_set, **kwargs): """ Friendly wrapper for instantiating the linear-increased-velocity medium model. """ # Setup the defaults model_config = dict(z_delta=None, min_ppw_at_freq=(6,10.0), # 6ppw at 10hz y_length=None, y_...
1000cbdff9cdf086946da5eddbe6e6a420aedf6a
51,510
from typing import OrderedDict import math def determine_fit_quality(imglist, filtered_table, catalogs_remaining, print_fit_parameters=True): """Determine the quality of the fit to the data Parameters ---------- imglist : list output of interpret_fits. Contains sourcelist tables, newly comput...
930767957621fc537d8e6bd833f0de18685fcb9e
51,511
def fetch_movies_for(category_id): """ Fetches movies for the selected category Updates the placeholder text for the Movies column :param category_id: :return: index.html """ categories = Category.query.order_by(Category.name).all() selected_category = Category.query.filter_by( c...
8c9d902d22fffa6bc2712873eb8e8041648376c6
51,512
def interp1d(x, y, target): """ return 1d linear interpolation """ return np.interp(target, x, y)
7546d37b1a083f4e5197c3717335ee5316d229d0
51,513
def get_vm_ip(vmName, poolName): """Get IP address for a VM on a NIMBUS cluster 'vmName' is required. For example, vmName='pgu-repTest-01' """ command = 'NIMBUS=%s /mts/git/bin/nimbus-ctl ip %s' % (poolName, vmName) output = run_cmd_on_pdc(command) print 'Got IP address on %s for %s: %s' % (pool...
6277668ab0b933f005753309968dd9613a36b055
51,514
def fin_diff(): """Pytest fixture for basic FiniteDifference class with centered method.""" dic = {"Grid": {"N": 10, "r_min": 0, "r_max": 10}, "Clock": {"start_time": 0, "end_time": 10, "num_steps": 100}, "Tools": {}, "PhysicsModules": {...
4697c837559dc733eefa589a7299df519b14f78a
51,515
import collections def scope_symbols(dfg): """ Returns all symbols used in scopes within the given DFG, separated into (iteration variables, symbols used in subsets). """ iteration_variables = collections.OrderedDict() subset_symbols = collections.OrderedDict() for n in dfg.nodes(): if...
49ee517f65ffa05d4a9a8f3bc927d34b9d465d74
51,516
import string def solve(moves, nr=16): """Return program order after doing all the moves. :moves: dance moves, separated by commas :nr: number of programs :returns: program order >>> solve('s1,x3/4,pe/b', nr=5) 'baedc' """ pgms = list(string.ascii_lowercase[:nr]) for move in mo...
92fed6e01bd09a60d8b9b81ac63bef7045b9ccd6
51,518
def values(): """Get the full current set of B3 values. :return: A dict containing the keys "X-B3-TraceId", "X-B3-ParentSpanId", "X-B3-SpanId", "X-B3-Sampled" and "X-B3-Flags" for the current span or subspan. NB some of the values are likely be None, but all keys will be present. """ result = {}...
2d6324a319a13b93a0fa019f8d0b7de51d6bf977
51,519
def sort_flavors(flavors): """ Sorting flavors, flavors with low resources first :param flavors: flavor list in JSON :return: sorted flavor list in JSON """ return sorted(flavors, key=compare_flavors)
98b02e72f69e7c2b764eb6707ac92ac5685ad10c
51,520
def test_decorator(f): """Decorator that does nothing""" return f
b60b815e336a3f1ca3f12712a2d1d207a5fe110c
51,522
def get_audio(file_path: str) -> mutagen.File: """Get audio object from file""" return mutagen.File(file_path)
0d32e6b95687361590990ad6bcecb177fef18771
51,523
def find_machine_id(agents, host): """ :param agents: Array of mesos agents properties (machine_id + additional infos) :type: list of dict :param host: Host to find. Can be ip, hostname of agent ID :type: string :returns: a machine_id :rtype: dict """ for agent in agents: # d...
706bb16d02aec1fe6844f3ed49b13e6fe54a08a6
51,524
def get_connection_string(include_password=True): """ Return the connection string based on the configuration specified in the `merlin.yaml` config file. """ broker = CONFIG.broker.name config_path = CONFIG.celery.certs if broker not in BROKERS: raise ValueError(f"Error: {broker} is...
6b97a1cf84447c6dcf503c190d80ea331e3c13f0
51,526
from typing import Dict def _create_Particles_dict() -> Dict[str, dict]: """ Create a dictionary of dictionaries that contains physical information for particles and antiparticles that are not elements or ions. The keys of the top-level dictionary are the standard particle symbols. The values...
5f737b79ac18d4332be1b88d948aa1212c8d595d
51,528
def load_from_secretsmanager(environment=None): """ Load the secrets into a dictionary, skip if no environment available """ if environment is None: try: environment = environ["MICROCOSM_ENVIRONMENT"] except KeyError: # noop return load_from_dict(dict...
9880d7478d44d0794e86cd8ce235d544edfc08b0
51,529
def _dfs_out(atom): """Traverse an Atom's outgoing neighborhood iteratively with a depth-first search.""" atoms = [atom] stack = list(atom.out) while stack: atom = stack.pop(0) atoms.append(atom) stack[0:0] = atom.out return atoms
099258d3d9a51782cacf274e6a3dea6dcd5e6464
51,530
def _read_csv_with_fallback_encoding(filepath, dtypes=None): """read a CSV to a pandas DataFrame using default utf-8 encoding, but try alternate Windows-compatible cp1252 if unicode fails """ try: logger.info('Reading CSV file %s' % filepath) df = pd.read_csv(filepath, comment='#', dty...
1e09a47b90b9e2a3cd0466eb6cf56d00e4824c43
51,531
def cnn_model(features, labels, mode): """CNN model function. Arguments: features -- Batch features from input function labels -- Batch labels from input function mode -- train, eval, predict, instance of tf.estimator.Modekeys Returns: The estimator spec depending on the chosen mode """ ...
a16bc923075bc957cc64adbef435fe0b58e0bc07
51,532
def create_classification_dataset(n_samples, n_features, n_informative, n_redundant, n_repeated, n_clusters_per_class, weights, n_classes, random_state=None): """ Creates a binary classifier dataset :param n_samples: number of observations :param n_features: number of ...
f245fa4dda1c3f73840b7c01cd932d4779a547d5
51,533
def median(data, interval=34): """Calculate the median and ``interval`` size quartile uncertainties. Parameters ---------- data: numpy.nparray Needs to be an 1D array. interval: int The percentile (to one side) you want for uncertainties. Returns ------- numpy.nparray...
0019e7b1671c5be451fddbaa8556039faba889ac
51,534
def npgettext(context, singular, plural, num, **variables): """Translates `singular` and `plural` and returns the appropriate string based on `number` and `context`. """ return _translate('npgettext', context, singular, plural, num, **variables)
95cbb18ddb253104a82616bcf8765f5bf748e0b5
51,535
def load_data(in_path, out_path, in_vocab, out_vocab, max_input_len=56, max_output_len=66): """Loads the data from the given path and preprocesses the data by converting the tokens into ID's using the vocab dictionary. Additionally, token...
5a9d842ed654f6b20409306d874213e7c0d81a18
51,536
def is_compatible(subreddit, index_type, status): """ Checks if the submission exists and belongs to the required type of subreddit """ if status == 'Exists': if index_type == 'AV': keys = list(subreddits[index_type].keys()) for key in keys: if s...
11ce4f3af63a5610f857e8da104ebbb5a9ae3844
51,537
def makePoint(x, y): """ create a point or a dict """ if type(x) == float: return Point(x, y) else: return { 'x': x, 'y': y }
72e3af9e307c9f8f45fa5ab0317748a7181143a3
51,538
def convert_confusion_matrix_to_MCM(conf_matrix): """ Converts a confusion matrix into the MCM format for precision/recall/fscore/ support computation by sklearn. The format is as specified by sklearn below: In multilabel confusion matrix :math:`MCM`, the count of true negatives is :math:`MCM_{:,0,0...
78017974a3d99c506f93e0767df0042bce1d3e91
51,540
def setup(hass, config): """Setup the Hello State component. """ _LOGGER.info("The 'hello state' component is ready!") # Get the text from the configuration. Use DEFAULT_TEXT if no name is provided. text = config[DOMAIN].get(CONF_TEXT, DEFAULT_TEXT) # States are in the format DOMAIN.OBJECT_ID ...
5ddc9259ad752a04ca9ed443bc99d810fa28a001
51,541
def render_report(jobs_with_error): """Build a text report for the jobs with errors """ output = [] for job in jobs_with_error: errors_count = job.info.get('errors_count', 0) close_reason = job.info.get('close_reason') job_id = job.info["id"].split('/') url = 'https://ap...
42c0ef405b3b684830433aa5ddd38d4283c7472c
51,542
def in_range(target, bounds): """ Check whether target integer x lies within the closed interval [a,b] where bounds (a,b) are given as a tuple of integers. Returns boolean value of the expression a <= x <= b """ lower, upper = bounds return lower <= target <= upper
ac9dee9092388d150611ab5e1a4a800b72cf8f83
51,543
def score_sent(text, sent_data, normalize=False): """ Evaluate the data """ test_sent = next(iter(sent_data.values())) sents = np.zeros_like(test_sent).astype(np.float).reshape(-1) tokens = word_tokenize(text.lower()) for token in tokens: try: sent = np.array(sent_data[t...
c1c85685a2b9231e58a11e3db9e3d96200726eff
51,545
def is_master_process(rank=0): """Check if master process or not..""" if not dist.is_initialized(): return True if rank == dist.get_rank(): return True return False
077423bd97175ce271a5edd2e5734e47ed5de4a1
51,546
import zmq import gc import time def test_zmq_with_poller(count): """single thread zmq with poller""" print(".", end="", flush=True) ctx = zmq.Context() router = ctx.socket(zmq.ROUTER) router.bind("tcp://127.0.0.1:*") address = router.getsockopt(zmq.LAST_ENDPOINT).rstrip(b"\0") dealer = ct...
b6ac176b684d306b8e33480ecdd1cf3f17b1a1be
51,547
def _parse_path_segment(acc, segment): """ Parse a single path segment. If the segment is an identifier or wildcard, it's constraint is also derived. :param _ParsedRoutePath acc: Accumulated parse result. :param unicode segment: Path segment. :rtype: _ParsedRoutePath """ match = _t...
03d7d53a9bee78df083b1bc077366f0403699947
51,548
def valid_chrom(): """ Valid chromosomes should be 1 - 22, X, Y, and MT. Validity is not checked or enforced """ return '1'
050baa71f61eaa1f8160953aacfe3f1cd0193899
51,549
def annotateTree(bT, fn): """ annotate a tree in an external array using the given function """ l = [None]*bT.traversalID.midEnd def fn2(bT): l[bT.traversalID.mid] = fn(bT) if bT.internal: fn2(bT.left) fn2(bT.right) fn2(bT) return l
c254a1258e0bc4b0bbbe17c9a2830b955f6a7a55
51,550
import scipy def plotRadiants(pickle_trajs, plot_type='geocentric', ra_cent=None, dec_cent=None, radius=1, plt_handle=None, label=None, plot_stddev=True, **kwargs): """ Plots geocentric radiants of the given pickle files. Arguments: pickle_trajs: [list] A list of trajectory objects loaded from ...
bbbccf1ff5c68fbaf39aff39929ab83762d223c4
51,551
def read_o01(fn): """Read a formatted output file of the ENVIRO program and extract the electric and magnetic fields across the model's transect, returning them in a DataFrame args: fn - str, path to the target file, must have a ".o01" extension returns: df - DataFrame of fields across the t...
470a83064f56abb5d295782f55a1fd0bce60dc00
51,552
def median_squared_percentage_error( y_true, y_pred, horizon_weight=None, multioutput="uniform_average", square_root=False, symmetric=True, **kwargs, ): """Median squared percentage error (MdSPE) or square root version. If `square_root` is False then calculates MdSPE and if `square...
a9e12d9ae34e5d7fb08512e840b581290b436ef0
51,553
import traceback def error_response(ex): """ Handles any errors raised in the execution of the backend Builds a JSON representation of the error messages, to be handled by the client Complies with the Swagger definnition of an error response """ if 'code' in ex: code = ex.code elif...
ed6a492e34a3cd6b00b6e751ccfa58152922a993
51,554
def simulate_from_psd(S_func, m=2000, dt=1, ymean=0, sigma=0.2, size=1, seed=None, **args): """ Simulate light curve given input times, model PSD, and ymean S_func: model PSD function S(omega) [note omega = 2 pi f] m: number of bins [output will have length 2(m - 1)] dt: equal spacing in time ...
c4118d1e31e3f9b70a8518576a161b4fa18c3277
51,555
def eta_error_no_initial(ratio, k1, k2, k3, p1, p2, p3, sratio, sp1, sp2, sp3): """ :param ratio: :param k1: :param k2: :param k3: :param p1: :param p2: :param p3: :param sratio: :param sp1: :param sp2: :param sp3: :return: """ aux0 = ((((-((1. +ratio) ** -2....
f360c462be605c83f797905036e1dc153919efef
51,556
def beta_gen_lasso(p): """ Generate the linear model coefficient in constrained lasso case. @param p int: dimension. @return np.array(p,1): the coefficient. """ cardi = 0.005 return np.array([0]*int(p-int(cardi*p)) + [1]*int(cardi*p))
7618a84bc983596aa17749f56cb79be895281597
51,557
from typing import Optional from typing import Dict import logging def extract_bibliographic_data(node: ET.Element) -> Optional[Dict]: """ Find bibliographic data like title, authors and editors """ data = dict() title = node.find(f"{TEI}titleStmt") if not title is None: extract_title(...
44b9418da114243ab4767fe388b115bf4f29d885
51,558
from typing import Optional def whiten( strain, dt, phase_shift=0, time_shift=0, interp_psd: Optional[np.ndarray] = None, psd: Optional[np.ndarray] = None, ): """Whitens strain data given the psd and sample rate, also applying a phase shift and time shift. Args: strain (nd...
6da702f6f849466a8ef30bddb8fef8007b99854c
51,559
def separator(node, label=None): """Create a visual separator for the channel box using a dummy attribute. This create a maya enum attribute at the last position of the channel box. The name section will be left empty, and the enum section will be filled with the value specified in the ``label`` param...
91459855e98580873a6b743bfdd0f32f9c1934b1
51,560
from typing import Tuple from typing import Optional def find_operating_point( x: np.ndarray, y: np.ndarray, z: np.ndarray, required_x: float ) -> Tuple[float, Optional[float], Optional[float]]: """ Find the highest y (and corresponding z) with x at least `required_x`. Returns ------- x, y, z...
be1489ea8cfa85d0c0a15c0a355fae5c3eac4b0c
51,561
import json import requests def save_request(url, output_file): """ Attempts to read from file. If there's no file, then it will save the contents of a url in json/html """ # check for cached version try: with open(output_file) as fp: data = fp.read() try: ...
79d20b101b0fe811ef9129a701c6f5487e2c8a84
51,562
def load_dependency_files(path): """ Recursively (if necessary) gather all the manifests referenced by the starting_path and return as list :param starting_path: :return: """ f = load_dependency_file(path) files = [f] # recursively call if f.dparser: for file in f.dparser.re...
9af8fde21a65b5ce7e0288abcd8d2fd41d3a9a45
51,563
def accuracy(pred, target, topk): """accuracy = top-k correct""" correct_k = topk_correct(pred, target, topk) accuracy_list = [(x / pred.size(0)) * 100.0 for x in correct_k] return accuracy_list
258b42c760552952adff3a9b7b197badc717d0cf
51,564
import doctest def load_tests(loader, tests, ignore): """Run doctests and file-based doctests.""" tests.addTests(doctest.DocTestSuite(server)) return tests
cf2fbb713885393167782dce783b4292044107ca
51,565
def get_avg_heart_rate(envelope=None, sampling_rate=1000.): """Compute average heart rate from the signal's homomorphic envelope. Follows the approach described by Schmidt et al. [Schimdt10]_, with code adapted from David Springer [Springer16]_. Parameters ---------- envelope : ar...
8f007908c40170835b4963f0ee6aea7f9343990c
51,566
from random import random def busqueda_local(solucion_inicial, evaluacion, obtener_vecinos, T_max, T_min, reduccion): """ Simulated Annealing. """ solucion_mejor = solucion_actual = solucion_inicial evaluacion_mejor = evaluacion_actual = evaluacion(solucion_actual) sol...
f21a03657161d75ca513b6f0f56cc3d9a0c5f27b
51,567
from typing import Dict from typing import Any def _get_aggregate_funcs( df: DataFrame, aggregates: Dict[str, Dict[str, Any]], ) -> Dict[str, NamedAgg]: """ Converts a set of aggregate config objects into functions that pandas can use as aggregators. Currently only numpy aggregators are supported....
5f3730c4be4c285154096a943b6b2c68b3c05305
51,568
from scipy.spatial.distance import pdist, squareform from typing import Optional def distance_weights( X: "npt.ArrayLike", y: "npt.ArrayLike", grouping: "Optional[npt.ArrayLike]" = None, ) -> np.ndarray: """ Compute weights based on Manhattan distance of the X-values. This function ignores inform...
0c581b3674466963603748c7c28fa66c9d83e431
51,569
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
4c0361cf8e63d7608b4213ddd8f8a4c498282dcf
51,570
from typing import Callable from typing import Tuple def plot_2d(*plotters: Callable) -> Tuple: """Plot multiple spatial objects in 2D.""" fig, ax = plt.subplots() for plotter in plotters: plotter(ax) return fig, ax
7eb169f19ba83e5ebb9d98e9ead7ef3cd0041af0
51,571
import torch def cosine_sim(x1, x2, dim=1, eps=1e-8): """Returns cosine similarity between x1 and x2, computed along dim.""" x1 = torch.tensor(x1) x2 = torch.tensor(x2) w12 = torch.sum(x1 * x2, dim) w1 = torch.norm(x1, 2, dim) w2 = torch.norm(x2, 2, dim) return (w12 / (w1 * w2).clamp(min=...
a4992b3f3a4a483c96a5b18bbc3402df70a8b44d
51,572
def cut_descendants(D, nodes, page_tree): """Given the distance matrix D, a set of nodes and a PageTree perform a multicut of the complete graph of nodes separating the nodes that are descendant/ascendants of each other according to the PageTree""" index = {node: i for i, node in enumerate(nodes)} ...
4cbf96bfde518fcd8d4f76fd0a002bf672568140
51,574
import math def rotate_around_point(xy, radians, origin=(0, 0)): """Rotate a point around a given point. I call this the "high performance" version since we're caching some values that are needed >1 time. It's less readable than the previous function but it's faster. """ x, y = xy off...
f4d2c5639b8ac8378ad1f7dafeaa6563350fe92a
51,575
def create_ensemble(datasets, mf_flag=False): """Create an xarray datset of ensemble of climate simulation from a list of netcdf files. Input data is concatenated along a newly created data dimension ('realization') Returns a xarray dataset object containing input data from the list of netcdf files concate...
45ae20e7d3dffc5b67efd99df2432baa57c89dcb
51,577
def isabs(s): """Test whether a path is absolute. """ return s.startswith('/')
c8d33faabd7a1ec0d5fc4902e2d271057037111c
51,578
import psutil def check_memory(): """Return True when less than 0.5gb RAM available""" mu = psutil.virtual_memory() # memory in GB GB_mem_free = mu.available/(2**30) stats["check_memory_wrap"] = (f"\n Total RAM available(in GB): {mu.total/(2**30):.2f}\n\ Available RAM(in GB): {GB_mem_free:.2f}") if GB...
2fc3703cfe62c61d4b556b959466a4f16d560bbb
51,580
def read_csv(fname, log = True, since_midnight = True): """Generates a single Peak instance from a file or list of files Arguments --------- fname: string or list of strings log: bool. If the actual or the log of the amplitude is given. If log is True the value in the file will be 10**amp ...
75ea31a66154e57e194290780a4f1512b9c86af2
51,581
def aer2geodetic(az, el, srange, lat0, lon0, h0, ell=None, deg=True): # type: (float, float, float, float, float, float, Ellipsoid, bool) -> tuple """ gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parameters ---------- az : float azimut...
c84d331a50aaaaca795e8814b79a540926f18d0b
51,582
async def play_game_human(client, player_id, realtime, game_time_limit): """Allow humans to play""" while True: state = await client.observation() if client.game_result: return client.game_result[player_id] if game_time_limit and (state.observation.observation.game_loop * 0.7...
1428a097f3c90fb07cce9c1865d351b90572912b
51,583
import binascii def random_secret_exponent(curve_order): """ Generates a random secret exponent. """ random_256bit_hex_string = binascii.hexlify(get_entropy(32)) random_256bit_int = int(random_256bit_hex_string, 16) int_secret_exponent = fit_number_in_range(random_256bit_int, 1, curve_order) retu...
42f95df6164647d6bdc376e91debba9bc5a2812f
51,584
def astype(value, types=None): """Return argument as one of types if possible.""" if value[0] in '\'"': return value[1:-1] if types is None: types = int, float, str for typ in types: try: return typ(value) except (ValueError, TypeError, UnicodeEncodeError): ...
47d066d9d4bb5b0b96216cc722c6896d6fdcf1a4
51,586
from functools import reduce import operator def adjlist_to_metis(adjlist, nodew=None, nodesz=None): """ Rudimentary adjacency list converter. Primarily of use if you don't have or don't want to use NetworkX. :param adjlist: A list of tuples. Each list element represents a node or vertex in the...
1b4854904ce40f2d03e76db78763639044bc167a
51,587
def _minmax(*args): """ Return the min and max of the input arguments """ min_ = min(*args) max_ = max(*args) return(min_, max_)
9985ebbffd3ee0b03dc751a3c90db00e922ab489
51,588
def find_variable(text, start): """ Return `(name, var_start, var_end)` or None. The variable may be of two forms: `$XYZ` or `{$XYZ}`. The latter is to be used when otherwise the variable name would be followed by a name character, which would make it ambiguous. """ result = None i = text....
35f8d0a1ead0abb54746399321e406fcb9d67b0b
51,589