content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _hist2d_add(list_results: list): """ Quick helper function that we can submit to dask cluster to sum the results of running hist2d_numba_seq on multiple chunks of data. Parameters ---------- list_results list, list of numpy ndarray histograms that we want to sum to get global result...
e00efe2716e83b26354c0f6ca3c339a470921592
3,625,455
def dwnld_worker(qtbot, mocker, workdir): """A fixture for the WeatherDataGapfiller.""" dwnld_worker = RawDataDownloader() return dwnld_worker
c3f0d6b57d8a39c7e90e202106a6708d662f1031
3,625,456
import re def camel_case_to_title_case(camel_case_string): """ Turn Camel Case string into Title Case string in which first characters of all the words are capitalized. :param camel_case_string: Camel Case string :return: Title Case string """ if not isinstance(camel_case_string, str): ...
bcc40753a8672355519741f5aec64c262431d582
3,625,457
def add_subplot_axes(ax, rect): """ Plotting utility """ fig = plt.gcf() box = ax.get_position() width = box.width height = box.height inax_position = ax.transAxes.transform(rect[0:2]) transFigure = fig.transFigure.inverted() infig_position = transFigure.transform(inax_position) ...
c91126c81e1608e35ef3a7aa48ae9ea9da4ea684
3,625,458
def starfind(data, snr, background, noise, fwhm, mask=None, box_size=35, sharp_limit=(0.2, 1.0), round_limit=(-1.0, 1.0), logger=logger): """Find stars using daofind AND sexfind.""" # First, we identify the sources with sepfind (fwhm independent) sources = sepfind(data, snr, backgr...
1f9792f75a9a0d877993260118d7ca95480a85ba
3,625,459
import torch def displace(a, delta): """ fns = { -1: lambda x: -x, 0: lambda x: 1 - np.abs(x), 1: lambda x: x, }""" delta_x, delta_y = delta[:, :, :, 0], delta[:, :, :, 1] delta_x = delta_x.unsqueeze(3) delta_y = delta_y.unsqueeze(3) # BatchSize x Height X Width x 3 x_multipliers = torch.relu(torch.cat(...
cf8819193d331c7edcb1a90989bf0fb2e3896370
3,625,460
def inferType(fname): """Return the type of the given X5 file - either ``'linear'`` or ``'nonlinear'``. :arg fname: Name of a X5 file :returns: ``'linear'`` or ``'nonlinear'`` """ with h5py.File(fname, 'r') as f: ftype = f.attrs.get('Type') if ftype not in ('linear', 'nonlin...
7be135f126dc20da70c6fb0f9e2d5f2f5ebc0a1c
3,625,461
def pmr_corr(vlos, r, d): """ Correction on radial proper motion due to apparent contraction/expansion of the cluster. Parameters ---------- vlos : float Line of sight velocity, in km/s. r : array_like, float Projected radius, in degrees. d : float Cluster distan...
c9136c5ae33e89d6f57b936b92c23001fd30ccfa
3,625,462
def get_min_corner(sparse_voxel): """ Voxel should either be a schematic, a list of ((x, y, z), (block_id, ?)) objects or a list of coordinates. Returns the minimum corner of the bounding box around the voxel. """ if len(sparse_voxel) == 0: return [0, 0, 0] # A schematic if len(...
371b25b795a1a2ffeb0fc3724f01f1a329f917ae
3,625,463
def ExtractListsFromVertices(vertexProp, g): """ Method to extract the lists at each vertex of a vertex property, vertexProp, belonging to a graph, g, and to return a list of lists, where each sub-list is a list of values from each vertex :param vertexProp: :param g: :return: ...
fd10e9285f9382511a526468e41e8a516a6f50bd
3,625,464
def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc.) The JSON body of the request is provided in the event parameter. """ print("event.session.application.applicationId=" + event['session']['application']['applicationId']) "...
651532a7337322171f8fcf8874048a5b840505cf
3,625,465
def _traverse_dirtable(rsrc, off, rtype): """Recursively traverse the dirtable, returning all data entries under the given type id.""" # resource directory header resdir = _IMAGE_RESOURCE_DIRECTORY.from_bytes(rsrc, off) number = resdir.NumberOfNamedEntries + resdir.NumberOfIdEntries # followed by re...
51de90b056fae726faea0732f3fcd09ba8ec1db8
3,625,467
def i18n_enabled(): """ Return the projects i18n setting """ return getattr(settings, "USE_I18N", False)
35931fcfc6fbfd19508024c8fa3405d82bd59dfb
3,625,468
def delete(request, testplan_id, rule_id): """ Delete test plan based on testplan_id. """ dbc = db_model.connect() try: testplan = dbc.testplan.find_one({"_id": ObjectId(testplan_id)}) except InvalidId: return HttpResponseNotFound("testplan '%s' not found" % testplan_id) if t...
473d87f8ea5f586e8e1c6803d3bc10bdcb3e5f49
3,625,470
def _third_order(B3, Y_res, C3, R, n3, m3, lambdax): """Compute third order sensitivities.""" Y_ijk = np.zeros((R, n3)) # Initialize 1st order contributions T3 = np.zeros((m3, R, n3)) # Initialize T(emporary) matrix - 1st # First order individual estimation for j in range(n3): # Re...
ebc33133cdb8fa5006c47621b1f867230cc9d73d
3,625,471
from typing import Optional def _query_statistics( total_queries_name: str = TOTAL_QUERIES_NAME, total_documents_name: str = TOTAL_DOCUMENTS_NAME, min_documents_name: str = MIN_DOCUMENTS_NAME, max_documents_name: str = MAX_DOCUMENTS_NAME, eval_config: Optional[config_pb2.EvalConfig] = None, mo...
4472dd35220a2788005f366b46a5275dcc3b207d
3,625,473
def get_scrapyd(client): """ get scrapyd of client :param client: client :return: scrapyd """ if not client.auth: return ScrapydAPI(scrapyd_url(client.ip, client.port)) return ScrapydAPI(scrapyd_url(client.ip, client.port), auth=(client.username, client.password))
40c0fd8afb4b499aaf05264f66d0a6558109f5c2
3,625,474
def byteListToU32leList(data): """Convert a list of bytes to a list of 32-bit integers (little endian)""" res = [] for i in range(len(data) / 4): res.append(data[i * 4 + 0] | data[i * 4 + 1] << 8 | data[i * 4 + 2] << 16 | data[i * 4 + 3] << 24...
a06cdb918070837728c5f6100ca237bab4a4773f
3,625,475
def normalize_fr(fr): """Normalize an input flavor combination to a flavor ratio. Parameters ---------- fr : list, length = 3 flavor combination Returns ---------- numpy ndarray flavor ratio Examples ---------- >>> from fr import normalize_fr >>> print(normalize_fr...
b290c0e03b862306d995c5426b833d701b4093d1
3,625,477
def max_row_by_row(arrays,NaN=False): """Perform row by row min""" if NaN: rowmax=[max_w_nan(arr) for arr in arrays] else: rowmax=[max(arr) for arr in arrays] return rowmax
5897efc74f473d1d2d40f8479df11ce0f08c607d
3,625,479
def is_palindrome_letters_only(str): """ Confirm Palindrome, even when string contains non-alphabet letters and ignore capitalization. casefold() method, which was introduced in Python 3.3, could be used instead of this older method, which converts to lower(). """ i = 0 j = hi = len(str) - ...
5f95add0ecf3fbe31af2b9cd0e27aac36b2c3985
3,625,481
def extract_std_bandwidth(spectrogram, doppler_bins, render = False, render_time = None, idstr = None): """ Extracts the mean time between peaks in the spectrogram. """ spectrogram, doppler_bins = clean_spectrogram(spectrogram, doppler_bins) bandwidth = get_bandwidth(spectrogram, doppler_bins) std_b...
1a0c83786825fb54e6c3c285becdd6adbf9e29a8
3,625,482
import json def Schedule(name, config, scheduled_by, executor_requirements, priority=0): """Adds a new Task with given name, config, user and requirements.""" webhook = json.loads(config)['task'].get('webhook', None) task = Task(parent=MakeParentKey(), name=name, config=config, ...
73924c5a590a4b9791673f16f52a0a19f03c743f
3,625,483
import time import logging def createResponseBody(lines, context, client, lang='en'): """Parse the **lines** from an incoming email request and determine how to respond. :param list lines: The list of lines from the original request sent by the client. :type context: class:`bridgedb.email.ser...
663bdf2b90a471b4b65db26de7d8165f6a6ec2f0
3,625,484
from typing import Any def validate_delta(delta: Any) -> float: """Make sure that delta is in a reasonable range Args: delta (Any): Delta hyperparameter Raises: ValueError: Delta must be in [0,1]. Returns: float: delta """ if (delta > 1) | (delta < 0): raise ...
1fd3084c047724a14df753e792b8500a103a34c0
3,625,485
def deparagraph(element: Element, doc: Doc) -> Element: """Panflute filter function that converts content wrapped in a Para to Plain. Use this filter with pandoc as:: pandoc [..] --filter=lander-deparagraph Only lone paragraphs are affected. Para elements with siblings (like a second Para...
aff8bdb03baa8427f4026c22a125d286a1fb323b
3,625,486
def get_residual_loss(query_images, encoded_images, params): """Gets residual loss between query and encoded images. Args: query_images: tensor, query image input for predictions. encoded_images: tensor, image from generator from encoder's logits. params: dict, user passed parameters. ...
2d3614a6f1b0d99f7b7a8907d0a90d1b1ce69cbc
3,625,488
def directed_connected_components(digr): """ Returns a list of strongly connected components in a directed graph using Kosaraju's two pass algorithm """ if not digr.DIRECTED: raise Exception("%s is not a directed graph" % digr) finishing_times = DFS_loop(digr.get_transpose()) # use finishing...
4e0b69aa6d7feeccafc94354210568c21ecbc775
3,625,489
from typing import Any async def leave_group_by_id(id: str, number: str) -> Any: """ leave a group by id """ cmd = ["-u", quote(number), "quitGroup", "-g", quote(id)] await run_signal_cli_command(cmd) return id
c0fc42a00a67e50c53a5f1608516a066ec2d3141
3,625,490
from datetime import datetime def capacitytoactivity(trade, outPutFile, input_data): """ builds the CapacityToActivityUnit (Region, Technology, CapacitytoActivityUnit) ------------- Arguments trade, outPutFile, input_data outPutFile: is a string containing the OSeMOSYS parameters file ...
88560b00505c31e8f438206e4ff6da03362df634
3,625,491
import numpy as np def molpos_1Dbin(data,bins,diameter): """Creates a 1D histogram from X,Y location data of a single tracked molecule over time Args: data (pandas dataframe): time series 2D location data of a tracked molecule bins (int): # of rectangular bins to discretize cell with (bin...
fbc05b9c14d82c19f62ae30ec1d05b7e314b57e8
3,625,492
import test def suite(): """ A test suite for the ITU-P Recommendations. Recommendations tested: * ITU-P R-676-9 * ITU-P R-676-11 * ITU-P R-618-12 * ITU-P R-618-13 * ITU-P R-453-12 * ITU-P R-837-6 * ITU-P R-837-7 * ITU-P R-838-3 * ITU-P R-839-4 * ITU-P R-840-4 * ITU-P R...
c1b87ef1781945e0b7ffb3577959176ea28b4469
3,625,493
def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
74c2e4e4188b608120f241aadb20d8480ac84008
3,625,494
def add_ops(op_classes): """ Decorator to add default implementation of ops. """ def f(cls): for op_attr_name, op_class in op_classes.items(): ops = getattr(cls, f"{op_attr_name}_ops") ops_map = getattr(cls, f"{op_attr_name}_op_nodes_map") for op in ops: ...
c2721444a5b211d2d7f3a78c61df3e68e143f3f4
3,625,495
def clear_history_fixture_test(): """define a function that will run each time you pass it to a test, it is called a fixture""" return Calculations.clear_history()
6baac016824cef4d710366f376e4ea3ff2d74990
3,625,496
def get_bool_mask_from_ivar(ivar): """ Return mask determined by pixels that are nonzero in all ivar maps. Parameters ---------- ivar : (..., nsplit, 1, ny, nx) ndmap Inverse variance maps for N splits. Returns ------- mask : (ny, nx) bool enmap Mask, True in ob...
8776e4089dcb612cbe32e58f3a9d654c0a29e938
3,625,497
from typing import Optional def check_if_function_can_be_run( ctx: typer.Context, param: typer.CallbackParam, value: str ) -> Optional[str]: """Callback that validates if a function can be run""" if not is_function_built(value): raise typer.BadParameter( f"Function - '{value}' is not a...
d6cff1f76c41acc7b7a1732536c7b50e2cd217ef
3,625,498
import math def random_rotate(X, y, rotation_range=0): """Randomly rotate centroids and appearances. Args: X (dict): Dictionary of feature data. rotation_range (int): Maximum rotation range in degrees. Returns: dict: Rotated ``X`` data. """ appearances = X['appearances'] ...
ad7b1bd47e4fd5e1cdda6bd6b192df67475ade0f
3,625,499
def decorator_with_default_params(real_decorator, args, kwargs, default_args=None, default_kwargs=None): """ This function makes it easy to build a parametrized decorator, having a default value. Construct your decorator like this: >>> def decorator(*d_args, **d_kwargs): # d_args with d like decorator ...
63e38bbdaea3483250db7281908a0053e072e866
3,625,500
import json import copy def get_args(request, required_args): """ Helper function to get arguments for an HTTP request Currently takes args from the top level keys of a json object or www-form-urlencoded for backwards compatability. Returns a tuple (error, args) where if error is non-null, the...
b44e058590945211ca410005a5be2405b4756ca4
3,625,501
def compute_ndcg_ps_parity_check(scores, labels, topk=10): """ adapter for pps ndcg calculating util :param scores: raw scores :param labels: actual labels, ordered numerically :param topk: default is 10 :return: ndcg score as float """ return compute_ndcg_ps_parity_check_original_api(li...
de49eea462b7562c11fa1bfe5445578a3a739d32
3,625,502
import re def create_table(request): """ 创建餐桌 --- serializer: table.serializers.TableCreateSerializer omit_serializer: false responseMessages: - code: 201 message: Created - code: 400 message: Bad Request - code: 401 message: Not authentic...
25e6a62f26a26014c6f1b972628ed369f7cd14d5
3,625,504
def transl(tx,ty=None,tz=None): """Returns a translation matrix (M) :param float tx: translation along the X axis :param float ty: translation along the Y axis :param float tz: translation along the Z axis """ if ty is None: xx = tx[0] yy = tx[1] zz = tx[2] else: ...
7d79b5db7a64966738171fbcecc4e25f63804cf3
3,625,506
def find_most_sim(mesh, doc_id, top_n=10): """Find documents most similar to the given document.""" doc = mesh.doc_cache[doc_id] results = [] doc_conc = list(map(lambda x: x[1], mesh.graph.out_edges(doc_id))) for other_doc in mesh.doc_cache.values(): if other_doc._.id != doc_id: ...
2eef0091bebb7dd8f4aa1a186020aafb6eefca7c
3,625,508
def split_hosts_list(hosts_list, split_type, log_file=None): """ Return a list of multiple hosts list for the safe deployment. :param hosts_list list: Dictionnaries instances infos(id and private IP). :param split_type: string: The way to split the hosts list(1by1-1/3-25%-50%). ...
e30951f809700246ef142e206ca3a7a3cc89ce90
3,625,509
def load_panel_from_excel(excelfile): """Load a pandas Panel object by reading it from an Excel spreadsheet. :param excelfile: Path to Excel file. :returns: pandas Panel object. """ paneldict = {} xl = pd.ExcelFile(excelfile) for sheet in xl.sheet_names: frame = pd.read_...
e4b2c7a63ed726997fca67fe0521cfe891ff1146
3,625,510
import tqdm import requests def tweets_request(tweets_ids): """ Make a request to Tweeter API """ df_lst = [] for batch in tqdm(tweets_ids): url = "https://api.twitter.com/2/tweets?ids={}&&tweet.fields=created_at,entities,geo,id,public_metrics,text&user.fields=description,entities,id,...
a022504710096393403f6bf806fe2f12d20008be
3,625,512
def prefix_to_netmask(in_prefix): """ Converts a prefix into a netmask :param in_prefix: Cidr prefix n <= 32 :return: Netmask value """ prefix = int(in_prefix) if prefix > 32 or prefix <= 0: return None return IPAddress(inet_ntoa(pack(">I", (0xffffffff << (32 - prefix)) & 0xffff...
387d25ac1d568ebaa285556b5b8e99f964b3ccf9
3,625,513
import itertools def compute_class_correspondence(predicted_domain, true_domain, verbose=True): """Compute the best match of two lists of labels among all permutations.""" def mismatches(domain1, domain2): return (domain1 != domain2).sum() def associate(domain, current_ids, new_ids): new_...
48e71dd115a150a26ece9ec4879b37f3a6699dce
3,625,514
from typing import Union from typing import Optional from typing import Iterable def l2norm( mdata: Union[MuData, AnnData], mod: Optional[Union[Iterable[str], str]] = None, rep: Optional[Union[Iterable[str], str]] = None, n_pcs: Optional[Union[Iterable[int], int]] = 0, copy: bool = False, ) -> Opt...
5a9130e48c2067acf7b366ff18fd5256473acb25
3,625,515
def topsis(df, weights, impacts): """ Validates dataframe, impacts, weights and calculates performance score. Outputs a dataframe with "Performance Score" and "Rank" column appended. """ validate_data(df, weights, impacts) ops_df = df.iloc[:,1:] ## normalized matrix ops_df1 = ops_df ** 2 demoninat...
b8ecf2ee4e8f14a00a9a9a4408cb76f8d1bb1d3c
3,625,516
def mergeGC_genecategories(GC_content_df, gene_categories): """merged GC content df with gene categories""" # read in gene categories gene_cats = pd.read_csv(gene_categories, sep="\t", header=None) gene_cats.columns = ["AGI", "gene_type"] # merge to limit to genes of interest GC_content_categori...
a9b5f67d0fce5106a2c426309b896df8b2e139e1
3,625,517
def noise_lut_range(atracks, xtracks, noiseLuts): """ Parameters ---------- atracks: np.ndarray 1D array of atracks. lut is defined at each atrack xtracks: list of np.ndarray arrays of xtracks. list length is same as xtracks. each array define xtracks where lut is defined noiseL...
23e977eb83de87f1b24d892efc271e823b86ca05
3,625,518
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD...
1d5e99281fdfa642c637fc8d85be86f11456c8b3
3,625,519
def view_shape(shape, view): """Return the shape of a view of an array :param shape: Tuple describing shape of the array :param view: View object -- a valid index into a numpy array, or None Returns equivalent of np.zeros(shape)[view].shape """ if view is None: return shape shp = t...
7b9d5321d84e5ca1f90b0531ca2d0837a90e9153
3,625,520
def get_requester_ip(request): """ Get the IP address from a request """ x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip_addr = x_forwarded_for.split(',')[0] else: ip_addr = request.META.get('REMOTE_ADDR') return ip_addr
f7cde3745fdd40947a1c63068802b0d79584d21d
3,625,521
from typing import Dict def _get_info_source(context) -> Dict: """Returns the current information source""" return context.transaction_data[TransactionLoops.INFORMATION_SOURCE][-1]
d3062d91c4456ed94002acaf92481bdd501a84ad
3,625,523
from datetime import datetime from typing import List def history_snapshot( order_book_id: str, bar_count: int, dt: datetime.datetime, fields: List[str]=None, skip_suspended: bool=True, include_now: bool=False, adjust_type: str="none", adjust_orig:datetime = None, ) -> pd.DataFrame: ...
98b30d3607add30ae8e08e394dc2b7321beb14e9
3,625,524
def determine_header_length(trf_contents: bytes) -> int: """Returns the header length of a TRF file Determined through brute force reverse engineering only. Not based upon official documentation. Parameters ---------- trf_contents : bytes Returns ------- header_length : int ...
e8aa5110691e877c34f208af5bd508f0f5ec4760
3,625,525
import xml def _parse_define(define: xml.etree.ElementTree.Element) -> str: """Parse <define> manifest stanza. Schema: <define name="EXAMPLE" value="1"/> <define name="OTHER"/> Args: define: XML Element for <define>. Returns: str with a value NAME=VALUE or NAME. ...
00f366d7dc969e32431301cce094144e9398e471
3,625,527
import re def _join_lines(source): """Remove Fortran line continuations""" return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source)
9caa3b6f470a96a7b473f3cce12f57d3787e91dd
3,625,528
import decimal from datetime import datetime def fromjson(datatype, value): """A generic converter from json base types to python datatype. """ if value is None: return None if isinstance(datatype, atypes.ArrayType): return fromjson_array(datatype, value) if isinstance(datatype,...
fcbb08948f1f4cf97850c7190d860c4788177858
3,625,529
def format(t): """ function to format the stopwatch time to A:BC.D Returns: the formatted six character string """ A = t/600 t = t - A * 600 # this round function isn't needed when t is an integer CD = round(t/10.0, 1) B = "" if CD < 10.0: B = "0" r...
ad6dc72f0d6b090cf4d94d27e1f0560c58a9f42d
3,625,531
def var(array, axis=None, controller=None): """Returns the variance of all values along a particular axis (dimension). Given an array of m tuples and n components: * Default is to return the variance of all values in an array. * axis=0: Return the variance values of all components and return a one ...
696ab35d107cf758fe0fac2241a00b3167353418
3,625,532
import requests def get_kalliope_bijlage(path, session): """ Perform the API-call to get a poststuk-uit bijlage. :param path: url of the api endpoint that we want to fetch :param session: a Kalliope session, as returned by open_kalliope_api_session() :returns: buffer with bijlage """ r = ...
b2a126b8e33bab50b1e2aa122645d7a45d6dfea9
3,625,533
def validate_dice_seed(dice, min_length): """ Validates dice data (i.e. ensures all digits are between 1 and 6). returns => <boolean> dice: <string> representing list of dice rolls (e.g. "5261435236...") """ if len(dice) < min_length: print("Error: You must provide at least {0} dice rol...
e63922476e66825c159ba94db5eb9e65ae906a40
3,625,534
import re def make_vocab_from_docs(docs): """ Make a dictionary that contains all words from the docs. The order of words is arbitrary. docs: iterable of documents """ vocab_words=set() for doc in docs: doc=doc.lower() doc=re.sub(r'-',' ',doc) doc=re.sub(r' +',' ',doc) ...
6869bae9cbfe1b17a105feb0f3c5a06afa1ec8a0
3,625,535
def filter_by_book_style(bibtexs, book_style): """Returns bibtex objects of the selected book type. Args: bibtexs (list of core.models.Bibtex): queryset of Bibtex. book_style (str): book style key (e.g. JOUNRAL) Returns: list of Bibtex objectsxs """ return [bib for bib in ...
ca3b46772930a6f6e28b6fc0ee4d175ee8d69c3c
3,625,536
def _rmse(a, b, weights, axis): """ Root Mean Squared Error. Parameters ---------- a : ndarray Input array. b : ndarray Input array. axis : int The axis to apply the rmse along. weights : ndarray Input array. Returns ------- res : ndarray ...
77e6296a08d9c8210cb3e1f05d2fc0788a77b2a0
3,625,538
from typing import Counter def cdf_function_5(cd: ChemicalDiagram): """exclusion: all M hydroxide""" env_dict = cd.get_env_dict() def neighboring_hydrogen_count(node): return max( Counter(env_dict[node]["nb_elements"])["H"], Counter(env_dict[node]["nb_elements"])["D"], ...
59e394369d5ec5d9427c79a5a15c01030886fd57
3,625,540
def _ns_tag(ns_id, tag): """Return a namespace/tag item. The ns_id is translated to a full name space via the NS module variable. :param ns_id: The name space ID. Translated to a namespace via the module variable NS :type ns_id: str :param tag: The tag :type str: str """ return...
b5cf6d00c3c4a8afe373e12e7761ba9eba9287aa
3,625,542
def half_size(A, amount=50, interp='bicubic', mode=None): """ nearest, bilinear, bicubic, cubic """ return misc.imresize(A, amount, interp, mode)
97cca97676fd56a90330a877fca3e6b45d347541
3,625,543
def load_labels(lamost_ids, filename='lamost_labels_all_dates.csv'): """ Extracts training labels from file. Assumes that first row is # then label names, first col is # then filenames, remaining values are floats and user wants all the labels. """ print("Loading reference labels from file %s" %fi...
13123d919dd1d2166fe8ce39fcf8727582324c4c
3,625,544
def _create_alb( stack, name: str, vpc: ec2.Vpc, target_group: elbv2.ApplicationTargetGroup ) -> elbv2.ApplicationListener: """Create Application Load Balancer for integration to the service's API""" sg = ec2.SecurityGroup(stack, f'{name}-http-public-sg', vpc=vpc) sg.add_ingress_rule(ec2.Peer.any_ipv4()...
208f03b313acb799690800cb3f613e3eed5d2bfc
3,625,545
import json def load_mock_response(file_name: str) -> dict: """ Load one of the mock responses to be used for assertion. Args: file_name (str): Name of the mock response JSON file to return. """ with open(f'{file_name}', mode='r', encoding='utf-8') as json_file: return json.loads(j...
8385f435bf666e5c5a4636c0f93cf90436f6aff9
3,625,546
def fixedvals_from_searchspaces(params): """Converts any search space hyperparams in params dict into fixed default values.""" if any(isinstance(params[hyperparam], Space) for hyperparam in params): logger.warning("Attempting to fit model without HPO, but search space is provided. fit() will only consid...
a2a2712efd55cab49f9288d800ad15b56580c479
3,625,547
import torch def attributions(scores: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: """Error analysis for antecedent scoring ## Inputs - `scores`: `(batch_size, max_antecedent_number)`-shaped float tensor. The first dimension might be padded with `-float("-inf")` or approximations...
6ce0c443d6e344bfc84565f8f901984904216194
3,625,549
def get_recommendation_and_prediction_from_text(input_text, num_feats=10): """ 플래스크 앱에 출력할 점수와 추천을 구합니다. :param input_text: 입력 문자열 :param num_feats: 추천으로 제시한 특성 개수 :return: 추천과 현재 점수 """ global MODEL feats = get_features_from_input_text(input_text) pos_score = MODEL.predict_proba([f...
f5998c9025beabf13e32f41bee7ff43236f58cc6
3,625,550
def Ct_a(a, F=None, method='Glauert', ac=None): """ High thrust corrections of the form: Ct = Ct(a) see a_Ct """ if F is None: F=np.ones(a.shape) if method=='Glauert': Ct = 4*a*F*(1-a) if ac is None: ac = 1/3 Ic = a>ac Ct[Ic] =4*a[...
9a503e2566e78e149cbc6225edf01841c56a6a7d
3,625,551
def authors_to_string(*authors): """ >>> author1 = {'first': 'S.', 'last': 'Miyamoto'} >>> author2 = {'first': 'K.', 'last': 'Kondo'} >>> author3 = {'first': 'H.', 'last': 'Tanaka'} >>> authors_to_string(author1) 'S. Miyamoto' >>> authors_to_string(author1, author2) 'S. Miyamoto and K. K...
2e6f63954dd6ad9c031eecbc42a39423196baba5
3,625,552
def square_quad_f(x, a, matrix): """ Compute the square of the quadratic function. Parameters ---------- x : 1-D array Point in which the square of the quadratic is to be evaluated. minimizer : 1-D array Minimizer of the square of the quadratic function. matrix : 2-D...
1ff7aafd5d4259bfccd110d4f2880071b8fad18a
3,625,554
def calc_dist_matrix(chain_one, chain_two) : """Returns a matrix of C-alpha distances between two chains""" ''' an example chain_one = chain chain_two = chain''' answer = np.zeros((len(chain_one), len(chain_two)), np.float) for row, residue_one in enumerate(chain_one) : for col, residue...
88e12fdc9511c445a998c66d82a2aa3a51545c08
3,625,555
def compare_sequence(old, new): """Compare two Seq or DBSeq objects.""" assert len(old) == len(new), "%i vs %i" % (len(old), len(new)) assert str(old) == str(new), "%s vs %s" % (old, new) if isinstance(old, UnknownSeq): assert isinstance(new, UnknownSeq) else: assert not isinstance(...
bee02d5c4af5ea7faf7b30dcfca2f1ee1174c47a
3,625,556
def _get_slope(x, y): """ Retrun the slope of x and y data, using scipy.signal.linregress """ slope = linregress(x, y) return slope
14882f8cd604c0360c3f75c6c0c065a5344c9855
3,625,558
def get_spans(tokens, tags): """Convert tags to textspans.""" spans = tags_to_spans(tags) text_spans = [ x[0] + ": " + " ".join([tokens[i] for i in range(x[1][0], x[1][1] + 1)]) for x in spans ] if not text_spans: text_spans = ["None"] return text_spans
fa23e1164e6753652a123412879760529a675626
3,625,559
def applyPCA(data_points,pcaComponents): """Apply PCA to a list of values Parameters ---------- data_points : numpy.ndarray Array of type numpy.ndarray. pcaComponents : int Number of components to be used in PCA analysis. Returns Array of t...
65b2d4e9c29dfc8e4c7d44c83ed761c69c55127e
3,625,560
import requests import json def delete_account(Id, token: str): """Deletes the account resource.""" headers = Header(token) URL = "https://api.mail.tm/accounts/"+Id response = requests.delete(url=URL, headers=headers.header) if response.status_code == 204: return response.status_code ...
9d173aca8968af511059734d9adb2e959527bfe8
3,625,561
import json def load_quran_obj_from_json(input_json_path): """ Loads the Json object containing Qur'anic data from the specific path. """ try: with open(input_json_path, 'rb') as quran_json_file: # Import json file and return Qur'an object. return json.load(quran_json_...
708b873bb5694472585ce05924a8262fe60de77e
3,625,562
import json import requests def get_company_info(secret1, secret2, symbol): """ scrapes data (currently from alphavantage) and returns the response in json format Arguments: secret1: one of the API keys to scrape data secret2: a second API key to scrape data symbol: synonymous to...
145230e4cefd062c14bad11cc09344354d9701f9
3,625,563
from typing import Union def cyclic_digraph(n: int = 3, metadata: bool = False) -> Union[sparse.csr_matrix, Bunch]: """Cyclic graph (directed). Parameters ---------- n : int Number of nodes. metadata : bool If ``True``, return a `Bunch` object with metadata. Returns -----...
fae1c67831a1bc151b05ec123c5d069fb4a3da40
3,625,564
def is_wildcard_query(query): """ Checks if provided query selects using a * wildcard :type query str :rtype bool """ if not is_select_query(query): return False query = preprocess_query(query) tokens = get_query_tokens(query) last_token = None for token in tokens: ...
b952850f6f5eb4fcc7155889ab7da4d6b97f7900
3,625,565
import random def random_val(index, tune_params): """return a random value for a parameter""" key = list(tune_params.keys())[index] return random.choice(tune_params[key])
1cf7ba9d1a3ff651f946a8013e338d62f4fec3ab
3,625,566
def read_envvar_file(name, extension): """ Read values from a file provided as a environment variable ``NAME_CONFIG_FILE``. :param name: environment variable prefix to look for (without the ``_CONFIG_FILE``) :param extension: *(unused)* :return: a `.Configuration`, possibly `.NotConfigu...
6717f9f442d3693878c213cbb1a6c0276d86ac3a
3,625,567
def take_while(array, callback=None): """Creates a slice of `array` with elements taken from the beginning. Elements are taken until the `callback` returns falsey. The `callback` is invoked with three arguments: ``(value, index, array)``. Args: array (list): List to process. callback (m...
b00f3c43c769022443d8a19af739eb7a263cca20
3,625,568
import tokenize def build_model(): """ Using grid search, builds the model to classify the messages Returns: model (): The trained model over the data """ # text pipeline text_pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ...
d874cba5c06483963bd60d360ac5a972ca0d54f0
3,625,569
def extract_cutted_data_and_timesteps_from_given_indexes(dataframe_indexes, dict_instances, result_data_shape, result_timesteps_shape): """This function extracts data and labels in window format via corresponding indexes located in dataframe_indexes Cut format is needed for train recurrent models. The techni...
a1c256f48f16be94e8b67c1d7d407513fdda6764
3,625,570
def git_version_specifier(refspec, branch, commit, tag): """ Return the minimal set of specifiers that the user input reduces to, in a dict of variables for Ansible. :param refspec: provided refspec like 'pull/1/head' :param branch: provided branch like 'master' :param commit: provided commit S...
9b723b44f3bad03a74b78a10153f4d6120202fc6
3,625,572
import socket def receive_bytes(socket: socket.socket, buffer_size: int) -> str: """ Receives the specified number of bytes from the specified socket @param socket - the socket from which to receive @param buffer_size - the number of bytes to receive @return - string """ receiver_buffe...
bb28fa45641596a02f6e325e3a62ccc51c9f9905
3,625,573
def roulette_selection(population, pop_fitness, select_n, config): """ Metoda selekcji ruletki Minimalizujemy wartośc funkcji dopasowania, co jest podejściem odwrotnym do standardowego. By moc poprawnie zastosowac algorytm selekcji ruletki wykorzystujemy odwrocone wartosci funkcji. W celu rozproszen...
ac187093f9b22329449fffd0773b0d408089218a
3,625,574
def create_additional_front_points(pt6x, pt7x, pt14x, pt9z, pt15x, pt8z, pt14z, pt9x, pt8x, pt15z): """Create pot surface points to create faces--Nameing them 21(L)-22(R) to not collide with current fuel vert numbers""" # Left point pt20x = pt6x pt20z = pt14z pt20y = 0 # Right point pt21x = ...
c6e021c4ce1bf514be80b60558e6152c571da68c
3,625,575